text:
2.4" TFT LCD Shield isn't working on Arduino Mega
Even on ebay's website 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.

    // 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);
}

The eBay ad has this nonsensical statement: "This shield does NOT work with the Mega Arduinos but its going to be half the speed of the Uno-type boards because of the way the Mega rearranges all the pins (there is no way to get around this!)"  How can it simultaneously not work, and be half speed?

Are you using the 8bit or the 16bit version?

You code says to use pins 38-41 while looking at the picture the shield doesn't even connect to pins 38-41. You are also defining a different lcd-model for the Mega than for the UNO. Try using the same code as the uno; so UTFT myGLCD(UNO_24,A2,A1,A3,A4);

Looking at the wording, it sounds like it doesn't work, but eventually they will have a slower library to make it work.

You can use the MEGA2560 and an Arduino UNO interchangeably.  They run at the same speed, and they have the same pinouts and pin definitions.  if it works on a UNO, then it works on a MEGA

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 |
+---------------+-----+-----+-----+-----+-----+-----+-----+-----+

OH MY GOD!! IT IS WORKING :D First I download Arduino Enhanced Release 1.0.5 from here: http://forum.arduino.cc/index.php/topic,118440.0.html Then I opened your GitHub code then download it. I open swtft.cpp via DevC/C++ program I downloaded before. I change uno lines with these: #include "mega_24_shield.h" then I upload the code into Mega and it worked. I only put the 2.4" TFT LCD onto MEGA, I didn't make more nothing connection. Just I put the shield onto Mega :D God saves you :D Very special thank you. The error has been still for 6 months. Thanks.

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.

Have you checked out the Library homepage? Henning Karlsen's library page
He has made a user manual for the library. There is also a reference to what pin goes where in the requirements document.

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.
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?

SPI isn't a problem, as the shield is using D0-D7 picture. What other things could affect this?


text:
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?

Take a look at Bridge example or TemperatureWebPanel example: you see you can receive kind of "commands" and react "doing things".
Then take a look at HTTP Client example, 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.

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
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?

Not a Yun expert but shell commands seem easy on the Yun. I don't know much about adding a script to it, so feel free to build off of this and post an answer.

Don't know anything about Yun but I'd look at the FileIO class to make a file and write your script into it. Then use Process class to execute it.

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 and bash. Other languages such as ruby, erlang and php are available as optional packages.

In which directory on Yun should I put my script files?

Wherever, but the sd card is the preferred choice, so you don't wear out the flash. If you have an sd card with an arduino folder, you should have it available at /mnt/sd

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
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?

You need to clarify what OS you're working with. Linux or Windows? What versions, too, since this may require more than just Arduino code.

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.

For the second one, you don't need a dual firmware. IIRC you just need to flash the standard USB firmware, upload, and reflash the keyboard/mouse one again. No where near ideal, but workable.

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.
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 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 on how to do it.

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.


text:
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?

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.

Yes, I have Bridge.begin(); and YunClient client = server.accept(); is there within the loop. I'm able to access everything internally, just not externally.

So your answer helped me validate that what I am doing is correct. I'll mark it as solved. What ended up happening is that my router didn't save the NAT for port 5555. So I re-did that, and it's good. Thanks again for verifying that noListenOnLocalhost() is correct for external hits!

@Pat Glad to have... ahem... "helped" :-)

You did! I wasn't sure if noListenOnLocalhost() was correct, and the documentation on noListenOnLocalhost vs listenOnLocalhost wasn't overly clear (I think they both say the exact same thing).

The doc is "correct", but indeed not very explicit regarding internal VS external. And I must admit that when I first saw the function name I found it rather suspect.


text:
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?

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.

What do you mean by "take a point in every position"?

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.

Am i correct to assume that the z-axis should (ideally) give an acceleration value of approximately 9.8m/s^2? Or should it really read 0m/s^2 at rest?

@Paul - yes you are correct


text:
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?

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.

Are the I/O-pins connected to GND when in OUTPUT mode and not outputting? This would make sense, and would mean this answer is correct.

