message:
2.4" TFT LCD Shield isn't working on Arduino Mega

Even on ebay's [website][1] it is mentioned that I can't use 2.4" TFT LCD Shield display on attach to Arduino Mega. The problem is that I bought this shield by mistake. I want to put this shield onto Arduino Mega 2560. Is there a way to combine Mega and 2.4" Display Shield?

note: I tried on my friend's Arduino Uno. Shield is working very good.

note: The photo below is determining my question. The display not runs my Arduino's code. It only runs its LED.

![enter image description here][2]

  [1]: http://www.ebay.com/itm/2-4-TFT-LCD-Shield-Touch-Panel-Display-TF-Reader-For-Arduino-UNO-R2-R3-A137-/390631788477
  [2]: https://i.stack.imgur.com/DGkHU.jpg

        // UTFT_Demo_320x240 (C)2012 Henning Karlsen
    // web: http://www.henningkarlsen.com/electronics
    //
    // This program is a demo of how to use most of the functions
    // of the library with a supported display modules.
    //
    // This demo was made for modules with a screen resolution
    // of 320x240 pixels.
    //
    // This program requires the UTFT library.
    //

    #include <UTFT.h>
    #define ILI9320_16 18
    // Declare which fonts we will be using
    extern uint8_t SmallFont[];

    // Uncomment the next line for Arduino 2009/Uno
    //UTFT myGLCD(UNO_24,A2,A1,A3,A4);   // Remember to change the model parameter to suit your display module!

    // Uncomment the next line for Arduino Mega
    UTFT myGLCD(ILI9320_16,38,39,40,41);   // Remember to change the model parameter to suit your display module!

    void setup()
    {
      randomSeed(analogRead(0));

    // Setup the LCD
      pinMode(A0,OUTPUT);  // for the UNO_SHIELD_1IN1
      digitalWrite(A0,HIGH); // the RD pin must be set high
      myGLCD.InitLCD();
      myGLCD.setFont(SmallFont);
    }

    void loop()
    {
      int buf[318];
      int x, x2;
      int y, y2;
      int r;

    // Clear the screen and draw the frame
      myGLCD.clrScr();

      myGLCD.setColor(255, 0, 0);
      myGLCD.fillRect(0, 0, 319, 13);
      myGLCD.setColor(64, 64, 64);
      myGLCD.fillRect(0, 226, 319, 239);
      myGLCD.setColor(255, 255, 255);
      myGLCD.setBackColor(255, 0, 0);
      myGLCD.print("* Universal Color TFT Display Library *", CENTER, 1);
      myGLCD.setBackColor(64, 64, 64);
      myGLCD.setColor(255,255,0);
      myGLCD.print("<http://electronics.henningkarlsen.com>", CENTER, 227);

      myGLCD.setColor(0, 0, 255);
      myGLCD.drawRect(0, 14, 319, 225);

    // Draw crosshairs
      myGLCD.setColor(0, 0, 255);
      myGLCD.setBackColor(0, 0, 0);
      myGLCD.drawLine(159, 15, 159, 224);
      myGLCD.drawLine(1, 119, 318, 119);
      for (int i=9; i<310; i+=10)
        myGLCD.drawLine(i, 117, i, 121);
      for (int i=19; i<220; i+=10)
        myGLCD.drawLine(157, i, 161, i);

    // Draw sin-, cos- and tan-lines
      myGLCD.setColor(0,255,255);
      myGLCD.print("Sin", 5, 15);
      for (int i=1; i<318; i++)
      {
        myGLCD.drawPixel(i,119+(sin(((i*1.13)*3.14)/180)*95));
      }

      myGLCD.setColor(255,0,0);
      myGLCD.print("Cos", 5, 27);
      for (int i=1; i<318; i++)
      {
        myGLCD.drawPixel(i,119+(cos(((i*1.13)*3.14)/180)*95));
      }

      myGLCD.setColor(255,255,0);
      myGLCD.print("Tan", 5, 39);
      for (int i=1; i<318; i++)
      {
        myGLCD.drawPixel(i,119+(tan(((i*1.13)*3.14)/180)));
      }

      delay(2000);

      myGLCD.setColor(0,0,0);
      myGLCD.fillRect(1,15,318,224);
      myGLCD.setColor(0, 0, 255);
      myGLCD.setBackColor(0, 0, 0);
      myGLCD.drawLine(159, 15, 159, 224);
      myGLCD.drawLine(1, 119, 318, 119);

    // Draw a moving sinewave
      x=1;
      for (int i=1; i<(318*20); i++)
      {
        x++;
        if (x==319)
          x=1;
        if (i>319)
        {
          if ((x==159)||(buf[x-1]==119))
            myGLCD.setColor(0,0,255);
          else
            myGLCD.setColor(0,0,0);
          myGLCD.drawPixel(x,buf[x-1]);
        }
        myGLCD.setColor(0,255,255);
        y=119+(sin(((i*1.1)*3.14)/180)*(90-(i / 100)));
        myGLCD.drawPixel(x,y);
        buf[x-1]=y;
      }

      delay(2000);

      myGLCD.setColor(0,0,0);
      myGLCD.fillRect(1,15,318,224);

    // Draw some filled rectangles
      for (int i=1; i<6; i++)
      {
        switch (i)
        {
          case 1:
            myGLCD.setColor(255,0,255);
            break;
          case 2:
            myGLCD.setColor(255,0,0);
            break;
          case 3:
            myGLCD.setColor(0,255,0);
            break;
          case 4:
            myGLCD.setColor(0,0,255);
            break;
          case 5:
            myGLCD.setColor(255,255,0);
            break;
        }
        myGLCD.fillRect(70+(i*20), 30+(i*20), 130+(i*20), 90+(i*20));
      }

      delay(2000);

      myGLCD.setColor(0,0,0);
      myGLCD.fillRect(1,15,318,224);

    // Draw some filled, rounded rectangles
      for (int i=1; i<6; i++)
      {
        switch (i)
        {
          case 1:
            myGLCD.setColor(255,0,255);
            break;
          case 2:
            myGLCD.setColor(255,0,0);
            break;
          case 3:
            myGLCD.setColor(0,255,0);
            break;
          case 4:
            myGLCD.setColor(0,0,255);
            break;
          case 5:
            myGLCD.setColor(255,255,0);
            break;
        }
        myGLCD.fillRoundRect(190-(i*20), 30+(i*20), 250-(i*20), 90+(i*20));
      }

      delay(2000);

      myGLCD.setColor(0,0,0);
      myGLCD.fillRect(1,15,318,224);

    // Draw some filled circles
      for (int i=1; i<6; i++)
      {
        switch (i)
        {
          case 1:
            myGLCD.setColor(255,0,255);
            break;
          case 2:
            myGLCD.setColor(255,0,0);
            break;
          case 3:
            myGLCD.setColor(0,255,0);
            break;
          case 4:
            myGLCD.setColor(0,0,255);
            break;
          case 5:
            myGLCD.setColor(255,255,0);
            break;
        }
        myGLCD.fillCircle(100+(i*20),60+(i*20), 30);
      }

      delay(2000);

      myGLCD.setColor(0,0,0);
      myGLCD.fillRect(1,15,318,224);

    // Draw some lines in a pattern
      myGLCD.setColor (255,0,0);
      for (int i=15; i<224; i+=5)
      {
        myGLCD.drawLine(1, i, (i*1.44)-10, 224);
      }
      myGLCD.setColor (255,0,0);
      for (int i=224; i>15; i-=5)
      {
        myGLCD.drawLine(318, i, (i*1.44)-11, 15);
      }
      myGLCD.setColor (0,255,255);
      for (int i=224; i>15; i-=5)
      {
        myGLCD.drawLine(1, i, 331-(i*1.44), 15);
      }
      myGLCD.setColor (0,255,255);
      for (int i=15; i<224; i+=5)
      {
        myGLCD.drawLine(318, i, 330-(i*1.44), 224);
      }

      delay(2000);

      myGLCD.setColor(0,0,0);
      myGLCD.fillRect(1,15,318,224);

    // Draw some random circles
      for (int i=0; i<100; i++)
      {
        myGLCD.setColor(random(255), random(255), random(255));
        x=32+random(256);
        y=45+random(146);
        r=random(30);
        myGLCD.drawCircle(x, y, r);
      }

      delay(2000);

      myGLCD.setColor(0,0,0);
      myGLCD.fillRect(1,15,318,224);

    // Draw some random rectangles
      for (int i=0; i<100; i++)
      {
        myGLCD.setColor(random(255), random(255), random(255));
        x=2+random(316);
        y=16+random(207);
        x2=2+random(316);
        y2=16+random(207);
        myGLCD.drawRect(x, y, x2, y2);
      }

      delay(2000);

      myGLCD.setColor(0,0,0);
      myGLCD.fillRect(1,15,318,224);

    // Draw some random rounded rectangles
      for (int i=0; i<100; i++)
      {
        myGLCD.setColor(random(255), random(255), random(255));
        x=2+random(316);
        y=16+random(207);
        x2=2+random(316);
        y2=16+random(207);
        myGLCD.drawRoundRect(x, y, x2, y2);
      }

      delay(2000);

      myGLCD.setColor(0,0,0);
      myGLCD.fillRect(1,15,318,224);

      for (int i=0; i<100; i++)
      {
        myGLCD.setColor(random(255), random(255), random(255));
        x=2+random(316);
        y=16+random(209);
        x2=2+random(316);
        y2=16+random(209);
        myGLCD.drawLine(x, y, x2, y2);
      }

      delay(2000);

      myGLCD.setColor(0,0,0);
      myGLCD.fillRect(1,15,318,224);

      for (int i=0; i<10000; i++)
      {
        myGLCD.setColor(random(255), random(255), random(255));
        myGLCD.drawPixel(2+random(316), 16+random(209));
      }

      delay(2000);

      myGLCD.fillScr(0, 0, 255);
      myGLCD.setColor(255, 0, 0);
      myGLCD.fillRoundRect(80, 70, 239, 169);

      myGLCD.setColor(255, 255, 255);
      myGLCD.setBackColor(255, 0, 0);
      myGLCD.print("That's it!", CENTER, 93);
      myGLCD.print("Restarting in a", CENTER, 119);
      myGLCD.print("few seconds...", CENTER, 132);

      myGLCD.setColor(0, 255, 0);
      myGLCD.setBackColor(0, 0, 255);
      myGLCD.print("Runtime: (msecs)", CENTER, 210);
      myGLCD.printNumI(millis(), CENTER, 225);

      delay (10000);
    }

body:
You need to compare the pins' functions between your Mega and your friend's Uno. Then you need to make those electrical connections happen. I talk about this a little in the "pin locations" section of [my answer here][1].

This requires "hacking". Something needs to be done to reroute those physical connections. I normally use an intermediate shield to translate pins as needed. There was a shield specifically made for this purpose but I couldn't find it. [Maybe this one would work][2]?

  [1]: https://arduino.stackexchange.com/questions/462/which-are-the-competitors-of-the-arduino-boards/476#476
  [2]: http://www.dfrobot.com/index.php?route=product/product&path=123_124&product_id=990#.U071vPldX_M


sender: user

sender: assistant

body:
A way to proceed is to create a spreadsheet showing the pin positions used by this board, and the Arduino shield signals they plug into. Next to these, you need columns showing the actual signals on the ATMega2560 (for Mega2560) and ATMega328 (for Uno) that these shield pins attach to. You can get this info from the Uno and Mega2560 schematic drawings.