@FriendofKim In any output mode through protection diodes in the microcontroller an in OUTPUT node through the driver transistor.

Yep, it doesn't work with just one servo, which I didn't think to try. Thanks!


text:
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?

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
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

I can't see what it's doing because there are too many lines outputted. The first lines where it's calling BOSSA are being clipped away.

I found a way. Press the upload-button while in the middle of uploading. It will fail, and will not output too many lines anymore. I'm going to try it out now.

you can also try with a non-due (or a physical serial port with nothing attached)

I believe the problem was either the command line arguments, or that the board needed to be reset before connecting to it. I can't connect to it through the master bossash.exe, so it seems they've changed something on the Due rendering the master BOSSA useless. I don't quite know yet, but I'll try to leave a comment later when I've figured it all out.

edited my answer, as expected the reset opening theserial port with a baudrate of 1200 is a foundamental passage. Also please note that the bootload probably as a little timeout, so you have to script the execution of reset + upload to make it in the time slot.

Does it reset when connecting with 1200 because of some code written by Arduino? If I were to program the Due without the Arduino library, would this method stop working? Is the Arduino Bootloader which runs automatically saved to a different memory than the code we normally flash to the chip?

no special code needed, just opening the serial at 1200baud is fine, and yes, bootloader live in a special area, like in the UNO! Util you get that reset working, you can program using wathever you want

Hmm, how does it know the serial is opened at 1200 baud? Isn't this a number both parts have to know on before hand?

automatic baudrate discovering is possible. Btw you are forgetting that this is a virtual serial over USB, some trick may apply. see /hardware/arduino/sam/cores/arduino/USB/CDC.cpp

Okay, I'm able to upload it now. The problem is just that after the upload, the Arduino doesn't restart, and it isn't possible to connect to it without rebooting the computer.

rebooting the computer?? just disconnect/reconnect the USB does not work? do you close the serial connection?

My mistake. Rebooting the computer worked only once. Now even the Arduino IDE does not recognize it using the native port. It finds the Due on the programming port, but cannot upload code with it. Yes, I have closed the connection.

that's another kind of issue, i think. Developer usb works but not user? How are you compiling code? Des the pc detect the usb?

The PC doesn't detect the USB when connected directly to the SAM (native), but is recognized when connected to the programming port. All using the Arduino IDE, it cannot upload code through the programming USB. Might there be something wrong with the Arduino Due? When connecting RESET to GND, nothing happens.

let us continue this discussion in chat

Sorry, but this answer is fundamentally mistaken.  Opening the port at 1200 baud specifically cannot do anything for a true serial port as listed here.  That's only "magic" with a USB serial device, where the baud rate is a parameter communicated to the hardware.  But on many configurations, merely opening a (real or USB) serial port will change the state of control lines which can be wired to trigger a reset.

@ChrisStratton my answer stand as he is opening a ttyACM0 witch IS acm driver (virtual serial over usb), and the usb driver on the due has been scecifically written to use that as a reboot request. Strange but true: see the "programming" at http://arduino.cc/en/Main/arduinoBoardDue

I'm aware of the special casing - but it does not apply here.  Your answer is erroneous, as in your answer you are, by both description and quoted command, access a true serial port /dev/ttyS0, rather than a USB one.  What you are proposing will not work for a true serial port.

I see. This is because that output is from arduino ide, and because i didn't had a Due i told the ide to use the hw port. I now i get what you say, and I'll point this out

Your description and example command still references a hardware serial port where that trick will not work.

Fixed, i think. Feel free to edit if you dont like it

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

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.)

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
How do I use two ultrasonic sensors to control a 5 V motor?
I've hooked up two ultrasonic sensors to my breadboard and I also got a 5 V motor installed. I also got the diode installed and the usual set up. I can easily control the motor with one sensor.
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);
  }
}

Is "100" half speed?

uhm the max is 225, so I assume that the half speed should be around 112. but yeah, in my concept it's half speed

What do you want to happen if the two objects were both kept at the same time infront and at the back of the robot?
This problem can be solved if you wrote down all possible combinations which is as far as i see it 4 combinations.

Well what I want when two objects were both kept at the same time is that the speed turns to normal (default) as in 100

Is there anyway to the same thing but with a raspberry Pi and a PWM extension/driver HAT from adafruit?
Same ultrasonic sensor and a single motor. What I'm trying to do is increase the speed of the motor when there's something close to the motor (also reverse direction) and keep the motor running forward as normal if the object is far away

This is very simple using the map() instruction. 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.

Thank you for the help. Whenever I try to do it according to what you've posted above, the motor kinda acts weird. Weird as in, it just stops working all of a sudden and then starts working again.

Can you confirm that you use a transistor to drive your motor (don't connect it directly to an Arduino pin)? Also, you should use a flyback diode in parallel with it.

Yes I am using a transistor and a diode.

Chatroom created

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
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:

Don't use Serial inside a function that is called by a timer. Never.

I don't understand why you have an external pin that must trigger the beginning of every period of your waveform.

You mention that "the waveform seems to shift". after how long does it seem to shift? Of how many ms can it shift?

What you've failed to mention is: are you doing anything else at the same time? If so, you're going to have to get rid of those delays because it will halt your code. If not, then it really doesn't matter, but still, just set a flag in your interrupt and run it on flag in the main loop. If you ARE doing something else, implement a state machine in the main loop for it

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.
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();
 }

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
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

If all code is ran inside loop() and you're really looking to squeeze out a few clock cycles I would do the following void loop() { while(true) { /* Code Here */ } } as you don't have to worry about the small overhead of recalling loop()

You've said pinMode() can only be set once. I believe that's incorrect. It can be called as often as necessary, at any time.

you are right, but digitalWrite is a mayor speedup, to sqeeze mcu use the PWM and you will have a lot more power with a lot less efford (once you know how to PWM :) )

@PeterR.Bloomfield my english is bad, i can't find a way to say what i mean. if you can edit my answer to correct the sentence so it will be correct.. thank you


text:
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

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

The Host header isn't required under HTTP/1.0, which is what he appears to be using.  Those were the days before  we hosted multiple websites on the same server.

you are right, tecnically is not, but many server does not care, i'm quite sure as i can replicate this with google's server by telnet

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)

This seems to support the idea that the server is ignoring the http/1.0 and act as HTTP/1.1 instead

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("");


text:
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?

Why can't you use millis() for this?

Do you know how to wire up and detect the sound from the microphone using the Arduino?

What is the time precision you need?

@jippie: yes, I have done so successfully

@jfpoilpret: I need time precision of the order of 10^-6 secs. Of course, smaller is better :)

1us precision is about the best you could get on Arduino UNO. But any instruction executed will probably have an impact on that precision. Your best option is probably to use attachInterrupt() but it requires you to first change the electronics so that it converts the mic analog signal to a logical signal (you can use an AOP for that) that is connected to a pin that will trigger the interrupt.

1us may be impossible to reach as it leads to 1MHz frequency; audible sounds are limited to ~20KHz only; I don't even think your mike could react that fast!

Can you elaborate on the mic's analog -> logical signal? And what is an AOP?
IMO, you should post it as an answer instead :)

and ah, good point about the 20 KHz signal. That's where experimentation comes in.

Sorry no time for an answer right now (must go to work...). I'll do it tonight if it's not answered yet. By AOP, I meant op-amp (Operational Amplificator); sorry that was the french abbreviation :-(

You may want to investigate using ICP on timer 1 for lowest possible latency.

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:

converting the analog output of the mike into a digital value (based on a threshold to determine)
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 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 is probably a good solution for this problem but further experiment will be needed to confirm that.

Thanks for the answer. Well the ADMP 401 already has an amp of sorts, so is a separate op-amp required? Would an op amp like this one work: http://www.protocentral.com/breakout-boards/136-mono-audio-amp-breakout-tpa2005d1.html?search_query=op+amp&results=22 ?

The ADMP 401 uses an Op Amp as a signal amplifier not as a comparator, so you will still need an additional Op Amp mounted as a comparator. There are plenty of Op Amps available and cheap; I think the LM 358 chip (https://www.sparkfun.com/products/9456) should fit your purpose; this one only requires a single supply (between 3V and 32V).

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.

Yes, that is correct, I'll try this out the next time I start messing with my arduino :)


text:
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:

After opening the serial port, only a line "GSM network scanner" is read. Seems that the program is stuck ongsmAccess.begin(PINNUMBER), how shall I fix that?
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)
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
Note for using GSM shield with Mega
* 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.

On point #2, yeah, you'll most likely need to provide an adequate supply. I have a GSM module and it'll turn off as it's trying to connect when I don't give it enough current.

Does it work when you do directly stack the boards together?

I see pin 3 as input but no where in your code are you setting the pin to input. As I missing something?

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


text:
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?

Ethernet shield
#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");
  }
}

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.