In a quick look, it seems that the Arduino shield pin names for Uno and Mega are the same: for example, shield pin '0' (digital zero) is in the same location on both boards, and likewise for other pins.

However, on the Uno digital-0 attaches to ATMega328 Port D bit 0, while on the Mega2560, it attaches to ATMega2560 Port E bit 0. And things get more obtuse with digital 2..7.

Now, when twiddling bits individually using digitalWrite(pin, value), the Arduino library no doubt takes care of translating to the appropriate port/bits that need to be set for the ATMega chip and Arduino board that's in use. However, libraries that use lower-level functions (especially if they need to write entire bytes to ports, as a fast LCD library might) will need to take their own steps to make this translation.

So... first step is to determine whether there is a separate LCD driver library for Mega2560.

Next, investigate whether the library you have has initialization code that is supposed to determine what board it's running on (and is your board included?), or requires you to set some flag to tell it what board is in use.

Failing that, you _could_ create a mess of jumpers or some other wiring scheme to jumper the Mega's ATMega2560's signals so that it's wired up like a Uno would be. It's not clear that this is possible, since some of ATMega2560's Port D is not even wired to a header.

Or you could look at the source code for the library and see what it's actually doing, and what it would need to do different to operate the ATMega 2560 pins that the shield does connect to.


body:
Have you checked out the Library homepage? [Henning Karlsen's library page][1]

  [1]: http://www.henningkarlsen.com/electronics/library.php?id=51

He has made a user manual for the library. There is also a reference to what pin goes where in the requirements document.


body:
I just happened to buy the same LCD Shields a few days ago, looking for a library to use it with a MEGA 2560 board I found https://github.com/Smoke-And-Wires/TFT-Shield-Example-Code which supports both **UNO** and **MEGA** boards.

Usage is very, simple if we want to use it for **MEGA** we should change the header `#include "uno_24_shield.h"` in **SWTFT.cpp** to `#include "mega_24_shield.h"`

**Description (useful for adding suppport for the shield in other libraries):**

Incompatibility comes from different Port mappings for Arduino pin-out between Mega and UNO.

in **UNO** LCD shield will be connected through:

    +---------------+-----+-----+-----+-----+-----+-----+-----+-----+
    | LCD Data Bit  |  7  |  6  |  5  |  4  |  3  |  2  |  1  |  0  |
    +---------------+-----+-----+-----+-----+-----+-----+-----+-----+
    | Digital pin # |  7  |  6  |  5  |  4  |  3  |  2  |  9  |  8  |
    +---------------+-----+-----+-----+-----+-----+-----+-----+-----+
    | Uno port/pin  | PD7 | PD6 | PD5 | PD4 | PD3 | PD2 | PB1 | PB0 |
    +---------------+-----+-----+-----+-----+-----+-----+-----+-----+

in **MEGA** it will be connected through:

    +---------------+-----+-----+-----+-----+-----+-----+-----+-----+
    | LCD Data Bit  |  7  |  6  |  5  |  4  |  3  |  2  |  1  |  0  |
    +---------------+-----+-----+-----+-----+-----+-----+-----+-----+
    | Digital pin # |  7  |  6  |  5  |  4  |  3  |  2  |  9  |  8  |
    +---------------+-----+-----+-----+-----+-----+-----+-----+-----+
    | MEGA port/pin | PH4 | PH3 | PE3 | PG5 | PE5 | PE4 | PH6 | PH5 |
    +---------------+-----+-----+-----+-----+-----+-----+-----+-----+


message:
It is possible to program Linino to send HTTP requests and then use the returned values in sketch?

I am new to using Arduino Yun and I would like to know if it is possible to run a command from the Arduino sketch in order to make (probably, through the Bridge Library) Linino to execute a HTTP Request to a remote server. Then I would like to know if it is possible to use the returned values in that Arduino sketch.

In other words, I would like to delegate the task of retrieving values from the web to the Linux side and the usage of the retrieved data to the sketch.

If it is possible, how to do that?

body:
Take a look at [Bridge example][1] or [TemperatureWebPanel example][2]: you see you can receive kind of "commands" and react "doing things".

Then take a look at [HTTP Client example][3], where you delegate an HTTP call to the linux side.

Now mix the two: you can make HTTP calls after receiving a command from outside your Yun.

A short test can be done by cutting and pasting the examples above.

  [1]: http://arduino.cc/en/Tutorial/Bridge
  [2]: http://arduino.cc/en/Tutorial/TemperatureWebPanel
  [3]: http://arduino.cc/en/Tutorial/HttpClient


message:
It is possible to run an entire script on the Linux side? If so, how, what and where to do that?

I am new to using Arduino Yun and I would like to know if it is possible to run an entire script on the Linux side. In my case the script should execute a HTTP request to a remote server, parse the subsequent HTTP response and return some value that then can be used in the Arduino sketch.

If it is possible, what I have to do? For example, how should I write and run script files? what programming language should I use? where I should put those script files on the Linux side?

body:
Arduino Yun ships with python pre installed. You can copy python scripts from your pc to the yun with `scp` (or WinSCP or `putty`, if you're on windows). Once copied, just run it using Process from your sketch. As they are scripts, program name is `python` and the path to your script is its first argument (you can do that in a different way, but that would require some linux magic, which I suggest to postpone if you're new to it).

Other pre installed options include [lua][1] and bash. Other languages such as ruby, erlang and php are available as optional packages.

  [1]: http://www.lua.org/


message:
Use an Arduino as a user interface for the computer

I wanted to use either Arduino Mega or Uno as a form of an interface between me and the computer. I want to apply it to the following scenario; if I press a button on a circuit board I want it to trigger an action on my computer, like scroll down.

How can I achieve this? How would the code look like and what programs would I need to translate from Arduino to Windows?

body:
You can do that easily with a few of the Arduino boards that have built-in USB communications support.

You find that feature on Leonardo, Micro, Esplora and Due boards. You also find that on some Arduino compatible boards like the Adafruit Flora.

Simply plug the Arduino USB port to your computer and the Arduino will behave like a keyboard. Then you can program your sketch to perform what you want with your buttons. Check the Arduino  [mouse and keyboard library][1].

  [1]: http://arduino.cc/en/Reference/MouseKeyboard#.Uxt6yuddVTY


body:
Arduino Yun, Leonardo, Esplora and Due have  the ability to appear as a native Mouse and/or Keyboard to a connected computer by use of the [Mouse and Keyboard libraries][1].

Here's an example of how you would use SWITCH3 on the Esplora to active PAGE UP on your keyboard.

    if (!Esplora.readButton(SWITCH_3)) {
      Keyboard.press(KEY_PAGE_UP)
      delay(100);
      Keyboard.releaseAll();
      }

[Here's an example][2] of using the Esplora to control the Keyboard and Mouse to control the Flight Simulator option of Google Earth.

If you want to use the Uno it's more difficult but it can be done by sending data from the Uno to a Python program running on the PC. The Python program uses the pywin library to control windows.

[Here's a fully worked out Instructable][3] on how to do it.

  [1]: http://arduino.cc/en/Reference/MouseKeyboard#.Uxt-kIWzBzw
  [2]: http://www.instructables.com/id/Arduino-Esplora-Flight-Simulator/
  [3]: http://www.instructables.com/id/Flight-Simulator-with-Arduino-and-Python/


body:
For the sake of completeness, on the more traditional boards where the USB interface is not implemented from the main "sketch" processor, there are three other potential possibilities:

 - Use the (USB) serial data interface, and have software on the host computer which accepts commands over that.  Obviously, the downside is requiring installation of something on the host system - installation which may require admin privileges or even disabling code signing requirements in some cases (especially if it is to inject the data into the host operating system as if it came from a keyaboard)

 - On boards such as the Uno and comparable-generation Mega which use a secondary ATmega "u" series part as a USB-serial converter, this chip can be reprogrammed to act instead as a keyboard.  That could make loading sketches tricky - though it might be possible to come up with a dual-mode firmware that could switch roles under control of an external hardware or software signal.

 - The main ATmega "sketch" processor can generally implement a "not quite compliant, but workable" *approximation* of a low-speed USB interface *in software* on arbitrary I/O pins with some external matching/protection componenets.  A USB keyboard is a common demo application of that.


message:
Accessing Arduino Yun from Internet

I am trying to access my Arduino Yun from the internet, and it's not quite working. I have correctly port forwarded the port 5555 from the router to the Yun (verified I am able to access my many other NAT'd resources).

I can access the Yun from my internal network.

In the Arduino sketch I have this (among many other things). Mainly taken from example sketches.

    #include <Bridge.h>
    #include <HttpClient.h>
    #include <YunServer.h>
    #include <YunClient.h>

    YunServer server;

    void setup {
       // Listen for incoming connections on port 5555
       server.noListenOnLocalhost();
       server.begin();
    }
Is `server.noListenOnLocalhost();` the right one to use to access from the outside world?

body:
Well, I'm not familiar with the Yun, but the first thing that stands out is the missing

    Bridge.begin();

line apparently needed to initialize the Bridge library that you use.

And you do have something like

    YunClient client = server.accept();

and "more" in the main loop (or a function where applicable) of your code, right ?

And yes, `noListenOnLocalhost()` is the correct function for serving external clients.


message:
Calibrating Accelerometer Sensor

I'm working with an Adafruit LSM303DLHC Accelerometer Sensor hooked up to an Arduino.  I've downloaded the appropriate libraries to make it work and uploaded the example sketch "accelsensor.pde".  I then placed my sensor at rest on a flat surface and obtained the following acceleration vector values on average, in units of meters per second:

    X: -0.24  Y: -0.71  Z: 10.47

At rest, each of these three values fluctuate approximately +-0.04 on average.

As I see it, the values are off a bit.  At rest, the X and Y components should hover closer to 0m/s^2 while the Z component should be closer to 9.8m/s^2.

What is the best way to compensate for this biased measurement?  Should I simply add back the average observed bias?  Or is there a more robust method to calibrate the sensor values?

body:
there are varius calculation.

At the end of the day, if take a point in every position (under no acceleration), you should end up with a sphere, or matematically speacking, wthe lenght of the vector should be equal to gravity, so `sqrt(x*x+y*y+z*z) = G` or, to do less computing `x*x+y*y+z*z = G*G` (same apply for magnetometer, but using local magnetic force, or gyroscope, using a know-speed rotation like a LP player)

To create that spere you have to take many point, and find a multiplicator (or function) for each axes. That is particualary important when one axes has differnet precision of others, you are `linearizing` the axis output, and then `normalizig` its value relative to others axes.

Once you have corrected the vector lenght to have a spere, you should look at the offset of the sphere; if its `center` point is not on the `origin` point 0,0,0 then the differece between `center` and `origin` is the correction you talk about. This is offset correction.

Also many (well, all) sensor are affected on their temperature; many claim to be "thermocompensated", that means this difference is less evident due to some some sort of hardware and/or software filtering.


body:
To get rid of the fluctuation, you could always try a moving average. It isn't hard to modify the `Smoothing` example (under `File->Examples->1. Analog->Smoothing`) to accept accelerometer values.

As for the slight offset in the X & Y values, that is probably because your sensor isn't sitting perfectly flat.


message:
How can Arduino control with a servo with only one wire?

I was playing with getting my servos to be on dedicated power, separate form the Arduino entirely, but obviously controlled by the Arduino. I originally had the ground of the Arduino joined with the `-` of the battery, but to my surprise my Arduino continued to control the servos when I remove the ground wire entirely from the Arduino.

I was under the impression that all electricity must form a complete circuit, and be a closed loop. But my Arduino can obviously send a signal to a component that has no return path to itself.

I feel like I'm missing something fundamental about a electricity. So my question is:

**Why does this work?**

![arduino setup][1]

  [1]: https://i.stack.imgur.com/n37I0.jpg

body:
The return signal is probably the other wire's servo. This only works when the control pulses to both servos are not in sync. Pull one signal wire off the breadboard and both servos will stop working.

You need to interconnect grounds or you will get strange effects sooner or later.


message:
Why does command line BOSSA not recognize Arduino Due?

Running Ubuntu 12.04.4 LTS (64 bit) I try to upload my code to the Arduino Due through the Native port. I have tried both the `bossac` that ships with the Arduino IDE (which is a modified version of BOSSA), and the master BOSSA branch.

Running this command:

    sudo ./bossac -p /dev/ttyACM0

I get this error:

    No device found on /dev/ttyACM0

However, it works perfectly inside the Arduino IDE.

What can the problem be?

body:
from the IDE's menu you can activate the verbose upload (and compile) mode, that will print all the command executed; Probabibly what you miss is the necessity to open the serial at 1200baud, that will trigger the reboot and consequent bootloader's start ont DUE chip, and bossac need to find the bootloader. see [autoReset][1]

edit: i've now a pc with a physical Serial, so i've tryed to upload in verbose mode:

    Sketch uses 10,380 bytes (1%) of program storage space. Maximum is 524,288 bytes.
    Forcing reset using 1200bps open/close on port /dev/ttyS0
    /home/xxx/arduino-1.5.6-r2/hardware/tools/bossac -i -d --port=ttyS0 -U false -e -w -v -b /tmp/build8035422101690460839.tmp/sketch_apr14a.cpp.bin -R
as you can see he is resetting the board by opening the serial at 1200, forcing the bootloader to start. You have to do the same on your script befor launching bossac. How this can be done depends on your OS

Please note that the reset is triggered by the 8u2 chip used as USB to serial adapter on the arduino board, so bypassing it by connecting through tx/rx pin (like using your own conversor, like in my example with hardware serial) won't work unless you do a manual reset at the right time

  [1]: http://arduino.cc/en/Guide/ArduinoDue#toc4


body:
Easiest way I've found to do this purely from the terminal:

    stty -f /dev/cu.usbmodemfa121 1200;stty stop /dev/cu.usbmodemfa121;./bossac -i -d --port=tty.usbmodemfa121 -U false -e -w -v -b Blink.cpp.bin -R

Swap out the serial device for whatever /dev you are using; in Linux you may have to sudo to get direct access to the device.
This is assuming you are in the directory where bossac lives and your .bin file is there too. Adjust to suit your needs.
If using the native USB port you should change -U to *true*


body:
The Arduino CLI uses a slightly different version of bossa from the one that is on master:

https://github.com/shumatech/BOSSA/tree/arduino

On Linux, I was able to do the following:

    $ git clone git@github.com:shumatech/BOSSA.git
    $ cd BOSSA
    $ make bin/bossac -j4
    $ stty -F /dev/ttyACM0 1200
    $ ./bin/bossac --port=/dev/ttyACM0 --force_usb_port=true -e -w -v -b /path/to/my/firmware.bin -R

(I got the answer from [this Arduino forum thread][1].)

  [1]: https://forum.arduino.cc/index.php?topic=150195.0


message:
How do I use 2 ultrasonic sensors to control a 5v motor?

I've hooked up two ultrasonic sensors to my breadboard and I also got a 5v motor installed. I also got the diode installed and the usual set up. I can easily control the motor with one sensor.

But what I'm trying to do is I want the motor to run at let's say 100 once I start it up:

- The first sensor should be used to slowly slow down the motor when an object is placed in front of it
- The second sensor should be used to slowly speed up the motor when an object is placed in front of it

**I do not want the speed to return to 100 once the object is removed.** It should remain at the same speed according to which sensor was used. (Tell me if I have to clarify anything in the comments)

Code

    int motorPin = 9;
    int trigPin = 13;
    int echoPin = 12;
    int trigPin2 = 5;
    int echoPin2 = 4;

    void setup() {
      Serial.begin (9600);
      pinMode(trigPin, OUTPUT);
      pinMode(echoPin, INPUT);
      pinMode(trigPin2, OUTPUT);
      pinMode(echoPin2, INPUT);
      pinMode(motorPin, OUTPUT);
    }

    void loop() {
      int duration, distance;
      digitalWrite (trigPin, HIGH);
      delayMicroseconds (1000);
      digitalWrite (trigPin, LOW);
      duration = pulseIn (echoPin, HIGH);
      distance = (duration/2) / 29.1;
      if (distance < 20) {  // Distance from sensor
        analogWrite (motorPin, 50);
      } else {
        int duration, distance;
        digitalWrite (trigPin2, HIGH);
        delayMicroseconds (1000);
        digitalWrite (trigPin2, LOW);
        duration = pulseIn (echoPin2, HIGH);
        distance = (duration/2) / 29.1;
        if (distance > 20) {  // Distance from sensor
          analogWrite (motorPin, 150);
        }
        if  (distance > 20) {  // Distance from sensor
          Serial.println("Out of range");
        } else {
          Serial.print(distance);
         Serial.println(" cm");
        }
        delay(500);
      }
    }

body:
This is *very* simple using the **[`map()` instruction](http://arduino.cc/en/reference/map).** Here's the code you would use (feel free to modify values:

    int speed = 112 + map(distance, 0, 20, 0, 112) - map(distance2, 0, 20, 0, 112);

So if both sensors gave equal values, they would offset each other. To make it still work if an object is removed, you could just use the last `distance`/`distance_2` value and update the other.
****
One issue with this approach is, if the line of transformation of the object is *not* perpendicular to the line of the pings, the value will go:
> 10 → 11 → 12 → 13 → 14 → 15 → 16 → 17 → 18 → 19 → 20 → [Out of range]

**I've added some pretty animations to show you what I mean:**

Perpendicular:

Collinear:

****
As I understand, this is what you want:

    int motorPin = 9;
    int trigPin = 13;
    int echoPin = 12;
    int trigPin2 = 5;
    int echoPin2 = 4;
    int postdist = 112;
    int postdist2 = 112;

    void setup() {
      Serial.begin (9600);
      pinMode(trigPin, OUTPUT);
      pinMode(echoPin, INPUT);
      pinMode(trigPin2, OUTPUT);
      pinMode(echoPin2, INPUT);
      pinMode(motorPin, OUTPUT);
    }

    void loop() {
      //First Read
      int duration, distance;
      digitalWrite (trigPin, HIGH);
      delayMicroseconds (1000);
      digitalWrite (trigPin, LOW);
      duration = pulseIn (echoPin, HIGH);
      distance = (duration/2) / 29.1;
      int ltol = postdist - 5;
      int htol = postdist + 5;
      if (distance > 20 || !(distance > ltol && distance < htol)) {  // Distance from sensor
        Serial.println("Out of range");
        distance = postdist;
      }
      //Second Read
      int duration2, distance2;
      digitalWrite (trigPin2, HIGH);
      delayMicroseconds (1000);
      digitalWrite (trigPin2, LOW);
      duration2 = pulseIn (echoPin2, HIGH);
      distance2 = (duration2/2) / 29.1;
      int ltol2 = postdist2 - 5;
      int htol2 = postdist2 + 5;
      if (distance2 > 20 || !(distance2 > ltol2 && distance2 < htol2)) {  // Distance from sensor
        Serial.println("Out of range");
        distance2 = postdist2;
      }
      //Math:
      Serial.print("Distances-1: ");
      Serial.print(distance);
      Serial.print(" cm 2: ");
      Serial.print("Distances-1: ");
      Serial.print(distance2);
      Serial.println(" cm");
      postdist = distance;
      postdist2 = distance2;
      int speed = 112 + map(distance, 0, 20, 0, 112) - map(distance2, 0, 20, 0, 112);
      if(speed < 60) {speed = 60;} //Modify 60 to meet your needs for minimum threshold
      analogWrite (motorPin, speed);
      Serial.print("Motor Speed: ");
      Serial.println(speed);
      delay(500);
    }

**Changelog:** forgot to edit `postdist`/`postdist2` at end of cycle, added minimum threshold, prevent very small changes in voltage to keep voltage stable and prevent noise.


message:
Replicate a Waveform Exactly with An Arduino Uno

So I've got a waveform that's high for 16ms and low for 2ms repeating forever. I need to recreate that and offsets of that waveform time exactly on a different pin. Right now, I've got an interrupt on the rising edge for the 16ms low/high transistion, and delayMicroseconds() that determines the offset and duration of the high and low pulses. Trouble is, I'm not sure the code I have is as fast and accurate as it could be. And the replicated waveform seems to shift through the full period of the original one. I need it to be locked in.Any suggestions?
Here is the code:

     //3 is interrupt for Timing
    //4 through 11 are Time dependent receivers
    //3-11 Pins 12-19
    char incomingByte = 0;

    int pins[9] =
    {
      3,4,5,6,7,8,9,10,11
    };

    void timing()
    {
      //Serial.println("This is a 0ms Event");
     // if(Serial.available() > 0)
     // {
        incomingByte = Serial.read();
        Serial.print("I received");
        Serial.println(incomingByte);

         pinMode(10, OUTPUT);
         digitalWrite(10, HIGH);
         delayMicroseconds(16000);
          digitalWrite(10, LOW);
          delayMicroseconds(2000);
          digitalWrite(10, HIGH);
     }
    //}

    void setup() {
      // put your setup code here, to run once:

    for(int i=0;i<8;i++)
    {
      pinMode(pins[i], INPUT);
    }
    pinMode(3,INPUT);
    attachInterrupt(1,timing,RISING);

    //Begins Serial
    Serial.begin(115200);
    }

    void loop() {
      // put your main code here, to run repeatedly:
    }

Here's the waveform I'm trying to duplicate:

![Desired Waveform][1]

  [1]: https://i.stack.imgur.com/dkxhW.png

body:
If you're looking to speed your code up I would recommend not using `digitalWrite` or `Serial`. When using digitalWrite it can take quite a few unneeded clock cycles to turn the pin on or off, as a replacement I would suggest looking into using [port manipulation][1].

Example of turning a pin on or off with a preprocessor macro using port manipulation

    #define DIGITAL_WRITE_10_HIGH() PORTB = PORTB | B00000100     // Town ON only pin 10
    #define DIGITAL_WRITE_10_LOW() PORTB = PORTB & ~B00000100     // Turn OFF only pin 10

Using port manipulation in your code:

    #define DIGITAL_WRITE_10_HIGH() PORTB = PORTB | B00000100     // Town ON only pin 10
    #define DIGITAL_WRITE_10_LOW() PORTB = PORTB & ~B00000100     // Turn OFF only pin 10

    void timing()
    {
        //incomingByte = Serial.read(); // If needed uncomment, but it's slow
        //Serial.println(incomingByte); // If needed uncomment, but it's slow

         // Set pinMode in setup()
         DIGITAL_WRITE_10_HIGH();
         delayMicroseconds(16000);
         DIGITAL_WRITE_10_LOW();
         delayMicroseconds(2000);
         DIGITAL_WRITE_10_HIGH();
     }

  [1]: http://arduino.cc/en/Reference/PortManipulation


body:
This code is wrong in many ways.

first of all, `timing()` is execute inside an interrupt, this mean that while it is running, all other interrupt and timer stop (delayMicroseconds works because it does not rely on timer, but on know instruction execution time). That mean you have to keep the interrupt funzion faster as possible, or bad things may and will happen. (microseconds still work because it is based on know instruction duration in loop)

For example, Serial is interrupt driven; this may cause a race condition that will freeze the code.

As far as i can understand pin 3 may be a button (in that case you need to apply some antibounce code, just look at the signal create by pressing a button with your oscilloscope to see what happen), so you can just make a digitalRead every loop, if true do your code. So you will keep `timing()` out of interrupt.

`pinMode()` only needs to be set once, in `setup()`. Also, `digitalRead()` is really slow: operating directly on the register is a lot faster! see [port manipulation][1]

but in your case i would delete all precendent code and do some math to use an ad-hoc PWM, so you will be almost code free and because it will be almost all done by hardware, precision and possible granularity will increase, see [secret of arduino PWM][2]

  [1]: http://arduino.cc/en/Reference/PortManipulation
  [2]: http://arduino.cc/en/Tutorial/SecretsOfArduinoPWM


message:
TCP communication between Arduino client and server

I'm currently trying to build an Arduino robot controlled via a wifi connection. I have an Arduino Mega running as a client and it successfully connects to the server on LAN via the Adafruit cc3000 wifi board. However instead of grabbing the contents of the JSON file and printing it to serial, I'm just getting a 100 continue response. While this means I'm doing something right, I don't know what to do next in order to grab the data I need. Do I need to get the 100 message then respond with the GET request, or is there a way that I can GET the data straight away?

Thank you all in advance. Here is the Arduino code I have so far:

    #include <Adafruit_CC3000.h>
    #include <ccspi.h>
    #include <SPI.h>
    #include <string.h>
    #include "utility/debug.h"
    #include <stdlib.h>

    // These are the interrupt and control pins
    #define ADAFRUIT_CC3000_IRQ 3  // MUST be an interrupt pin!
    #define ADAFRUIT_CC3000_VBAT 5 // Apparently these can be any two pins
    #define ADAFRUIT_CC3000_CS 10  // But I wouldn't change these...
    // Use hardware SPI for the remaining pins (On a Mega 2560, SCK = 52, MISO = 50, and MOSI = 51)
    Adafruit_CC3000 cc3000 = Adafruit_CC3000(ADAFRUIT_CC3000_CS, ADAFRUIT_CC3000_IRQ, ADAFRUIT_CC3000_VBAT, SPI_CLOCK_DIV2);

    #define WLAN_SSID "VM540258-2G"
    #define WLAN_PASS "XXXXXXXX"
    #define WLAN_SECURITY WLAN_SEC_WPA2

    String readString = String(100); //string for fetching data from address
    uint32_t ip = 3232235523; // This translates into the ip address we need
                              // 323223552X; 192.168.0.X

    void setup(){
      Serial.begin(115200); //Can also work at 9600

      //Initialise CC3000 module
      Serial.println(F("\nInitializing CC3000..."));
      if (!cc3000.begin())
      {
        Serial.println(F("Couldn't begin()! Check your wiring?"));
        while(1);
      }
      //Connect to the Wireless Access Point
      if (!cc3000.connectToAP(WLAN_SSID, WLAN_PASS, WLAN_SECURITY)) {
        Serial.println(F("Failed!"));
        while(1);
      }

      Serial.println(F("Connected!"));

      Serial.println(F("Request DHCP"));
      while (!cc3000.checkDHCP()) { //Obtain IP addeess
        delay(100);
      }

      while (! displayConnectionDetails())
      {
        delay(1000);
      }
    }

    void loop(){
      Adafruit_CC3000_Client client = cc3000.connectTCP(ip, 80);

      if (client.connected()) {
        client.println("GET /project-test/state.json HTTP/1.0"); //Make a request for state.json
        client.println(""); //Mandatory blank line?
        if (client.available()){
          char c = client.read();
          Serial.print(c);
          //read char by char HTTP request
          if (readString.length() < 100) {
           //store characters to string
           readString += c;
          }
        }
      }
      //Once we have obtained the data, disconnect from the server
      client.close();
      Serial.println(readString);
      delay(1000);
    }

    bool displayConnectionDetails(void)
    {
      uint32_t ipAddress, netmask, gateway, dhcpserv, dnsserv;

      if(!cc3000.getIPAddress(&ipAddress, &netmask, &gateway, &dhcpserv, &dnsserv))
      {
        Serial.println(F("Unable to retrieve the IP Address!\r\n"));
        return false;
      }
      else
      {
        Serial.print(F("\nIP Addr: ")); cc3000.printIPdotsRev(ipAddress);
        Serial.print(F("\nNetmask: ")); cc3000.printIPdotsRev(netmask);
        Serial.print(F("\nGateway: ")); cc3000.printIPdotsRev(gateway);
        Serial.print(F("\nDHCPsrv: ")); cc3000.printIPdotsRev(dhcpserv);
        Serial.print(F("\nDNSserv: ")); cc3000.printIPdotsRev(dnsserv);
        Serial.println();
        return true;
      }
    }

The initial JSON file I'm using contains the following:

    {"speed_left":null,"speed_right":null,"direction_left":null,"direction_right":null}

And the serial output I get when I run the Sketch:

    Initializing CC3000...
    Started AP/SSID scan

    Connecting to VM540258-2G...Waiting to connect...Connected!
    Request DHCP

    IP Addr: 192.168.0.7
    Netmask: 255.255.255.0
    Gateway: 192.168.0.1
    DHCPsrv: 192.168.0.1
    DNSserv: 192.168.0.1

    Connect to 192.168.0.3:80
    100

    Connect to 192.168.0.3:80
    100
ad infinitum

body:
you are missing the `HOST` header in the request, so the server tell you to `100 CONTINUE` you request.
Also yes, the final empty row IS mandatory

for example, to ask `www.example.com/index.html`

    GET /index.html HTTP/1.1
    Host: www.example.com


body:
I'm going to guess that it's a problem with your server not expecting an HTTP/1.0 request.  I note the following from RFC 1945 about the response codes:

> 9.1  Informational 1xx
>
>   This class of status code indicates a provisional response,
>   consisting only of the Status-Line and optional headers, and is
>   terminated by an empty line. HTTP/1.0 does not define any 1xx status
>   codes and they are not a valid response to a HTTP/1.0 request.
>   However, they may be useful for experimental applications which are
>   outside the scope of this specification.

I'd recommend changing your request to be HTTP/1.1 compliant (with a Host: header as suggested by @lesto)


body:
Okay, I have a better answer, again done without testing.

If I look at the BNF for an HTTP-message from the RFC, it indicates that the message body is terminated by a blank line.

So, you actually need 2 CRLFs (i.e. 2 blank lines).  The first one separates the headers from the body of the HTTP request.  You don't actually have a message body (which is fine, it is optional).  But, you'll need another CRLF to terminate the (blank) body.

Since you only sent one blank line, the server is sending you the continue status codes, prompting you to finish sending your message (i.e. the message body).

So, try adding another client.println("");


message:
How do I use the timers on an Arduino Uno R3?

I want to make a simple circuit which returns the time/delay between two, consecutive loud sounds (i.e, a mic reading of ~600) coming from a speaker. I have set up and ADMP 401 microphone for this purpose. How do I measure the time it takes for this application?

body:
Your question is probably not as simple as it may seem.

One approach I would use if I was to address this same problem would consist in:

1. converting the analog output of the mike into a digital value (based on a threshold to determine)
2. connect this digital signal to one Arduino pin that can trigger an interrupt when its level changes

Let's first start with the easy part: Arduino program.

Let's say we have a digital signal that raises to 1 as soon as a sound of too high amplitude is captured by the mike; it shall stay 1 as long as the sound does not reduce amplitude enough. We will connect this signal to Arduino pin 3; then we can use `attachInterrupt()` to have a function called whenever this pon level raises to 1:

    volatile static bool started = false;
    volatile static unsigned long timing = 0;
    volatile static bool finished = false;

    void loud() {
        if (started) {
            timing = micros() - timing;
            started = false;
            finished = true;
        } else {
            timing = micros();
            started = true;
            finished = false;
        }
    }

    void setup() {
        pinMode(3, INPUT);
        attachInterrupt(1, loud, RAISE);
    }

    void loop() {
        if (finished) {
            // Do something with timing
        }
    }

Now the hardest part: electronics!

A first issue we have to deal with is related to the fact that the raw mike signal will have same wave shape as the sound it captures, this wave has a frequency that can vary between 10Hz (bass) and 20KHz (treble).

Indeed, if we convert the mike analog output to a logical value (`1` when the analog value is above a threshold we'll call `Vt`, `0` when it is under `Vt`) fast enough, then, if the environmental sound as an amplitude above `Vt`, the logical input connected to your Arduino will oscillate at the same frequency as the sound! This would make our efforts pointless as you would measure the period of the sound wave instead of the elapsed time between two distinct sound bursts.

That means that we should probably first "smoothen" the analog sound signal in order to avoid disturbance of its frequency.

Hence point 1 will have to deal with these 2 aspects:

- smoothen analog input value
- compare smoothened value with `Vt` threshold and provide a logical value from this comparison

Comparison can rather easily be performed by an [op-amp][1] used as a comparator.

However, the main difficulty you may have with an op-amp is the need for a symetric voltage supply (e.g. +5V/-5V) although it is possible to use a single supply but that raises further limitations (outside the scope of my answer).

Smoothening the signal is potentially more complex, although it can be done with a simple capacitor, because smoothening the signal generally means weakening it, thus you would lose the initial amplitude of the sound signal.

So how can we deal with that?

A [Schmitt trigger][2] is probably a good solution for this problem but further experiment will be needed to confirm that.

  [1]: http://en.wikipedia.org/wiki/Operational_amplifier
  [2]: http://en.wikipedia.org/wiki/Schmitt_trigger


body:
When you mentions "loud sounds (i.e, a mic reading of ~600)" I'm guessing that means you've successfully connected the mic to an ADC input and you are referring to analog readings, right?  (If not you may need to clarify).  I won't worry about scaling or offset biasing the inputs, assuming you have that part down and you can test the Analog input to detect loudness.

If your Arduino can be dedicated to making this measurement (ie: doesn't need to do anything else while doing it), then the simplest solution might be a loop comparing the ADC input with some threshold you have determined, and using micros() to check the time different.  The micros() function has only 4 uS resolution, but the loop time will add more time than that anyway, and actually the limited bandwidth of your audio signals (speaker and mic both) will make any microsecond level measurement suspect anyway.  So the simple loop might be as accurate as you need.

For example:

    const int THRESHOLD = 600; // adjust
    const int MINDELAY = 1000;  // adjust

    long
    takeMeasurement() {
        while(analogRead(A4) < THRESHOLD); // wait for first trigger
        long start = micros();
        delayMicroseconds(MINDELAY); // let first noise die down
        while(analogRead(A4) < THRESHOLD); // wait for second trigger
        return micros() - start;
    }

You would call this function when you were ready to take a measurement.  To keep the loop time short (when it's waiting for a loud sound), it has no timeout, so it won't return until it does detect two loud sounds.  Depending on your need, you might need to change that and have an escape from the loops.  There are several ways that might be done:

* test for micros() exceeding some timeout within the loop

* decrement a counter in the loop and exit if it goes to zero (or if the sound is detected)

* test a flag (volatile byte) in the loop, which gets set by a timer interrrupt

Which is best depends on other aspects of your overall design.


message:
Connection problem with Arduino Mega 2560 and GSM shield ( official M10)

As I don't want to stack the shield over the mega 2560 board, I try to connect only the pins that used for GSM communication. Here are my connection:

Pin 3 on Mega <==> Pin GSM Rx on Shield

Pin 10 on Mega <==> Pin GSM Tx on Shield

Pin 4 on Mega <==> Pin 4 on Shield

Pin 5V on Mega <==> Pin Vin on Shield

Pin GRD on Mega <==> Pin GRD on Shield

Code I used is from the Examples library, GsmScanNetworks:

    #include <GSM.h>

    // PIN Number
    #define PINNUMBER "8888"

    // initialize the library instance
    GSM gsmAccess;     // include a 'true' parameter to enable debugging
    GSMScanner scannerNetworks;
    GSMModem modemTest;

    // Save data variables
    String IMEI = "";

    // serial monitor result messages
    String errortext = "ERROR";

    void setup()
    {
      // initialize serial communications and wait for port to open:
      Serial.begin(9600);
      while (!Serial) {
        ; // wait for serial port to connect. Needed for Leonardo only
      }

      Serial.println("GSM networks scanner");
      scannerNetworks.begin();

      // connection state
      boolean notConnected = true;

      // Start GSM shield
      // If your SIM has PIN, pass it as a parameter of begin() in quotes
      while(notConnected)
      {
        if(gsmAccess.begin(PINNUMBER)==GSM_READY)
          notConnected = false;
        else
        {
          Serial.println("Not connected");
          delay(1000);
        }
      }

      // get modem parameters
      // IMEI, modem unique identifier
      Serial.print("Modem IMEI: ");
      IMEI = modemTest.getIMEI();
      IMEI.replace("\n","");
      if(IMEI != NULL)
        Serial.println(IMEI);
    }

    void loop()
    {
      // scan for existing networks, displays a list of networks
      Serial.println("Scanning available networks. May take some seconds.");
      Serial.println(scannerNetworks.readNetworks());

        // currently connected carrier
      Serial.print("Current carrier: ");
      Serial.println(scannerNetworks.getCurrentCarrier());

      // returns strength and ber
      // signal strength in 0-31 scale. 31 means power > 51dBm
      // BER is the Bit Error Rate. 0-7 scale. 99=not detectable
      Serial.print("Signal Strength: ");
      Serial.print(scannerNetworks.getSignalStrength());
      Serial.println(" [0-31]");

    }

Questions:

 1. After opening the serial port, only a line "GSM network scanner" is read. Seems that the program is stuck on`gsmAccess.begin(PINNUMBER)`, how shall I fix that?
 2. Is it a must that I shall supply 5V 2A power to the shield seperately in order for the shield to work? (with connection mentioned above, the ON led light on the shield does turns on with an orange light)
 3. For the PINNUMBER defined in the program, my SIM has default PIN 8888. I checked with a mobile phone that the SIM card does work. But my phone shows that the SIM card is not locked with PIN. So shall I define the PIN as 8888 for ''?

EDIT:

[GSM shield link][1]

[Note for using GSM shield with Mega][2]

*** And yes! The shield did work when stacked! (Orginally I don't want to bend pin 2...but...unnh...stacking and bending out pin 2 did work)

*** Tried the examples "GSMScanNetwork" and "SendSMS", works fine. But for "GsmWebServer", an IP address is shown, but when I enter the IP address on my browser, chrome/ie says they cannot find the IP address.....Any clues?

*** And does the status LED on the GSM board have anything to do with power? It goes on and off and on and off.....

*** For question 1 & 3, PINNUMBER is set to ''. Worked fine.

  [1]: http://arduino.cc/en/Guide/ArduinoGSMShield
  [2]: http://arduino.cc/en/Guide/GSMShieldLeonardoMega

body:
I have done this, and had (some limited) success.

A couple of your connections are wrong;
Connect both the pin 7s on the shield and MEGA, not the pin 4s. Pin 7 is the reset pin - I think that GSM.begin resets the shield before doing anything. This might help with Q1.

Make sure that you use the regulated 5V output on the MEGA, and not the Vin to power your shield. Vin is whatever voltage is connected to the MEGA power socket, and could damage your shield. I personally have not noticed any difference when powering the MEGA+Shield from USB or external 12V supply.

I had problems with interference when I used wires to connect shield to MEGA. The stacking seems to have reduced this problem, but not eliminated it by any means...

The GSM Web server is unlikely to work except maybe from within your SIM provider's own network. Some of the limitations are mentioned here;
https://www.arduino.cc/en/Tutorial/GSMToolsTestWebServer


message:
Ethernet shield programming

This is first time programming with Ethernet shield . I want to test the web server application with my Arduino. I have an Arduino Uno, Ethernet shield, and a potentiometer. Below code being uploaded.

Question are:

 - Currently I am using LAN connection to configure. How to configure it? Is internet required for below application?
 - How do I check the output?
 - Is there any software where i can make customized tags?
 - I have values coming from the serial port to be monitored on webserver. Can someone share how to monitor it?

![Manually configured for windows 7][1]
![After config][2]
![][3]

[Ethernet shield][4]

    #include <SPI.h>
    #include <Ethernet.h>

    // Enter a MAC address and IP address for your controller below.
    // The IP address will be dependent on your local network:
    byte mac[] = {
      0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
    IPAddress ip(192,168,1,177);

    // Initialize the Ethernet server library
    // with the IP address and port you want to use
    // (port 80 is default for HTTP):
    EthernetServer server(80);

    void setup() {
     // Open serial communications and wait for port to open:
      Serial.begin(9600);
       while (!Serial) {
        ; // wait for serial port to connect. Needed for Leonardo only
      }

      // start the Ethernet connection and the server:
      Ethernet.begin(mac, ip);
      server.begin();
      Serial.print("server is at ");
      Serial.println(Ethernet.localIP());
    }

    void loop() {
      // listen for incoming clients
      EthernetClient client = server.available();
      if (client) {
        Serial.println("new client");
        // an http request ends with a blank line
        boolean currentLineIsBlank = true;
        while (client.connected()) {
          if (client.available()) {
            char c = client.read();
            Serial.write(c);
            // if you've gotten to the end of the line (received a newline
            // character) and the line is blank, the http request has ended,
            // so you can send a reply
            if (c == '\n' && currentLineIsBlank) {
              // send a standard http response header
              client.println("HTTP/1.1 200 OK");
              client.println("Content-Type: text/html");
              client.println("Connection: close");  // the connection will be closed after completion of the response
          client.println("Refresh: 5");  // refresh the page automatically every 5 sec
              client.println();
              client.println("<!DOCTYPE HTML>");
              client.println("");
              // output the value of each analog input pin
              for (int analogChannel = 0; analogChannel < 6; analogChannel++) {
                int sensorReading = analogRead(analogChannel);
                client.print("analog input ");
                client.print(analogChannel);
                client.print(" is ");
                client.print(sensorReading);
                client.println("
");
              }
              client.println("");
              break;
            }
            if (c == '\n') {
              // you're starting a new line
              currentLineIsBlank = true;
            }
            else if (c != '\r') {
              // you've gotten a character on the current line
              currentLineIsBlank = false;
            }
          }
        }
        // give the web browser time to receive the data
        delay(1);
        // close the connection:
        client.stop();
        Serial.println("client disconnected");
      }
    }

  [1]: https://i.stack.imgur.com/De3WX.jpg
  [2]: https://i.stack.imgur.com/HDDWk.jpg
  [3]: https://i.stack.imgur.com/yDM0O.jpg
  [4]: http://arduino.cc/en/Main/ArduinoEthernetShield

body:
You need to determine what the network address is of the LAN you have connected the arduino to. A router can often give you this information. Alternatively you can connect a computer to the same network and look at the computers network settings (this varies depending on what OS you use). Then you have determine what IP address is available on that network. You will enter this in the ip variable in your example.

The internet is not required for your application, however you do need the arduino to be connected to a LAN and another device (probably a standard computer) to invoke the arduinos server behaviour.

To test that it works, you can open an internet browser on the second device and type in the IP address that you have configured for the arduino into the address bar.


message:
Serial data plotting programs

I need to plot serial data from Arduino.

I require support for:

 1. Various data formats (e.g. signed, unsigned, 8 bits, 16 bits);
 2. Plots several data on the same axes;
 3. Exports / Imports file data.

As plotting serial data from Arduino is a common need, my question is:
What programs/utilities are available for plotting serial data from Arduino that meet the needs above?

What are the advantages / disadvantages of the method you have suggested?

body:
Responding to my own question here.. I use Bridge Control Panel as mentioned.

Advantages: Lots of Features.

Disadvantages: Tricky to setup and very poor syntax/error reporting.

To use:
You need to write the Arduino Data over the Serial Port one byte at a time. For an int data type that would look as follows:

    // RX8 [h=43] @1Key1 @0Key1
    Serial.print("C");
    Serial.write(data>>8);
    Serial.write(data&0xff);

In Bridge the command to Read Data is:

    RX8 [h=43] @1Key1 @0Key1

RX8 is the read command
[h=43] means the next valid byte is "C" in ASCII
then the High Byte of Key1
then the Low Byte of Key1

It looks like this in Bridge:

![enter image description here][1]

![enter image description here][2]

  [1]: https://i.stack.imgur.com/wO2vf.png
  [2]: https://i.stack.imgur.com/BBQqC.png


body:
I use [Matplotlib][1] for any plotting I need to do.

It's not arduino specific in any way, but it is a very excellent *Python* plotting toolkit.

I've built a number of applications that plot data from a variety of microcontrollers in real-time to a graph, but that was really more of a two-step process: 1. Get data from device into computer, 2. plot realtime data.

Really, I think you should break your question into two parts:

 - How do you get data from an Arduino/Any serial device into a computer easily.
 - What is a good plotting library that is easy to use.

  [1]: http://matplotlib.org/


body:
[GnuPlot](http://www.gnuplot.info/)

 Advantages: It's very flexible, scriptable, and freely available.

Disadvantages: A bit complex to learn (but I figured out how to get started in a few minutes, and quite functional in an hour or two), runs in a terminal window (if you consider that a disadvantage).

Something I found very useful was to script it to reload my terminal program's logfile periodically so i got a dynamic graph as my experiment progressed.

![Image of GnuPlot][1]

Edit: Here is the GnuPlot script that plots it:

    #!/usr/local/bin/gnuplot -rv
    # Note reverse video here ^^^   til I find a way to put it in the script

    # gpFanCtl - Plots DiffThermo fan controller data (aloft, alow, Tdiff, fan-state).
    # $Id: gpFanCtl,v 1.8 2014-04-28 09:40:51-04 jrobert Exp jrobert $

    set terminal x11 1 noraise
    set xtics 3600
    set mxtics 4
    set xdata time

    set ytics 1 nomirror
    set mytics 2

    set y2range [0:3]
    set y2tics 1
    set my2tics 4

    set grid
    set ylabel 'Temperature, degC'
    set y2label 'Tdiff, degC' textcolor rgb '#00CD63'

    cd '/Users/jrobert/Desktop'
    plot "Logfile.txt" using ($0*4):1 title "Aloft" with lines lc rgb "red",\
         "Logfile.txt" using ($0*4):2 title "Alow" with lines lc rgb "#3982FF",\
         "Logfile.txt" using ($0*4):3 title "Tdiff" with lines lc rgb "#00CD63" axis x1y2,\
         "Logfile.txt" using ($0*4):4 title "Fan" with lines lc rgb "orange" axis x1y2;
    pause 4
    refresh
    reread

  [1]: https://i.stack.imgur.com/r5x4O.png


body:
You can use [MATLAB Student Edition][1],
this can save your time for further analysis, too.
You can just open the COM port in MATLAB and plot the received signal and/or save the signal in the workspace or whatever. MATLAB makes everything easy!

  [1]: http://www.mathworks.com/academia/student_version/


body:
I made an equivalent tool in python that print real time data from ADXL345 accelerometer.
https://github.com/mba7/SerialPort-RealTime-Data-Plotter

may be it will be helpful for someone

![enter image description here][1]

  [1]: https://i.stack.imgur.com/b1Ywo.png

Just choose the serial com and speed and sent a serial data on the following format:

- 3 inputs, every input is a 2 bytes (Two's complement )
- 6 bytes seperated by a space
- the packet is a string terminated by '\n'

Could be easily adapted to change this format


body:
You can try **[serialchart](https://code.google.com/p/serialchart/)**. It's pretty strait forward program. It does exactly what you asked. The only disadvantage is that it requires data in CSV format (does not meet first point).

Screenshot from project page:

![example](https://i.stack.imgur.com/7I9kA.png)


body:
While I haven't used it myself, ["rqt_plot"][1] running on the PC seems to be a popular way to plot data on a PC that comes over a serial port from an Arduino running a sketch that includes the [rosserial_arduino][2] library or the [ros_arduino_bridge][3] library.

* [Arduino Oscilloscope Tutorial][4]
* [rosserial arduino][5]
* [visualize everything using rqt_plot... my first arduino micro ros project][6]
* "7/24: Now that I have the Arduino set up using Kessel, I can [visualize the data better using ROS tools][7]"
* etc.

  [1]: http://wiki.ros.org/rqt_plot
  [2]: http://wiki.ros.org/rosserial_arduino
  [3]: https://github.com/hbrobotics/ros_arduino_bridge
  [4]: http://wiki.ros.org/rosserial_arduino/Tutorials/Arduino Oscilloscope
  [5]: http://answers.ros.org/question/28548/rosserial-arduino/
  [6]: http://defendtheplanet.net/2014/05/21/ultrasonic-sensor-hc-sr04-as-a-ros-range-publisher/
  [7]: http://bdml.stanford.edu/Main/NikhilLeleSummer


body:
There are some good applications for visualizing the serial data, including:

 - [MegunoLink][1] ($39.95; [Lite][2] free) - plotting, logging, programming, reporting and more.

   [![MegunoLink][3]][1]

 - [Electric UI][4] ($80; free for students) - cross platform, fully featured code based GUI framework for hardware.

   [![Electric UI][5]][4]

 - [MakerPlot][6] ($59) - digital & analog plotting, monitoring, custom interfaces and more.

   [![MakerPlot][7]][6]

 - [ArduinoPlot][8] (free) - simple plotting.

   [![ArduinoPlot][9]][8]

 - [arduino-plotter][10] (free) - easy, light-weight plotting with support for all primitive types

   [![arduino-plotter][11]][10]

 - [Bridge Control Panel][12] (free) - logging, plotting, and more.

   [![Bridge Control Panel][13]][12]

 - [RealtimePlotter][14] (free) - 6 channels data plotting.

   [![RealtimePlotter][15]][14]

 - [SimPlot][16] (free) - 4 channel plotting.

   [![SimPlot][17]][16]

 - Arduino Serial Plotter (free) - built in [Arduino Editor][18] under *Tools > Serial Plotter*.

   [![Arduino Serial Plotter][19]][18]

(This is a community wiki, you can expand the list.)

  [1]: https://www.megunolink.com/
  [2]: https://www.megunolink.com/megunolink-lite/
  [3]: https://i.stack.imgur.com/YLakU.png
  [4]: https://electricui.com/features
  [5]: https://electricui.com/web_static/plot_examples.gif
  [6]: http://www.makerplot.com/
  [7]: https://i.stack.imgur.com/Nsmeb.jpg
  [8]: https://github.com/gregpinero/ArduinoPlot
  [9]: https://i.stack.imgur.com/jdTmK.png
  [10]: https://github.com/devinaconley/arduino-plotter
  [11]: https://www.dropbox.com/s/2mtg5ig7lyrrffi/plotter_preview.gif?raw=1
  [12]: https://www.infineon.com/cms/en/design-support/tools/programming-testing/psoc-programming-solutions/
  [13]: https://i.stack.imgur.com/rQjHY.jpg
  [14]: https://github.com/sebnil/RealtimePlotter
  [15]: https://i.stack.imgur.com/3okhi.png
  [16]: https://github.com/infomaniac50/projectsimplot/releases
  [17]: https://i.stack.imgur.com/YqoOn.jpg
  [18]: https://docs.arduino.cc/software/ide-v2/tutorials/ide-v2-serial-plotter
  [19]: https://docs.arduino.cc/f155cf7066d171d7b88b80f3c921e7b1/potentiometer_plotter.gif


body:
CSV format is most versatile for any data (signed/unsigned, various size and precision).

Cross-platform (written in Java/Scala) tool [Scsvlog][1] can receive/parse CSV strings from serial port / socket, show values and draw charts (up to 8).

  [1]: https://github.com/tardigrade888/scsvlog


body:
You can try out the software I developed for that propose. It's aimed to be easy to use. See [SerialGraphicator][1] - Open Source Free Serial Port Client capable of graph values that are received in JSON format.

  [1]: https://github.com/newtonis/SerialGraphicator/


body:
Almost useful. It needs:

 1. logging serial data to a file OR
 2. graphing from a file and updating every xxx milliseconds.

[Live Graph][1] is a better option and I use it in conjunction with [Tera Term][2] which gets the data via the USB/serial link (and saves it to a log file which then Live Graph polls).

Live Graph is slightly buggy when caching data and I haven't found a way to set a moving window to display results. Also, showing multiple graphs requires manual scaling, but in spite of all this, it's still very useful. It's written in java so you'll need the JRE. I prefer this over having to install python like some of the other graphing programs do. another downside is that it opens 4 different windows, which is a pain when I want to flip between it and Tera Term.

I've yet to find software that's

 1. An executable (.EXE) so it has no external reliance
 2. Includes a terminal emulator or serial data logger
 3. Logs serial data
 4. Graphs multiple items from a CSV
 5. Allows for CSV AND tab-delimited data (which is way easier to read as it scrolls along while *simultaneously* monitoring the graph.
 6. Allows setting of different scales for each overlaid graph without having to scale everything to [0..1] or setting a multiplier, i.e. allowing setting an [y0..y1] range for each item graphed.

  [1]: http://live-graph.sourceforge.net/
  [2]: https://ttssh2.osdn.jp/index.html.en


body:
Nobody had mentioned Processing which is super versatile. You can do a lot more than just plotting but if that's all you want to do you can use the gwoptics library; hook up Arduino and Processing as directed [here][1].

  [1]: https://learn.sparkfun.com/tutorials/connecting-arduino-to-processing


body:
You might be interested in `Telemetry` [See on Github](https://github.com/Overdrivr/Telemetry) . It is a communication protocol, highly simple to use, with a clean interface, that enables bidirectionnal communication with Arduino/Mbed devices.

If you don't want to read this long post, see [*A walkthrough of all the awesome features in it*][4]

The power of this library comes from the desktop command line interface (that requires **no** programming skills in python).

It is able to open high-performance plots (much higher that what can be done with matplotlib) **just by typing a command**.

The protocol supports **complexes data structures**. For now **arrays** and sparse arrays can be send from the embedded board.

The plots opened from the command line interface understand the type of data, and for arrays, rather than plotting each sample versus time, sample will be plotted against its own index.

In a near future, it is planned to add **support for spatial coordinates** (xyz data), that will allow you to plot immediately spatial data. Once, again the plots will figure everything out, plot your data in 2D or 3D space and you can focus on developping your app.

I believe those features are simply **unique** for such a project.

Pytelemetry CLI [![PyPI version](https://badge.fury.io/py/pytelemetrycli.svg)](https://badge.fury.io/py/pytelemetrycli)
---------------

Once installed with `pip`, the command line can be started with

    pytlm

Then you can `connect`, `ls`(list) received topics, `print` data received on a topic, `pub`(publish) on a topic, or open a `plot` on a topic to display received data in real-time

[![enter image description here][1]][1]

[![enter image description here][2]][2]

# Get started
[Wiki][3]

*PS : I am the author.*

I developed it because I could not find a solution that would allow me to:

 - write quickly PC scripts to control an Arduino
 - debug quickly
 - plot complex data (not just a time varying value)

all of the above without using proprietary solutions or bloated GUIs.

Using this library, the time to setup a communication between Arduino and PC went from usually half a day to 5 minutes.

  [1]: https://i.stack.imgur.com/Exo7a.png
  [2]: https://i.stack.imgur.com/q3rvr.png
  [3]: https://github.com/Overdrivr/Telemetry/wiki
  [4]: https://github.com/Overdrivr/Telemetry/wiki/Awesome-features-overview


body:
I know this is a very old question, but I recently created a mac application that solves this problem very well. You can find more information about it on www.bloonapp.com. There are some demo videos on the website that you can check out.[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/GiB7R.jpg


body:
I know you were probably after more advanced GUI output, but I managed to replicate a task that one would normally do with an oscilloscope:
[![Arduino Serial Plotter output][1]][1]

using the serial plotter in the Arduino IDE and an ADC module you can get for $3 on eBay. I admit it's a bit crude, but it might be worth playing with the tool for a while, before you invest in Python/Matlab/ect level solutions. It was exceedingly easy to use. It would not take much to add SD card recording to the process.

See: [https://edwardmallon.wordpress.com/2016/08/15/using-the-arduino-uno-as-a-basic-data-acquisition-system/][2]

  [1]: https://i.stack.imgur.com/VhOIW.jpg
  [2]: https://edwardmallon.wordpress.com/2016/08/15/using-the-arduino-uno-as-a-basic-data-acquisition-system/


body:
[SerialPlot][1] (free).  It does everything you require and much more.

Other features:

 - Zoom in on data
 - Click on datapoints to see values
 - Send commands back to Arduino
 - Adjust total number of points plotted
 - Ability to show each channel in its own autoscaled plot
 - Interprets binary, ASCII and custom packets
 - Demo mode lets you play with features

[![enter image description here][2]][2]

  [1]: https://hackaday.io/project/5334-serialplot-realtime-plotting-software
  [2]: https://i.stack.imgur.com/xvQlV.png


body:
[Telemetry Viewer][1]

Advantages:

 1. Easy to use
 2. Intuitive and flexible UI
 3. Open Source and free
 4. Different types of Graphs
 5. Very fast graph update rate

Disadvantages:

 1. Stopped development
 2. Binary data format is not complete yet.
 3. Primitive graph controls like zoom, screenshot and ...
[![enter image description here][2]][2]

  [1]: http://www.farrellf.com/
  [2]: https://i.stack.imgur.com/Y1FBk.png


body:
[SVisual][1] Monitoring and recording of signals for Arduino and not only.

[![enter image description here][5]][5]
[![enter image description here][2]][2]

[Video example][3]

[Download (free)][4]

  [1]: https://github.com/Tyill/SVisual
  [2]: https://i.stack.imgur.com/bvRwg.gif
  [3]: https://www.youtube.com/watch?v=wlvArf7h6lE
  [4]: https://github.com/Tyill/SVisual/releases
  [5]: https://i.stack.imgur.com/aZW07.gif


body:
[Serial Plotter][1] is a simple program that I've made with Electron that receives data in the following format:
`data1,data2,timestamp;` and converts it into a realtime chart.

[![enter image description here][2]][2]

  [1]: https://github.com/ItayRosen/Serial-Plotter
  [2]: https://i.stack.imgur.com/ab7to.png


body:
I am using processing.org for serial plotting from Arduino. It was the only app I could find that allowed me to make real histograms ( e.g. a million events in a hundred bins) and display various info numbers in addition to mean sigma for each channel. Two major problems:
A) it turned out to be based on Java with no unsigned bytes
B) synch ig with input required circular buffer and markers in the data. ( high speed, no handshake)


body:
[HITIPanel][1] Serial data plotting and recording. You can zoom in/out, pan, export data to text or excel file, or import external data from text files. Come with a user interface to control and monitor the hardware.

[![enter image description here][2]][2]

[![enter image description here][3]][3]

  [1]: https://hitisoftware.com/arduino-serial-plotter/
  [2]: https://i.stack.imgur.com/loS8z.jpg
  [3]: https://i.stack.imgur.com/f2D5W.jpg


message:
How to connect a 2 cell LiPo batter to Arduino Motor Shield?

I am trying to connect a 2 cell 7.4 volt LiPo battery into my motor shield. I am a beginner at robotics so I am not sure if I just connect the battery, via a connector of some sort, into the motor shield itself or do I use some 22 AWG wire and connect it via that way. Sorry if that sounds confusing.

body:
From the Motor Shield page,

> External (non-USB) power can come either from an AC-to-DC adapter
> (wall-wart) or battery. The adapter can be connected by plugging a
> 2.1mm center-positive plug into the Arduino's board power jack on which the motor shield is mounted or by **connecting the wires that lead
> the power supply to the Vin and GND screw terminals, taking care to
> respect the polarities.**

So they provide the screw terminals for a battery, you should be able to insert two wires from your battery/pack into the terminals. If your battery has a connector on it, you'll need to either cut it off or find an adapter.

**Be extra careful:** if you have exposed leads from your battery and they touch, it'll get extremely hot and possibly catch fire.


body:
it is up to you.
Welded cable is better, but you will probably need a connector, so you should take care to use low-ipendance one that can hadle your current need, like `bullet connector` used by RC toys.

Also the battery should have a `discarge current` higher that the maximum current used by the engine: normaly this can be calculated by the discarge factor (labeled as 'C' on the hobbyst battery) multiplied by the capacity in Ah o the battery. Pay attention to this as this can damage the battery and alco cause lipo-fire, witch cannot pulled off with just water, you need an extinguer. (this is what happen when you short-circuit the + and -)


message:
What's the fastest way to periodically communicate via serial?

I will be using an Arduino as a bridge between a computer high-level Java client and some low-level hardware computing units (e.g. other Arduinos). I need to find a solution to **periodically** communicate in **both** ways. It should be possible to send digital, analog inputs to the PC and receive digital, analog outputs from the PC via serial.

I have very specific requirements for my project to work:

 1. Lowest possible latency in both ways. High latency would cause
    instability of controlled systems.

 2. Extremely constant, possibly user-defined update period. Varying
    sample rate would cause inaccuracies in the control.

I need a very fast solution possible for update frequency of 100 Hz and higher.

So far I have tried to send data via Firmata to my java client using time interrupt.

    ISR(TIMER1_COMPA_vect) {
      Firmata.sendAnalog(analog, analogRead(analog));
    }

The messages however don't come at a very constant rate and are sometimes held up for twice the sample period or more which is unnaceptable. For higher frequencies this happens even more often. I suspect some kind of a buffer. Do you have any idea where should I look for bottlenecks? Would it be benefiting to design my own communication protocol and ditch Firmata?

EDIT: Look at the attached [diagram ][1]. Blue lines are "inputs", green lines "outputs". Right now I am trying to design the "Arduino (Bridge)"
![enter image description here][2]

  [1]: https://i.stack.imgur.com/9K9L8.png
  [2]: https://i.stack.imgur.com/fAmud.png

body:
> Lowest possible latency in both ways. High latency would cause instability of controlled systems.

the fact that you are using a not-real-time OS introduce a lot of unpredictable latency, the use of a visrtual machine over that os then add a bit more.
Fast communication can be obtained increasing the baudrate, that will decrease the latency between the sample and the elaboration.
Also sending RAW data instead of string will be faster (no convertion AND less byte send), and finally decreasing the overhead caused by the protocol.

For example Firmata by default use a low baudrate AND will add a lot of overhead to send WHAT kind of operation is doing. Writing your own communication protocol is better.

For example: analogRead use 10bit, so you may send a raw int, 2 byte, 16bit, so 6 bit are lost.. or you can "compress" with a bit of bitwise operation 4 read (40 bit) into 5 byte (40bit, no bit loss) instead of 8(int size * 4)!

AnalogRead is a really slow operation by default on arduino (~200us), but can be faster if you set up a lower prescaler (attention, lower prescaler means less ADC precision. at prescaler 16 guaranteed precision is 8bit, if my memory is good)

> Extremely constant, possibly user-defined update period. Varying sample rate would cause inaccuracies in the control.

On the PC side, if you need micro/nano second precision you need a `real time os`, newest linux kernel add a new special schedule but i think is still hard to find documentation. If less precision is ok, just use a timer.

On the arduino side, using a hardware timer is the best way, see [LeOS][1] for a nice scheduler on arduino

Please note HardwareSerial on the arduino side use interrupt to send data, so using it inside an ISR (like you are doing now or with LeOS) is really usafe and deadlock prone.
Also ISR will "slow down" each others, as they cannnot be executed parallel; and analogRead is a realtivly slow operation..
I would use timer to set up a flag, and in the loop if i see the flag, start the analogread, Serial.write and finally Serial.flush (to be sure to not fill Serial buffer, causing a lot of trouble on the arduino reprogrammation reset)

  [1]: http://www.leonardomiliani.com/2012/leos-un-semplice-so-per-arduino/?lang=en


body: I have had great success removing serial from such an example and setting up a closed network and then Ethernet enabling all the arduino devices. I then have a DCHP and SNTP server in the closed network. The PC etc are all in the closed network. I then setup a MQTT server (see www.mosquitto.org) and use the arduino PubSub library on the arduino. I get extremely short round trips with pretty consistent response times and this has the advantage that multiple sources can publish or subscribe to the data steams created. The SNTP server is used so that all the devices get the same time reference to use and I time stamp all messages and can then work out message sequence etc even if they are physically delayed slightly by an Ethernet collision! although in a closed network this is minimized.


body:
could you be more specific with your question ?
From what I understood:

 - you have a client java program acting as the "brain" of your system
 - your control is time sensitive. You have a PID or other regulation loop running on the pc
 - you have or plan to have multiple arguing boards on your system and you need to communicate with them.
 - you are dealing with analog IOs

## bridging ##
If you want to stick to serial port,you have to use RS485 or RS422. Those can work as a bus. Protocol on top of that can be Modbus.
Note that this has a higher latency and you need at least 2 serial ports on your bridge

I2C. Lower latency 2 wires bus. Command oriented,runs at 400 kHz. So you have plenty of time to send/receive data

SPI even lower latency as bytes are sent as stream .arduino mega has 5 pins for it. Note that you have to deal with the addressing yourself in this case.

Arduino like many micro controllers is bad as doing many tasks at the same time like for the bridging case. I would avoid using an arduino in this case

## latency ##

As already answered, ADC conversion takes time and you cannot nest interrupt.
Your minimum latency can be computed from the specifications of the arduino.
The maximum latency is a value you fix yourself.
Knowing the amount of time to send one byte on the communication port,
You can decide between options like

 - run the AD conversion in a loop outside interrupt, put the value inside a variable and do the communication a synchronously inside an interrupt
 - run the AD conversion interrupt based and the communication in the main loop of operation

## conclusions ##
Don't do hardware in the loop using a PC. The latency and lack of strict timing possibilities worsened by the use of java make it a dead end with your current setup.

Use a stronger micro controller like an AVR32 with USB running the brain of your system.
You can also use a raspberries pi or a beaglebone. Those runs "standard" Linux distributions and so you can use a PC like approach.

In any case guidelines are :

 - try to stay as close to the micro controller as possible and avoid abstraction libraries and OSes
 - don't use a pc for hardware in the loop
 - try to make your task run a synchronously as much as possible
 - keep your interrupt routines as small as possible


message:
Why does my wired button always read HIGH?

I have made a simple Arduino program that uses a potentiometer to dim a LED.

This program also makes a second LED blink.

Finally, I have added a button that controls a third LED; this part of my program does not work: the 3rd LED is always lit as the button always reads HIGH.

Here is the code:

    //sensePin is wired up to the FSR
    int sensePin = 2;

    //this is wired up to an LED
    int ledPin = 9;

    //Wired up to a button
    int inputPin = 1;

    int val = 0;

    //I was broed so added the default Blink
    int ledPinX = 13;

    //Wired up to a second LED
    int ledPinY = 7;

    void setup() {
      Serial.begin(9600);
      pinMode(ledPin, OUTPUT);
      pinMode(inputPin, INPUT);
      pinMode(ledPinX, OUTPUT);
      pinMode(ledPinY, OUTPUT);
      val = digitalRead(inputPin);
    }

    void loop() {
      if (val == HIGH){
        //This should ask "If your button is pressed, then do the code below
        digitalWrite(ledPinY, HIGH);
        //but for some reason the light is always on. I've tried it with more than one button
      }
      else if(val == LOW){
        digitalWrite(ledPinY, LOW);
      }
      int value;

      /*
     The rest of this stuff works. Well, it did before adding in the button. Now the FSR acts as a digital input. Please help.
       */
      value = analogRead(sensePin) / 4;
      analogWrite(ledPin, value);
      digitalWrite(ledPinX, HIGH);
      delay(500);
      digitalWrite(ledPinX, LOW);
      delay(500);
    }

What did I do wrong in this code?

EDIT:: diagram and pic at: instagram.com/p/m3AmHWmp4e

body: You read the button once, in `setup()`. The function is not called every time the variable's value is read, only when the line is executed and the variable assigned to. Move the `digitalRead()` call and assignment into `loop()`, before you check the variable's value.


body:
The main problem with your code is that you read the button state **only once** at the beginning of your program in `setup()`, so it keeps the initial value forever.

You should modify `loop()` as follows:

    void loop() {
      digitalWrite(ledPinY, digitalRead(inputPin));
      ...
    }

You can also remove the `val` variable, it is totally useless here; then you must also simplify `setup()`:

    void setup() {
      Serial.begin(9600);
      pinMode(ledPin, OUTPUT);
      pinMode(inputPin, INPUT);
      pinMode(ledPinX, OUTPUT);
      pinMode(ledPinY, OUTPUT);
      // val = digitalRead(inputPin);
    }


body:
Pin 1 is used for the serial output and can't be used if you enable serial using `serial.begin(9600)`.

Change button to pin 2.


message:
Arduino time(milli) and pressure sensor

I've succeeded to get an Arduino to work with a pressure sensor.

What I want to do is

 - when I put pressure on the sensor, after 5 minutes the led lights on.
 - it starts over again if there's no pressure on the sensor.

Here's the program:

    // FSR is verbonden met analoog 0
    int fsrAnalogePin = 0;
    // De LED is verbonden met pin 11 (pmw pin)
    int LEDpin = 11;
    // De analoge waarde van de fsr spanningdeler
    int fsrWaarde;
    // De helderheid van de led tussen 0 en 255
    int LEDhelderheid;

    void setup() {
        // start de serial monitor
        Serial.begin(9600);
        pinMode(LEDpin, OUTPUT);
    }

    void loop() {
        fsrWaarde = analogRead(fsrAnalogePin);
        // print ‘Analoge waarde’
        Serial.print(“Analoge waarde = “);
        // print de fsrwaarde op de monitor
        Serial.println(fsrWaarde);

        // maak van getallen tussen 0 en 1023 getallen tussen 0 en 255
        LEDhelderheid = map(fsrWaarde, 0, 50, 0, 255);
        analogWrite(LEDpin, LEDhelderheid);
        delay(100);
    }

I've got this for the pressure sensor... now I need to combine it with 5 minutes and the led lights on when it's reached that 5 min of pressure.

i managed to do this but it aint enough...

    unsigned long currentTime;
    unsigned long startTime;

    void setup() {
      // put your setup code here, to run once:
      Serial.begin(9600);
      currentTime = millis();
      startTime = currentTime;
    }

        void loop() {
      currentTime = millis();
      // put your main code here, to run repeatedly:
      Serial.println(currentTime);
      delay(1000);

      if(currentTime-startTime > 6000) {
    Serial.println("1 minuut voorbij");
    startTime = currentTime;
      }
    }

body:
The very simplest way - not necessarily the best way - is something like:

>     Keep re-reading the pressure sensor until it senses pressure;
>     Read millis(), add 300000 (# of msec in 5 min) to it's value, and store that;
>     Keep re-read millis() until it returns a number >= to that stored value;
>     Read the pressure sensor;
>     If it senses pressure,
>       turn on the alarm;
>       do nothing, forever;
>     Otherwise, start over again;

It isn't the best way, because the Arduino does nothing else for the 5 minutes until the final sensor check. But as you're learning, you probably don't need it to do anything else - for now. When that time comes, there are better ways than dedicating your processor to watching the clock. But this will get you started, and you may figure out some of those ways on your own, by then. Good luck!

Update: I realized my answer does not account for the possibility that pressure is released from the sensor and reapplied some time later, if both occur within the 5 minute wait. How you treat that situation will depend on the needs of your application (which I'm guessing is for you to learn to work with time and physical data). I'll leave that as a further exercise for you.


body:
Try this:

    unsigned long pressureOnTime; //millis() time when pressure switch is first turned on

    const unsigned long ledOnAfterTimeThreshold = 300000; //5 minutes * 60 sec * 1000 mSec
    int pressureThreshold = 1; //minimum analog reading from pressure sensor considered to be "on"

    const int fsrAnalogePin = 0;
    const int ledPin = 11;

    int ledState = LOW;
    int pressureState = LOW;

    void setup() {
     Serial.begin(9600);
    }

    void loop() {
     checkPressureSwitch();

     //do other stuff here
    }

    void checkPressureSwitch() {
     if( analogRead(fsrAnalogePin) >=  pressureThreshold )
     {
      handlePressureOn();
     }
     else
     {
      handlePressureOff();
     }

     digitalWrite(ledPin, ledState);
    }

    void handlePressureOn() {
     if ( pressureState == LOW )
     {
      //pressure switch was off, but is now on
      pressureOnTime = millis();
      pressureState = HIGH;
     }

     else if ( millis() - pressureOnTime >= ledOnAfterTimeThreshold )
     {
      ledState = HIGH;
     }
    }

    void handlePressureOff() {
     ledState = LOW;
     pressureState = LOW;
    }


message:
Which shield to use for GPRS?

I'm planning to build a device that would read some sensor data and send it via GPRS, eg. once per day. (Not that original, yeah.) But my problem is choosing a GSM/GPRS shield.

The official shield has a [**nice interface for doing an HTTP POST/GET**][1]. OTOH, the shield seems to be sold out (and would be quite expensive anyway).

There seem to be other shields available, but their code examples tend to look [**quite hacky**][2]: the device waits for an arbitrary moment and then hopes that the server is done. That's IMO both inefficient or unreliable.

My question: which GSM/GPRS shield would you recommend, with these features:

a sane library w/ examples, such as the official one

an external antenna

bonus: a competitive price

another bonus: hopefully a "real" shield, so no soldering required and a few pins still easily usable for the sensors.

  [1]: http://arduino.cc/en/Guide/ArduinoGSMShield#toc10
  [2]: http://www.seeedstudio.com/wiki/GPRS_Shield_V1.0#A_Simple_Source_Code_Examples

body:
That library should work with pretty much anything that has the M10 module on it.

I only have experience with the SIM900 modules. Found the cheapest one on EBay.

While interfacing with these things can be a challenge at first, you really just need to read the manual for all the AT commands and execute them. I've written a couple of functions that may help:

Note: you may safely replace all instances of `DEBUG_PRINT` and `DEBUG_PRINTLN` with `Serial.print` and `Serial.println`.

    SoftwareSerial SIM900(7, 8);

    /*
        Sends AT commands to SIM900 module.

        Parameter   Description
        command     String containing the AT command to send to the module
        timeout     A timeout, in milliseconds, to wait for the response

        Returns a string containing the response. Returns NULL on timeout.

    */
    String SIMCommunication::sendCommand(String command, int timeout) {
        SIM900.listen();
        // Clear read buffer before sending new command
        while(SIM900.available()) { SIM900.read(); }

        SIM900.println(command);

        if (responseTimedOut(timeout)) {
            DEBUG_PRINT(F("sendCommand Timed Out: "));DEBUG_PRINTLN(command);
            return NULL;
        }

        String response = "";

        while(SIM900.available()) {
            response.concat((char)SIM900.read());
            delayMicroseconds(500);
        }

        return response;
    }

    /*
        Waits for a response from SIM900 for <ms> milliseconds

        Returns true if timed out without response. False otherwise.
    */
    bool SIMCommunication::responseTimedOut(int ms) {
        SIM900.listen();

        int counter = 0;
        while(!SIM900.available() && counter < ms) {
            counter++;
            delay(1);
        }

        // Timed out, return null
        if (counter >= ms) {
            return true;
        }
        counter = 0;
        return false;
    }


body:
I would recommend the official [Arduino GSM shield][1].

  [1]: http://arduino.cc/en/Main/ArduinoGSMShield


body:
I ended up ordering an [**Elechouse board**][1] which uses the M10 chip. Found one on eBay for 59 USD. It appears to work fine with the official library.

As the manual says, it must be given external power - the USB cable isn't enough!

  [1]: http://www.elechouse.com/elechouse/images/product/GSM_shield/GSM-GPRSModule.pdf


body:
LinkitOne - ok not a shield but rather a compatible Arduino controller board with built-in GSM/GPRS/GPS/Wifi. comms library doesn't have as many diagnostic methods as e.g. the Adafruit one, but it was easy to setup and reliable. Main downside of the LinkitOne was that it uses a different processor from Arduinos so many of the Arduino libraries aren't compatible e.g. for I2C devices.

Adafruit Fona SIM808 2G Shield version. shield layout but stackable headers have to be bought and soldered seperately. Default pinouts work with Uno, but mods required for Mega. Library has lots of handy diagnostic methods (battery voltage, signal strength, etc). worked with giffgaff prepaid SIM but not vodafone for some reason. SMS worked ok. I could connect to GPRS but getting html from a website didnt' work.

DFRobot SIM808 GPS/GPRS/GSM Shield - Pre wired wirth stackable shield connectors, instructions to upload code and run the device are convoluted and vague. I Wasn't even able to get a basic connection to the Arduino to work. Either the library is very buggy or my device was faulty.

SEEEDStudio 113030009 GPRS Shield with Antenna and External SIM Holder V3.0 I'll probably tets this next..

Official Arduino GSM board DISCONTINUED

Sparkfun GSM/GPRS Module - SM5100B DISCONTINUED


message:
strange behaviour of dtostrf()

I'm trying to program a little bit in Arduino, but I'm stuck with probably something trivial.

This is what I have:

    char ang[3], lat[9];
    dtostrf(GPS.angle, 3, 0, ang);
    dtostrf(GPS.latitude, 9,5, lat);

    Serial.println(lat);
    Serial.println(ang);
    Serial.println("-------");

I would expect the following in the serial monitor:

    5111.60160
    267
    -------

But instead, I'm getting this:

    5111.60160
    2675111.60160
    -------

So it looks like the `ang` holds both the angle and the latitude....

Why is this happening? And how can I solve this?

My goal is to make one big string, comma separated, from the data stored in `GPS`

body:
Your arrays are both too short for the strings they're meant to hold. In particular, ang has three digits and only three bytes. The string-terminator, NUL, ends up in the 1st byte of lat. Since you generated the ang string first, lat over-wrote ang's NUL character, effectively getting appended to ang.

The lat string will need at least (10+1) bytes; ang will need (3+1) bytes, counting only the actual data in your question.

I make it a habit to declare string arrays just as I wrote the sums above, to make it clear that I've counted both the contents and the NUL byte, so:

> char ang[3+1], lat[10+1];

I doubt that you need to specifically add the NUL terminator; it would quite unusual (counter-conventional) for a C/C++ function that generates a string to leave off the terminator (except in a few special cases).

Try increasing just your array sizes first; it'll probably work.


message:
GSM library getIPaddress returns local network address 10.X.X.X

I have a [Mega board][1] and a [GSM shield][2]. I'm using Arduino's example "TestWebServer". The serial monitor shows that the GSM is connected, and returns a IP.

However, the IP is always 10.X.X.X. Isn't that a internal network IP address? How should I get the SIM cards IP? Thanks!

  [1]: http://arduino.cc/en/Main/ArduinoBoardMega2560
  [2]: http://arduino.cc/en/Main/ArduinoGSMShield

body: The SIM card does not have an IP address. When the data connection is made to your GSM APN it is assigned an IP in a similar way to DHCP. Often the address is the same after the first connection as the service provider will link that to your SIM for audit purposes. If you setup a private APN then you can arrange to have specific range allocated to your SIM card(s). This is normally only done for security of volume reasons.


message:
Arduino Mega's 4 Serial Ports?

I have been using only Arduino Uno. Now I am about to buy Mega. But a question rises. Are those 4 Serial Ports of Mega controlled still through one usb cable?

body: No. If Arduino ATmega microcontroller supports more than a single UART, then only the first one is available through the standard USB connection. Other UARTs use their own pins that you have to connect to on the board. Mind you these pins are TTL logic serial and need a converter for RS232 or similar. It is possible to use a second (third, ...) TTL-serial to USB cable to access the port on your PC.


message:
How to disable Arduino Yun to work as Access Point and set it to work as needed?

I am using Arduino Yun and I would like to disable it to work as Access Point. That is, I don't want that it is displayed in the list of available networks.

Then I would like to set and use it (separately) in the following scenarios:

a) Arduino Yun connected just over a given Wi-Fi network (Ethernet connection disabled).

b) Arduino Yun connected just over Ethernet (Wi-Fi connection disabled).

How can I make it?

**Note**: In my previous attempts I tried to customize and/or disable someway the Wi-Fi connection (through the LuCI panel) in order to reach what I am looking for but in all of these cases [I had to restore my Arduino Yun][1] from scratch because it did not work anymore.

  [1]: http://playground.arduino.cc/Hardware/Yun#restoring_a_yun

body:
Yun expects wifi to be working and, if it's not, it will reboot itself after 60 seconds and return in access point mode.

In order to disable this check, edit file `/etc/rc.local` and turn `wifi-live-or-reset` into `#wifi-live-or-reset` (with a starting `#`).

Once done, use LuCI (the advanced configuration panel) to configure network interfaces.