I have manually configured ip address as above . Let me know what problem i have made

It looks as though your network address is 192.168.7.0 with a subnet mast of 255.255.255.0. Therefore you would need to assign the Arduino an IP address is the range of 192.168.7.1 - 192.168.7.254. You need to make sure however that the IP address has not already been used by a device that is already on your network. e.g. 192.168.7.12 is already being used by your computer.

I have already  tried it but didn't worked . Is internet connect needed  for this application?? i have assigne d my network as 192.168.7.0 and arduino as you told it to 192.168.7.50. but nothing being changed

It is not clear what you mean by nothing has changed. Can you clarify? Are you seeing the server is at xxx serial output?


text:
Serial data plotting programs
I need to plot serial data from Arduino.
I require support for:

Various data formats (e.g. signed, unsigned, 8 bits, 16 bits);
Plots several data on the same axes;
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?

I decided to reopen with your last edit. As this question stands, it seems to be on topic because it's specific. I'll be clear to anyone (since there's not a lot of these types of questions): if this gets too off topic, I may have to step in. However, the likelihood of that happening is rare. :) @JRobert If GnuPlot meets the requirements in the question, post it.

The "Interfacing with Other Software" page on the Arduino Playground shows a bunch of ways to plot serial data from an Arduino to an iPhone, a Windows PC, a Linux PC, etc.

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

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

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

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

ArduinoPlot (free) - simple plotting.

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

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

RealtimePlotter (free) - 6 channels data plotting.

SimPlot (free) - 4 channel plotting.

Arduino Serial Plotter (free) - built in Arduino Editor under Tools > Serial Plotter.

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

I'm confused. I posted my own solution below but now I'm not sure if it wouldn't be better to edit your post since it's a wiki. What do you think ?

@Overdrivr Sure, go extend this wiki for others' sake!

GnuPlot
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.

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

This looks great. Could you add some demo code?

But it plots the data from Logfile.txt, not the realtime serial data. How to connect it to a serial port?

No, this script isn't "real-time" -- it could be up to around 4 seconds behind. Logfile.txt is the capture file output from a terminal program. In my case, the data collection system samples and logs every 4 seconds and the GnuPlot script replots the log file every 4 seconds. This is dynamic enough for what I'm doing with it (monitoring room temperatures).

I use Matplotlib 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. Does the "Arduino real time plot Matlab"[https://www.youtube.com/watch?v=ntHZsLmNkgw] video use that same technique?

Yep. It uses a call that reads the arduino data into a matlab variable, and then a call that updates the matlab plot with the matlab variable.

Matplotlib is python, not matlab.

I disagree with you, this question should not be divided in 2. There are solutions (such as the one I posted below) that do take care of both, because it is annoying to reivent the wheel for remote monitoring and control of arduino applications, and also because writing python code for real time plots is actually very far from trivial. Things can be done with matplotlib but clearly there are better alternatives for that such as pyqtgraph.

For part 1: getting data from Arduino: https://github.com/ElectricRCAircraftGuy/eRCaGuy_PyTerm

SerialPlot (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

Good answer, I liked serialplot, it found my COM port & baud rate automatically, I just had to change from binary to CSV and increase to 3 channels ( for a magnetometer) and it was plotting nicely.

This is the neatest and easy to use - but I do wish there was a mac Binary :)

AppImage available => ultra quick installation !

But seems that icon of SerialPlot is not visible in Ubuntu (AppImage).

Would love to give this tool a try, but can't seem to find any documentation on how to format the data sent to the serial port.

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:

You can try 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:

I tried this & found it very clunky to get working, no default config, doesn't autoscale, after half an hour faffing with the syntax I still didn't have a plot only a straight line, so I gave up & used SerialPlot which worked within a few minutes, just had to specify ascii text & number of channels.

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.

You might be interested in Telemetry See on Github . 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
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
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

Get started
Wiki
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.

PS: logging of the serial port data in the python packages (raw data and decoded data) is also fully supported. I intend to use it to implement an offline replay function (simulate serial data flow)

You can use MATLAB Student Edition,
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!

Welcome to Arduino SE! Can you please edit your answer to add more information describing how it fits the OP's needs and maybe a little other information like a link or a photo? Thanks!

Good answer, wouldn't have thought of using Matlab, there's a SO thread here about it https://stackoverflow.com/questions/19483098/using-matlab-to-display-streaming-serial-data

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

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

Can you explain how to use this, and what the advantages and disadvantages of this are?

While I haven't used it myself, "rqt_plot" 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 library or the ros_arduino_bridge library.

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

CSV format is most versatile for any data (signed/unsigned, various size and precision).
Cross-platform (written in Java/Scala) tool Scsvlog can receive/parse CSV strings from serial port / socket, show values and draw charts (up to 8).

Tool can no longer be found now, unfortunately - the original link is dead and I can't seem to find any copies.

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

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.

As of Aug 1 '18 this website is dead.

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:

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/

Serial Plotter 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.

Almost useful. It needs:

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

Live Graph is a better option and I use it in conjunction with Tera Term 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

An executable (.EXE) so it has no external reliance
Includes a terminal emulator or serial data logger
Logs serial data
Graphs multiple items from a CSV
Allows for CSV AND tab-delimited data (which is way easier to read as it scrolls along while simultaneously monitoring the graph.
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.

Welcome to Arduino SE! Your answer is informative but could you please improve the formatting of the answer using the markdown guide you can view by pressing the ? button in the editor.

Telemetry Viewer
Advantages:

Easy to use
Intuitive and flexible UI
Open Source and free
Different types of Graphs
Very fast graph update rate

Disadvantages:

Stopped development
Binary data format is not complete yet.
Primitive graph controls like zoom, screenshot and ...

SVisual Monitoring and recording of signals for Arduino and not only.

Video example
Download (free)

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)

HITIPanel 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.


text:
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.

22 AWG might be a little thin for some wire IMO; for power lines it's usually best to get something thicker, of course something really big would have too much resistance: that's why some power lines have more than 2 cables. (In the US, anyway)

You might want to check this about arduino overheating.

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.

Do I need a separate 5V battery to power arduino board, and my 7.4V battery for motor shield? Can I use one for both?

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 -)


text:
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:

Lowest possible latency in both ways. High latency would cause
instability of controlled systems.
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 . Blue lines are "inputs", green lines "outputs". Right now I am trying to design the "Arduino (Bridge)"

You might want to just use millis() and delay to help avoid variance in the sampling rate. For latency, IMHO it'd be better to get a very high baud rate. You could reduce errors with this library here.

I thought using hardware timed interrupt should be significantly more accurate. So nothing in the loop() can slow down the messages. Am I wrong?

You're correct. They would be more accurate, but do remember that, if you want it to always be consistent, you'll have to add a little "padding time" to most code to make sure that something a little longer doesn't hold back the next iteration. It won't make it faster, but it most likely will regulate the time between iterations well. Since I don't know your application, the solution in the first comment was the easiest :)

A USB interface itself may be a poor fit for an application requiring low latency.  It's possible that it would just barely work at the rate you need with very efficient software drivers on both ends, but you should consider the very fact of using USB to itself add a millisecond or more of latency, and your interval is less than 10 ms.  Normally, a control loop should be moved entirely outboard of the USB - ie, use a more capable embedded board ("Arduino" or otherwise) and run the entire control loop on it, passing only non-realtime settings/status over the USB.

I understand your point but it would be impossible for my project. I will be running a simulation of a robot and its enviroment on the PC, therefore I need to communicate periodically with the robot's control unit (to send simulated sensor input, and to receive commands) . This approach is called "hardware in loop" simulation and it's the whole point of my project.

Using hardware timers will be WAY better then one of the arduino constructs like millis(). It'll also be far more deterministic regarding timing constraints.
Of course, if you're including the USB's latency (anywhere from 10-200 mS, unpredictable and uncontrollable), you're probably SOL.

@SagiCZ - then you should host the simulation on a system designed for low-latency I/O, and thus avoid using USB in the critical path.  Many of the ARM-based boards for example can do that, and still run a desktop operating system like linux perhaps letting you move your simulation environment over with a simple recompile.  Alternatively, if you can't come up with low-latency hardware to host a "hardware in the loop" test fixture, perhaps you should drop that approach and run a copy of the robot's program on your PC.

I have come up with the best solution so far, although I have to test it a little more. I will move all the time or latency critical simulation to the Arduino and run the non-critical things on the PC. This way I can take advantage of computers superior processing power and graphics ability and not lose the microsecond precision of microcontrollers. The PC client will also generate and upload a custom Sketch for the "bridge" Arduino each time user changes configuration of the robot.

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 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)

"... but can be faster if you set up a lower prescaler ..." Or if you forgo analogRead() altogether and just have the ADC dump its results into a volatile variable when finished converting and read from that variable upon request.

i dont see how the adc read finished interrupt can help, expecially if not setting the adc. Or are you suggesting to use register insted of snalogread

You set the ADC to autotrigger (off, say, a timer), and have the completion ISR dump the value into the variable. You then read from this variable instead of accessing the ADC directly.

thank you, these are some great ideas.. When it comes to the PC client side I am not going for the RTOS route so I would like to implement the second approach you suggested -> "just use a timer". Could you elaborate on that a little bit? How does timer help me compared to uninterrupted listening to the port? Did you mean I can time the message processing for the cost of being "behind" one or two periods? That would probably be acceptable.

+SagiCZ i was talking about sheduled action. To read the data event or blocking call are optimal solution

What if I schedule the reading to some particular moments in time but the messages come in between those moments?

x arduino and pc: they are bufferized. a ring buffer is used, so when buffer is full, newest reading overwrite oldest

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

Maybe I could forget about serial but still use Arduino and USB connection. I think there might be a way to set up the connection as a HID device or something entirely different from Serial.
Your conclusion and final suggestions unfortunately dismiss the project's point. Which is to simulate with hardware in the loop but also visualize the simulated robot in java game engine.
I don't think it should be impossible to send the data so fast. I know that for example external audio cards have latency of about 1 ms and send the data with rate of 20 kHz or similar through USB.

I have edited the question with a diagram to help you understand.

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.

This sounds promising. Did you use Arduino ethernet shield? Could you provide more details or point me in a direction to learn about details of this implementation? Ditching serial has been my newest idea :)

@SagiCZ If you are looking for a high-performance PubSub based communication protocol, without the overhead of MQTT broker, you should have a look to my project, it is pretty much that, point-to-point protocol, lightweight C library and a python CLI to communicate with the device, open plots,etc : https://github.com/Overdrivr/pytelemetrycli


text:
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

Could you the part of your circuit showing how the button is wired to the Arduino?

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.

ok that helps a bit but when I run it the ledPinY stays on the entire time instead of responding to the button

http://pastebin.com/tBiHX7Zw
Ok the button still wont read input and I just revamped the code from scratch just to get the button working then I'll implement sensePin. It compiles fine but always digitalWrites HIGH to ledPinX

EDIT:: Taking a look at the button example i figured out whree I went wrong. I may just use that and integrate the FSR code
EDIT:: It doesnt work either

ummm.. even witht the button gone and input jumper cables pulled that output is screwed up

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);
}

I added the diagram to the original quesiton

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.