text:
Serial.read has garbled data after a Serial.write
I'm using the Serial1 of the Arduino Leonardo to send and receive data with another MCU. The following code will always retrieve garbled data:
byte streamReadResponse;
Serial1.begin(115200);
Serial1.setTimeout(9000);
Serial1.print(cmd);
Serial1.print('\r');
Serial1.flush();  //wait for all the data to be sent to the serial
streamReadResponse = Serial1.readBytesUntil('>', data, dataLength);

But, if I add a delay(50) before the Serial1 read, I would get the expected output. The value 50 was found by trial and error.
What am I missing? Why is the flush() command not working as expected?

Could you please tell more about "garbled data". You mean what it is inside your "data" variable? What is the final value of streamReadResponse after the call to readBytesUntil with and without the delay?

Try putting a ~2.2k pull-down resistor on the Arduino's RX pin (connect the resistor to ground and the pin).

Which version of Arduino IDE are you using? It seems HardwareSerial.cpp has changed a lot along different versions, in particular the flush() method. In version 1.0.5 it should be OK normally.

This question really is not answerable without more details, such as the nature of the garbled data as already requested.  It appears to have been abandoned and should probably be closed.

@ChrisStratton you are right - I was not even sure on how to provide the details - I still hope my own answer can help other people.

I've finally found that when the MCU  to which Arduino is talking to was initialized, it would send spurious data to the Serial - I guess it would start first with a lower baud rate, and then switch to the programmed baud rate of 115200.
To fix this, I had to flush the Arduino serial RX before sending any data. So:
byte streamReadResponse;
Serial1.begin(115200);
Serial1.setTimeout(9000);
while (Serial1.read() >= 0)
           ; // do nothing
Serial1.print(cmd);
Serial1.print('\r');
Serial1.flush();  //wait for all the data to be sent to the serial
streamReadResponse = Serial1.readBytesUntil('>', data, dataLength);

Usually, this kind of issue is the result of the several times by time unity of loop statements execution, with the baudrate defined for your serial i/o it's very possible that the flush are override by the new information input and the result are the "garbage" on that.
On my sketches, ever I put "idle function calls"  in some points of the code to avoid this and works succesfully.

I don't understand why this would be. Surely .flush() should do as documented unless Roberto has overridden it?

I don't know why, but, for example, for prevent in a project the malfunction of a clock module, I must call to read it fewer than times, when the documentation not tell nothing about this.The fact is that many times the execution speed of the main loop can make some features of functions and/or response of devices will be wrong. As if you push data onto a funnel and arrives to the exit mistaken.

.flush() pauses execution until the output buffer is empty.  It shouldn't have anything to do with garbage on your input.  Try putting a ~2.2k+- pull-down resistor between serial-in and ground to make sure you aren't getting noise or cross talk in the input buffer.


text:
Warning Arduino CMakeLists "Policy CMP0022 is not set: INTERFACE_LINK_LIBRARIES"
I'm trying to build an Arduino example without using its IDE. My OS is Windows 8.1 and I'm using the last version of CMake (2.8.12.2) and MinGW (GNU Make 3.82.90).
I downloaded the Arduino CMakeLists and I learned all about make/upload any firmware in my Arduino. I'm using Arduino UNO.
Then, if I modify the CMakeLists saved in ~/arduino-cmake-master/example/CMakeLists.txt (arduino-cmake-master is the repository folder) to build the WiFi example WiFiWebClient too:
...

#Add the WiFi example -> WiFiWebClient
generate_arduino_example(wifi_example
                     LIBRARY WiFi
                     EXAMPLE WiFiWebClient)
...

And execute:
  $ cmake -G "MinGW Makefiles"

  ...

  CMake Warning (dev) in example/CMakeLists.txt:
  Policy CMP0022 is not set: INTERFACE_LINK_LIBRARIES defines the link
  interface.  Run "cmake --help-policy CMP0022" for policy details.  Use the
  cmake_policy command to set the policy and suppress this warning.

  Target "uno_example" has an INTERFACE_LINK_LIBRARIES property.  This should
  be preferred as the source of the link interface for this library but
  because CMP0022 is not set CMake is ignoring the property and using the
  link implementation as the link interface instead.

  INTERFACE_LINK_LIBRARIES:

    uno_CORE;uno_example;uno_Wire

  Link implementation:

    uno_CORE;uno_Wire

This warning is for project developers.  Use -Wno-dev to suppress it.

CMake Warning (dev) in example/CMakeLists.txt:
  Policy CMP0022 is not set: INTERFACE_LINK_LIBRARIES defines the link
  interface.  Run "cmake --help-policy CMP0022" for policy details.  Use the
  cmake_policy command to set the policy and suppress this warning.

  Target "uno_Wire" has an INTERFACE_LINK_LIBRARIES property.  This should be
  preferred as the source of the link interface for this library but because
  CMP0022 is not set CMake is ignoring the property and using the link
  implementation as the link interface instead.

  INTERFACE_LINK_LIBRARIES:

    uno_CORE;uno_Wire

  Link implementation:

    uno_CORE

This warning is for project developers.  Use -Wno-dev to suppress it.

CMake Warning (dev) in example/CMakeLists.txt:
  Policy CMP0022 is not set: INTERFACE_LINK_LIBRARIES defines the link
  interface.  Run "cmake --help-policy CMP0022" for policy details.  Use the
  cmake_policy command to set the policy and suppress this warning.

  Target "uno_SPI" has an INTERFACE_LINK_LIBRARIES property.  This should be
  preferred as the source of the link interface for this library but because
  CMP0022 is not set CMake is ignoring the property and using the link
  implementation as the link interface instead.

  INTERFACE_LINK_LIBRARIES:

    uno_CORE;uno_SPI

  Link implementation:

    uno_CORE

This warning is for project developers.  Use -Wno-dev to suppress it.

CMake Warning (dev) in example/CMakeLists.txt:
  Policy CMP0022 is not set: INTERFACE_LINK_LIBRARIES defines the link
  interface.  Run "cmake --help-policy CMP0022" for policy details.  Use the
  cmake_policy command to set the policy and suppress this warning.

  Target "uno_WiFi" has an INTERFACE_LINK_LIBRARIES property.  This should be
  preferred as the source of the link interface for this library but because
  CMP0022 is not set CMake is ignoring the property and using the link
  implementation as the link interface instead.

  INTERFACE_LINK_LIBRARIES:

    uno_CORE;uno_WiFi

  Link implementation:

    uno_CORE

This warning is for project developers.  Use -Wno-dev to suppress it.

-- Generating done
-- Build files have been written to: ~/arduino-cmake-master

Later I execute:
$ mingw32-make

...

Linking CXX static library libuno_WiFi.a
[ 89%] Built target uno_WiFi
Scanning dependencies of target wifi_example
[ 92%] Building CXX object example/CMakeFiles/wifi_example.dir/wifi_example_WiFiWebClient.cpp.obj
Linking CXX executable wifi_example.elf
libuno_WiFi.a(WiFiClient.cpp.obj): In function `WiFiClient::status()':
C:\Program Files\Arduino\libraries\WiFi/WiFiClient.cpp:160: undefined reference to `ServerDrv::getClientState(unsigned char)'
libuno_WiFi.a(WiFiClient.cpp.obj): In function `WiFiClient::stop()':
C:\Program Files\Arduino\libraries\WiFi/WiFiClient.cpp:131: undefined reference to `ServerDrv::stopClient(unsigned char)'
libuno_WiFi.a(WiFiClient.cpp.obj): In function `WiFiClient::peek()':
C:\Program Files\Arduino\libraries\WiFi/WiFiClient.cpp:117: undefined reference to `ServerDrv::getData(unsigned char, unsigned char*, unsigned char)'
libuno_WiFi.a(WiFiClient.cpp.obj): In function `WiFiClient::read()':
C:\Program Files\Arduino\libraries\WiFi/WiFiClient.cpp:101: undefined reference to `ServerDrv::getData(unsigned char, unsigned char*, unsigned char)'
libuno_WiFi.a(WiFiClient.cpp.obj): In function `WiFiClient::read(unsigned char*, unsigned int)':
C:\Program Files\Arduino\libraries\WiFi/WiFiClient.cpp:107: undefined reference to `ServerDrv::getDataBuf(unsigned char, unsigned char*, unsigned int*)'
libuno_WiFi.a(WiFiClient.cpp.obj): In function `WiFiClient::available()':
C:\Program Files\Arduino\libraries\WiFi/WiFiClient.cpp:90: undefined reference to `ServerDrv::availData(unsigned char)'
libuno_WiFi.a(WiFiClient.cpp.obj): In function `WiFiClient::write(unsigned char const*, unsigned int)':
C:\Program Files\Arduino\libraries\WiFi/WiFiClient.cpp:73: undefined reference to `ServerDrv::sendData(unsigned char, unsigned char const*, unsigned int)'
C:\Program Files\Arduino\libraries\WiFi/WiFiClient.cpp:78: undefined reference to `ServerDrv::checkDataSent(unsigned char)'
libuno_WiFi.a(WiFiClient.cpp.obj): In function `WiFiClient::connect(IPAddress, unsigned int)':
C:\Program Files\Arduino\libraries\WiFi/WiFiClient.cpp:36: undefined reference to `ServerDrv::startClient(unsigned long, unsigned int, unsigned char, unsigned char)'
libuno_WiFi.a(WiFi.cpp.obj): In function `WiFiClass::hostByName(char const*, IPAddress&)':
C:\Program Files\Arduino\libraries\WiFi/WiFi.cpp:228: undefined reference to `WiFiDrv::getHostByName(char const*, IPAddress&)'
libuno_WiFi.a(WiFi.cpp.obj): In function `WiFiClass::status()':
C:\Program Files\Arduino\libraries\WiFi/WiFi.cpp:223: undefined reference to `WiFiDrv::getConnectionStatus()'
libuno_WiFi.a(WiFi.cpp.obj): In function `WiFiClass::RSSI()':
C:\Program Files\Arduino\libraries\WiFi/WiFi.cpp:181: undefined reference to `WiFiDrv::getCurrentRSSI()'
libuno_WiFi.a(WiFi.cpp.obj): In function `WiFiClass::SSID()':
C:\Program Files\Arduino\libraries\WiFi/WiFi.cpp:169: undefined reference to `WiFiDrv::getCurrentSSID()'
libuno_WiFi.a(WiFi.cpp.obj): In function `WiFiClass::localIP()':
C:\Program Files\Arduino\libraries\WiFi/WiFi.cpp:149: undefined reference to `WiFiDrv::getIpAddress(IPAddress&)'
libuno_WiFi.a(WiFi.cpp.obj): In function `WiFiClass::begin(char*, char const*)':
C:\Program Files\Arduino\libraries\WiFi/WiFi.cpp:87: undefined reference to `WiFiDrv::wifiSetPassphrase(char*, unsigned char, char const*, unsigned char)'
C:\Program Files\Arduino\libraries\WiFi/WiFi.cpp:92: undefined reference to `WiFiDrv::getConnectionStatus()'
libuno_WiFi.a(WiFi.cpp.obj): In function `WiFiClass::init()':
C:\Program Files\Arduino\libraries\WiFi/WiFi.cpp:22: undefined reference to `WiFiDrv::wifiDriverInit()'
example\CMakeFiles\wifi_example.dir\build.make:95: recipe for target 'example/wifi_example.elf' failed
mingw32-make[2]: *** [example/wifi_example.elf] Error 1
CMakeFiles\Makefile2:748: recipe for target 'example/CMakeFiles/wifi_example.dir/all' failed
mingw32-make[1]: *** [example/CMakeFiles/wifi_example.dir/all] Error 2
Makefile:74: recipe for target 'all' failed
mingw32-make: *** [all] Error 2

The problem is the Arduino.cmake because it's not linking correctly with the library WiFi, but it links with the Wire library.
Anyone knows why that warning appears and why Wire links ok but WiFi doesn't?
Thanks!
Note: I'm using original code which is in the repository example, I've not modified this one.

Can you confirm that you could generate the examples BEFORE modifying CMakeLists.txt? Also, did you modify something else in this file?

The warning given by cmake does not seem to be a problem (I got the same warning for one of my example projects and it works fine afterwards). Have you tried using another generator (I'm using "Unix Makefiles" and it works fine for my project; I just had to install a Windows version of make).

Another point: did you try generate_arduino_library(WiFi...) first, defining all headers and source files included in WiFi directory? Indeed, I don't think cmake will be able to build the library properly as it should not be able to find files in subdirectory utility: these are the files that contain definitions that mingw32-make is complaining about.

Related to my previous comment, a faster option that you could try is set(WiFi_RECURSE True); it tells cmake to compile all files including those in subdirectories of the WiFi library.

Your question actually has 2 distinct parts:

Why does arduino-cmake generate the warning "Policy CMP0022 is not set: INTERFACE_LINK_LIBRARIES..."?
Why does make, using the generated MakeFile, fail when building WiFi example?

First off, the arduino-cmake "Policy CMP0022" is just a warning, not an error. As per this cmake article, that CMP policy has been only recently introduced in CMake 2.8.12.
You get this warning simply because arduino-cmake has been created based on an older version of cmake and thus does not specifically support this new policy.
In order to get rid of this warning, the documentation mentions you should add the cmake_policy(SET CMP0022 OLD) command to your cmake configuration.
Unfortunately I tried it in the example CMakeLists.txt to no avail; maybe it has to be set directly in arduino-cmake files (which I have not tested).
Thus, if you want to get rid of this boring warning, it seems the only solution you are left with is to disable all warnings when launching cmake:

cmake -G "MinGW Makefiles" -Wno-dev

This works fine and has removed all warnings..
Your second problem (the real one I would say) is due to to the structure of WiFi library:

Indeed, as you can see above, it has a utility subdirectory that contains additional source code that cannot be found by arduino-cmake, as by default it searches for source code files only at first level directory.
How to solve it? Just tell arduino-cmake to do a recursive search for the WiFi library; in your CMakeLists.txt, ensure you add the following line:
set(WiFi_RECURSE True)
generate_arduino_example(wifi_example
                     LIBRARY WiFi
                     EXAMPLE WiFiWebClient)

The added set(WiFi_RECURSE True) line just tells arduino-cmake that, for WiFi library, it should recurse through subdirectories when looking for source code.
I have checked it with "Unix Makefiles" (not "MinGW Makefiles" but I guess that won't make any difference) and it worked fine.

source: Stack Exchange

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

sort: votes


text:
What's the most efficient implementation of map(x,0,1023,50,250)?
I recently noticed how the map() function in Arduino was bulky in both terms of flash space used and time taken to execute, largely because it deals with long and involves a division and multiplication.
Many times you can replace maps with more basic functions i.e.
output = map(input,0,1023,0,255);

can become
output = input >> 2;

or
output = map(input,0,1023,1023,0);

can become
output = 1023 - input;

I have one line in some code that says:
backlight = map(LDRreading,0,1023,50,250);

How could this be simplified so that it is both space and time efficient?
I'll allow slight differences in output values if it results in a much better solution.

The screenshot shows a base-2 (i.e. binary) result of calculating the constant part of a mapping. You can approximate this multiplication by a constant by a number of shifts added together. You need to break down each multiplication in the result first:
x * 0.0012 = x >> 3
x * 0.00012 = x >> 4
x * 0.00000012 = x >> 7
Then add these together. You are essentially breaking it down into convenient base-2 multiplies (which can always be represented by shifts) and adds - nearly always more efficient.
This doesn't get you right to 250, but pretty close:
>>> for i in range(0, 1024, 34):
...   print (i >> 3) + (i >> 4) + (i >> 7) + 50
...
50
56
62
   [snip]
235
241
247
>>> print (1023 >> 3) + (1023 >> 4) + (1023 >> 7) + 50
247

Do all your processing with a left-justified int (ADLAR=1) though, to minimize errors. The ADC returns a 10bit result, and ADLAR choses if this is aligned to the left or right of the two result registers.

Great answer. I have clarified how you got from the calculator result to the code, hope that is ok.

This is an excellent technique in general, but the original range was 1024, not 1023 (the 0 counts).

How about this, mapping to 50..249?
output = ((input * 25) >> 7)+50;

Your input range was 1024 (0..1023). Output range is 200 (In the original specification, it would have been 201, which does not divide as neatly). These have a gcd of 8, so output = (input * (200/8)) / (1024/8) + 50 will do, and the division by a power of 2 can be expressed with a shift. The nice thing is that 1024*25 still fits into a 16 bit integer, so no longs are needed.
If you want full range, you can try throwing in rounding
output = ((input*25+64) >> 7)+50;

Actually I'd say the input range is 201 as both boundaries are included.

@jfoilpret, I agree, that's why I said my solution (at least without the rounding) only covers 50..249.

Ah ok, sorry I misunderstood your statement "output range is 200"; maybe you should add " (instead of the expected 201)" that would clarify your answer.

You could approximate it quite closely using only two integer operations:
backlight = (LDRreading / 5) + 46;

That effectively maps input range 0 - 1023 onto output range 46 - 250, so it's fairly accurate. If LDRreading is a 2 byte integer type then it should be significantly more efficient (comparatively speaking) than anything which uses long.

The problem with division by a number that is not a power of 2 is that the AVR has no instruction for it, hence the compiler has to generate a bunch of instructions for this computation, which makes the formula longer to calculate.

If the input range is limited in size and you have the memory for it nothing beats a simple lookup-table.
like
unsigned char map[1024] = { 50, 50, << more entries here  >>, 250 } ;
You can pre-compute the content in a part of the program that isn't time-critical or just compute the entire table-content beforehand and put it verbatim in the source-code.
Doing a map is just a read of map[] with the original value as index.
If you input range starts with a non-zero number just decrement all inputs by the lower-bound value so you have a 0-base index for the map array. (That works for negative lower-bounds too !)
At most 1 substract (to adjust for a non-zero lower-bound) and 1 addition to calculate the array-base + index.
And a good compiler will be able to optimize it further.
You can't get more efficient than that, but you do need the space to store the table somewhere.

This is extremely space inefficient though and only marginally faster than the shift/add which gets very very close.

@Cybergibbons It is only marginally yes, but the question was about efficiency. If every cycle counts... Space efficiency could be an issue for larger tables, but I already mentioned that in my answer. I mainly posted this as a more generalized answer because many people don't realize that this technique exists at all. And it has far wider application than just Arduino's. (Check your C-library's implementation of isspace(), isalpha(). Most implementations use this technique extensively.)

"both space and time efficient" was the question :). isalpha() certainly doesn't use a lookup table in avr-libc. It's very memory heavy - 1Kbyte of RAM (1/2) or flash (1/32).

@Cybergibbons Embedded Libc do (mostly) things differently, but generic ones often make extensive use of lookup-tables. I have to admit I missed the "space" word in my initial read of the question.

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


text:
Arduino Serial Monitor only returning Null Characters
I'm trying to simply access my HC_05 bluetooth module and conduct some AT commands through the Serial Monitor. For some reason though, it only seems to be returning Null characters, though it does some to be actually responding to the command in some way (given by the length of Null characters it returns.

So you can clearly see that the command AT and AT+NAMEdevice return different data, but they are both all NUL blocks. I am viewing the monitor in text. Changing the view to Hex or ASCII does not change results.
Code for this simple program is below:
#include <SoftwareSerial.h>

SoftwareSerial BTSerial(10, 11); // RX | TX

void setup()
{
  pinMode(9, OUTPUT);  // this pin will pull the HC-05 pin 34 (key pin) HIGH to switch module to AT mode
  digitalWrite(9, HIGH);
  Serial.begin(9600);
  Serial.println("Enter AT commands:");
  BTSerial.begin(38400);  // HC-05 default speed in AT command more
}

void loop()
{

  // Keep reading from HC-05 and send to Arduino Serial Monitor
  if (BTSerial.available())
    Serial.write(BTSerial.read());

  // Keep reading from Arduino Serial Monitor and send to HC-05
  if (Serial.available())
    BTSerial.write(Serial.read());
}

Wire Diagram is as here
NOTE I have used both a direct connection to the 5V and also used a Voltage Divider. Neither changes the NUL return.

A couple of question/suggestions. Have you set the serial monitor baud rate to 9600? Try adding a small delay (5ms) at the end of loop. In the past I have had trouble with SoftwareSerial. It can cause trouble. Try using the hardware serial (pins 0 and 1) and see if you can communicate with it.

@StefanBossbaly Yes, all of those things have been tried, and none with any positive results. The error persists throughout all of them.

Are you sure the module is running at 38400 baud?

Shouldn't it be while (BTSerial.available()) and while (Serial.available()) instead of if...?

Have you tried to force the Key pin of HC-05 directly to +V, instead of using Arduino pin 9, just to remove one potential issue?

First, change all Serial.write to Serial.print I think that might be half your problem.
Next,
  pinMode(9, OUTPUT);  // this pin will pull the HC-05 pin 34 (key pin) HIGH to switch module to AT mode
  digitalWrite(9, HIGH);

The way you are doing this will probably put the HC-05 into 9600 baud mode. You can fix this one of two ways:
Change BTSerial.begin(38400); to BTSerial.begin(9600);
Or, as jfpoilpret suggested, tie the Key pin directly to VCC.  The reason is that in order to go into 38400 baud mode, there must be voltage on Key at the time the module is powered up.  By the time the digital write in your code happens, it's too late.
If for some reason you'd like to have digital control over the Key pin rather than directly wiring it to VCC, yet you'd like the module to operate at 38400 baud, you can simply change the default baud rate by issuing the appropriate AT command - I believe it's AT+UART= off the top of my head.
Also, I'm not sure, but jfpoilpret might be right as well about how your serial read/write handling is done within loop() but here is code that I know works:
#include <SoftwareSerial.h>

SoftwareSerial BTSerial(10, 11); // RX | TX
char myChar;

void setup()
{
  ...
}

void loop() {
  while (BTSerial.available()) {
    myChar = BTSerial.read();
    Serial.print(myChar);
  }

  while (Serial.available()) {
    myChar = Serial.read();
    Serial.print(myChar); //echo
    BTSerial.print(myChar);
  }
}

This sounds like baud-rate mismatch. These dongles don't have a reset ability; they remember their most recent settings. See my answer to another user having trouble communicating with one these.


text:
What is the maximum power consumption of the Arduino Nano 3.0?
What is the maximum power consumption (in mW) of the Arduino Nano 3.0, when it is running in its default state (at 16MHz, no LEDs removed) and powered by an external regulated 5V supply so it bypasses the built in voltage regulator?
This will give us an upper bound on the power consumption of the Arduino Nano that can be used during estimates.

In this line of the answer: So depending on how much you use the serial port, and the leds I would guess around (2.4 + 15 + 44) = 33.4 mA I don't really get why you multiply 44, wouldn't it be 2*4?

Well, it depends on what you have attached to the Arduino. If you are using the pins to do things you will definitely require more current.
If you ONLY want to power the Arduino, then I calculated what I think it should be below. (You should also check with someone who owns this device for an experimental value, and not just a calculated value. )
Based on the datasheet (fig 30-8, p 319), I would say the the processor will draw around 2.4 mA at 5 volts.
http://www.atmel.com/images/doc2545.pdf
The USB chip draws around 15 mA depending on several things (p 18)
http://www.ftdichip.com/Support/Documents/DataSheets/ICs/DS_FT232R.pdf
Then you have 2 LEDs with 680 ohm resistors. (Assuming 2 volt drop for each led)
(5-2)/680  = around 4 mA per led.
So depending on how much you use the serial port, and the LEDs I would guess around (2.4 + 15 + 4*4) = 33.4 mA
33.4 mA * 5V  = 0.167 Watts
I suspect you want to know to the total amount of power the Arduino can source, which is a bit harder to calculate.
The pins can provide up to 200 mA. (p 303 http://www.atmel.com/images/doc2545.pdf)
So 33.4 + 200 = 233.4
I would also add a 20% safety margin (around 50 mA)
So I would want a 280 mA supply, if I was going to attach the Arduino to different things.
280 mA * 5 = 1.4 Watts
Let me know if my numbers are way off.
P.S.: Be careful making your own supply. It is critical that the voltage be very stable. An unstable supply can/will destroy an Ardiuno. I suggest using a linear regulator, like the LM7805. or maybe the LM317

7805 and 317 both peak initially at 6V when first powered up from f.x. 12V. Doesn’t destroy my boards though.

@user13180 - clamp with a Zener and use a cap

does the usb draw that much if it is used nly to power the board? DO you have a good library to put Nano to sleep? Thanks

Yes, the i/o can source 40mA @ 5v (or 3v3) per pin, but the limit is'nt 40mA from each pin simultainiously but the limit is the processors dissipation. Read the 328A data sheet carefully and the truth will become clear.

From website https://store.arduino.cc/usa/arduino-nano:  Each of the 14 digital pins on the Nano can be used as an input or output. They operate at 5 volts. Each pin can provide or receive a maximum of 40 mA.
Therefore i would assume maximum power consumption is 14 x 40mA x 5V = 2.8W, depends on the board effeciency %, for example let's say 80%, so input could be 3.5W, but again you rarely use all 14 pins at once as outputs hence it is way way lower than 3.5W.This is just a ballpoint figure.

If an individual pin can provide 40mA, it does't mean that they can provide 560mA at once.

"Each of the 14 digital pins on the Nano can be used as an input or output."
There are 6 analog input pins which are also digital pins, you must take those into account.
However, Note 3 under Table 32-2 of the '328P datasheet says:
"Although each I/O port can source more than the test conditions (20mA at VCC = 5V, 10mA at VCC = 3V) under steady state conditions (non-transient), the following must be observed:
3.1. The sum of all IOH, for ports C0 - C5, D0- D4, ADC7, RESET should not exceed 100mA.
3.2. The sum of all IOH, for ports B0 - B5, D5 - D7, ADC6, XTAL1, XTAL2 should not exceed 100mA.
(but ADC6 and ADC7 are analog input only, and should not be sourcing current)
So I would suggest that to keep your Nano healthy, 200mA x 5V = 1W be considered for the IO, and then the amounts noted above for the Power LED, L LED (which is driven by D13), and internal running of the chip be taken into account.

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


text:
How frequently do you need to poll UI buttons before they are perceived as laggy?
Whilst it is possible, and sometimes desirable, to use pin change interrupts to read the state of buttons, it is simpler to poll the state of buttons in loop(). This is a commonly used technique.
If you loop() executes quickly enough, then button presses are always going to be caught and the user will not be able to perceive any delay or lag.
It is possible that your loop would take so long as to cause a delay or lag to be perceived.
The question is, how long would it be, in general, before a user would see this?

If your loop() is rather slow (I mean, too slow to be able to give fast enough feedback to the end user), you could possibly use an ISR on pin level change and provide immediate feedback (if this can be calculated fast) to the user, or give him temporary feedback (eg LED lit on) to tell him his request has been recognized and will be processed shortly (in loop()); you would let loop() by setting some global bool variable in the ISR.

It's probably one of the few times where key-click is useful.

The short answer is that you have 100 miliseconds to respond to the user if you want them to feel the action occurred instantaneously.
According to Jacob Nielsen in his book Usability Engineering, from 1993, which is considered an important reference in Systems Usability and User Experience:

0.1 second is about the limit for having the user feel that the system is reacting instantaneously, meaning that no special feedback is necessary except to display the result.

He also mentions that this basic advice regarding response times has been about the same for many decades [Miller 1968; Card et al. 1991].
I've taken this citation from this article: Response Times: The 3 Important Limits, also writen by Jacob Nielsen.
Note that in this time you must include all time taken to read the button press and give feedback to the user.
Other response time thresholds that are important for user experience, from the same source, but that were not mentioned directly by the OP are:

1.0 second is about the limit for the user's flow of thought to stay uninterrupted, even though the user will notice the delay. Normally, no special feedback is necessary during delays of more than 0.1 but less than 1.0 second, but the user does lose the feeling of operating directly on the data.

10 seconds is about the limit for keeping the user's attention focused on the dialogue. For longer delays, users will want to perform other tasks while waiting for the computer to finish, so they should be given feedback indicating when the computer expects to be done. Feedback during the delay is especially important if the response time is likely to be highly variable, since users will then not know what to expect.

Brilliant answer. Thanks for the extra info, it's also helpful.

It's commonly known that people are unable to perceive changes when they happen underneath 10ms after their action. This responsiveness will result in an experience that has recently mostly been described as "snappy". It's noticeable but for users it's hard to put a name on it.
So if you want perfection, take about 15ms of delay. If you want really good, take 100 ms of delay. 100ms is 50ms on average, and will certainly pass for people.
The application and the expected response time is vital too. A sliding door or elevator is given very large tolerance (as the physical object will always take a lot more time) whereas ticket vending machine interfaces are not given any time at all.
The upper limit for polling would be around 1500ms. Around there people will always notice it is slow.
This data is purely personal experience as a gamer and programmer. YMMV and remember that just trying it yourself is the best way to find out how it feels. The only "scientific" answer is the <10 milliseconds, beyond that it's about the ability to perceive the delay (which varies per person and moment) and the tolerance of the user.
As a side note, you can try fluctuating the delays in order to conserve battery or CPU time when the interface is not being used. The user-action, the faster the polling. When the application is doing it's thing, poll very slowly. Better to poll when it matters!


text:
Writing First Library - Serial Stream Object
I have done quite a few projects with Arduino, but have never done more than a "Hello World" in C. I am writing my first library, and a lot of the object oriented stuff is going over my head. Anyway, my library is working as it is supposed to, I pass a float to my function and it formats it properly and sends it out over serial. However, I implemented it in a clunky way. The Arduino API Style Guide mentions a way that seems much better:

When using serial communication, allow the user to specify any Stream object, rather than hard-coding "Serial". This will make your library compatible all serial ports on Mega and the Due, and can also use alternate interfaces like SoftwareSerial. The Stream object can be passed to your library's constructor or to a begin() function (as a reference, not a pointer). See Firmata 2.3 or XBee 0.4 for examples of each approach.

Can anybody elaborate on how to do this, or show me some code?

Here is a simple example (built and tested with a mega2560), with a class that can be passed a Stream object, and sends a Hello over this generic stream object. When constructing the object, you can pass the Stream object you want to actually communicate:
#include "Arduino.h"

class MyProtocol
{
public:
    MyProtocol(Stream& s):serial(s){}
    void send(){
        serial.println("Hello");
    }
private:
    Stream& serial;
};

MyProtocol p(Serial);

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

void loop() {
    delay(1000);
    p.send();
}

NOTE: The serial.println() is not the Serial global object, note the lower case, it is the internal Stream class variable.
If you are confused with the OO and classes, take into account (while you gain more knowledge about it) that this approach can be also used with a simple function, you can pass the serial parameter. Furthermore, it is not necessary to hardwire the Serial interface for ever, you can in fact switch in run time and use a different channel depending on some condition:
#include "Arduino.h"

void send(Stream& serial){
    serial.println("Hello");
}

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

void loop() {
    delay(1000);
    if(someCondition)
        send(Serial);
    else
        send(Serial1);
}

You can also declare the constructor as MyProtocol(Stream& s=Serial):serial(s){} sou you don't need to pass the Serial but you can if you want to. You would build then build the object just as MyProtocol p;

Thanks, this was really helpful, it took some work but I figured it out. You can see the result on my Github.


text:
Which type of Motor Drivers to drive Unipolar Stepper Motors?
I hope this question is specific enough. Basically I want to know if it matters a great deal what kind of Motor Driver IC(s) or pre-assembled kits you use to drive a Unipolar Stepper Motor.
For example: Can the following Driver be used to control this Stepper Motor?
Driver: https://www.sparkfun.com/products/9670
Motor: http://www.jaycar.com.au/productView.asp?ID=YM2754
Thanks!

You can abuse a L298 (like the one you link) to drive unipolar motors, but it's not the ideal tool for it. Really, you just need power transistors. Or get a bipolar motor.

Even if in this forum people may know and help, maybe you should try also in a more specific one, e.g.: http://electronics.stackexchange.com/ as this question is in fact not related at all with arduino

We already have a 12VDC Unipolar Stepper Motor as mentioned in the Question. This is specifically about Arduino-like boards and Stepper motor drivers.

It does matter.  There are pros and cons to each different driver setup.
If you wire the motor as a bipolar, which I'm not sure that you can, you can use the driver that you linked, but it is not very good for driving stepper motors.  https://www.sparkfun.com/products/11876 is a better driver for steppers for half the price.  (still have to wire it bipolar)
If you need to stick with unipolar wiring, PCBheaven.com shows an example using a CD4017, MOSFETs, and diodes to run a unipolar motor.  It will only turn one direction.  Instead you could use a micro-controller, such as an Arduino, in place of the CD4017 along with logic-level MOSFETs to go both directions.
A tutorial on the Arduino site uses a ULN2003A, which is not powerful enough to drive your motor to its full potential (does it need to turn, or turn well?) and doesn't have the diodes (important to protect your IC!), but the Arduino sketches would still work using the schematic from PCBheaven.
A couple of complete driver boards:
UNIPOLAR STEPPER MOTOR DRIVER
FANCY UNIPOLAR STEPPER MOTOR DRIVER

If you could add links to suitable pre-built Unipolar drivers that can be purchased I'll accept this. Finding any has proven difficult at best -- most are bipolar or micro-stepping drivers :/

I have edited my answer.  The first stepper I bought was a really cheap unipolar.  I learned many things by goofing around with it!  Then, when I was ready, I found a good bipolar driver/motor combination that is much more fun to play with. :)

A minor correction: The ULN2003A has the diodes built in.


text:
Changing the brightness on a Hitachi HD44780 LCD screen
I am finishing up a project- an LED game alarm clock. Seeing as this is a clock, I need to have a way to conserve power, which right now my Uno R3+ is eating up like a politician. My question is, how do I turn the screen off, or turn the back-light off using software only on a Hitachi HD44780 16x2 LCD screen? Or how do I set a sleep mode on one component? The way I plan on turning it off is with an ultrasonic range finder, if I get close it turns on the screen. If anything I say doesn't make sense, ask me to clarify, I'm in a bit of a rush.

Whether this can even be done is entirely dependent on how you have the LCD screen connected. The HD44780 command set has no provisions for backlight control. You would need to add some external mechanism of your own for controlling the backlight.

Place a transistor in series with a 33R resistor between the LCD pin 16 (backlight ground) and GND and switch the transistor on and off with a digital pin. That way you'll be able to turn the backlight on and off.
You can have a finer control over brightness if you put a PWM pulse on said pin. Just call analogWrite(D3, value) where value is the desired brightness.
The schematics is below. It's from Freetronics 16x2 LCD SHield.

+1 for the schematic, although I'm not sure why there are two resistors (R7 & R8).

@Madivad - I'm guessing it's to increase maximum dissipated power that the resistors can take. The two 68R resistors in parallel result in an equivalent 34R resistence but doubles the maximum power that can be dissipated through a single resistor. I don't remember what resistors were recommended by Freetronics, but in my case, I've used two 1/4W 68R resistors and the board is working ok. Also, I suppose that 68R resistors are more common. That certainly holds true for me as I have plenty of 68R resistors in my bins and no 33R ones.

I know this is "old", but hope someone will notice this... I'm having trouble understanding how the transistor connects (as i'm not familiar with the icon above for the transistor), where does the E, B, C connect to?

@wara -  That's a Field Effect Transistor (FET), not a BJT. So you'll be looking to connect its drain, source and gate. In any case, you'll get better help by asking a separate question, linking to this one.

Instead of tying the backlight directly to V+ and GND, connect it to a PWM pin (you may need to use a separate driver if the pin cannot source/sink enough current). This will allow you to control the brightness via analogWrite().
Turn the LCD display off (LiquidCrystal::noDisplay()) when not actively in use. The contents will remain in memory but the LCD segments will not be driven.
Set the various bits in the PRR register to disable any peripherals not it use.
And don't forget to sleep the CPU when it doesn't need to run. See the "Power Management and Sleep Modes" section of the datasheet for more information about this and the PRR register, as well as the <avr/sleep.h> documentation for AVR Libc.

Sleeping the MCU is pointless, since the rest of the parts on a common uno consume so much power it doesn't provide any meaningful reduction in overall consumption..

Really, if you want to actually get an arduino to be low-power, you need an arduino pro (or any other board with no onboard usb-serial), and then you'd need to put a regulator with decently low quiescent current draw on it. It's a bit involved.

Absolutely. Someone that wants to conserve every last bit of energy will design their own board and spec their components out accordingly.

Yep, but my point is that you can't even get meaningfully relevant power conservation on most any arduino boards, since even their vregs have horrible quiescent current (2 ma +, IIRC). Then there is the FTDI/ATmega16U2, which you can't turn off, etc....

@Mr.Floppy: IOW, pick something else. Something with fewer pieces.

@ConnorWolf Well, if you do actually measure the rail current of an Uno running the delay-based blink sketch vs a rewrite of the same based on timer interrupts and properly deep sleeping — you'll see that sleeping the MCU is not so pointless. In my case, the numbers were something like 30 mA vs 17 mA. Still quite a drain; but your point has been invalidated by an experiment.

43% is... less terrible, but still not great.


text:
How to measure total energy usage of an arduino board
I have a project that I'm currently working on. We have built a green wall, wich consists of plants on a wall

Now, we have a pump situated at the bottom that waters all the plants. There is an arduino board that decides when to put the pump on. Powering it is a solar panel and wind turbine. We want to know how much energy we have saved by using the solar panel and turbine.
Question:
How do I measure the amount of energy, in Wh, used from 00h00 that day? Is there a library? Or is this not possible with Arduino?
Thanks a lot.
To clear up some things
No, the pump is not fueled directly by the Arduino pin. We are using a motor shield.
Yes, there is an accumulator in the circuit. The solar and wind power recharge a battery which in turn powers the components.
I would like to know the entire energy consumed, not just the pump.

You want to know the current used by the board, not the volts. The volts will be constant. The current will change as the motor turns on/off.

Or more accurately, you want the energy (in Wh, Watt-hour) consumed since 00:00. To calculate the energy, you need the voltage, which is a constant, and the trend of current (in A or mA, Ampère) over time.

Ok i'll try that

You mentioned a pump: is it directly sourced by an Arduino pin (I hope not). What are the specs for the pump? I guess most energy consumed will come from there, hene you may possibly consider eneegy for Arduino itself negligible.

@jfpoilpret Using solar and wind power, chances are that neither voltage nor current is constant. Otherwise your method is correct. Energy[Wh] = V[V] × I[A] × t[s] / 3600[s/h]

@jippie Yeah but I guess there must be some accumulator in the circuit, that will provide an almost constant voltage. A global vision of the circuit would be useful.

@DLJ is it really the energy consumed by the sole Arduino board you want to know (as suggested by your question)? Or are you interested in the energy consumed by all your system, pump included (which seems more relevant to me)? Can you also confirm that the pump uses the same source as the Arduino, i.e. solar panel and wind turbine (I guess so)?

Basically you have 2 options to compute the consumed energy. First is experimenting and meaasuring currents with a DMM during various operations phases, then integrating this into your Arduino program as you must know how long your pump is on. Second way is to measure current in real-time with a current sensor and perform calculations based on that.

In order to calculate the amount of energy you have to calculate the power first.
The relation is
Energy = (Power * Time of usage)
How to calculate the power?
The voltage for each device in the system is constant. What changes is the current withdrawal in each component in the project.
The main thing you have here is the pump and how much does it consume current.
Usually, you will have on the "plate" of the pump the current withdrawal of it.
Say it consumes 2 Amps.
If that is not available there, use a DMM "Digital Multimeter" and connect in series with the pump and measure the amount of current.
If there are any other major/important components in your project just calculate the current withdrawal from them.
Now add up all the currents and say you ended up with 2 Amps.
If all the components are operating at the same voltage, just multiply the total amount of current withdrawal by the voltage.
WHY?
Because:
P(power) = V(voltage)   * I(current)
If not, just find the power of each component.
Add up all the powers of all you components.
Now you will only have to calculate the energy.
E(Energy) = Power * time
Time here refers to how long is your system working?
Is it a full day, couple of hours. IT doesn't matter. Usually to make things easier use time (in terms of hours).
Say your power ended up with 3kW kilo Watt
You've run the system for 2 hours every day
Energy = 3 * 2 = 6 kWh
If you've kept this for a full month.
Energy save in a month = 180kWh.
Just find out how much do the ministry cost for each kWh, and you'll know how much money you've saved!

I think this formula can't apply asi-is in this case as current consumption will vary dramatically when the pump is on (and that's not always fortunately).

He can find out the starter current ( In rush current) and see how much percentage increase sis that from normal operation. He then can add this percent -just in case- to compensqte for this error. Of course he has to see on avg how many times is he pump turned on. I think that will not make a big difference because the duration of starter current is really small.

I think this can help me a lot. I'll try it and then say what happens. Thanks!

There are some chip that measure current flow (like ACS714). Just be sure to buy a chip that will not fry under your load, and mount it in serie with the pump. That chip will bring an analog (but there a re "smarter" chip witch use i2c or spi) signal to arduino, using the formula on the datasheet you can find out real (well, as always there are small error) current flow.
You should already know the voltage of the pump, but you can easily read it with a similar chip or even a voltage divider, just pay attention if you are using PWM as if it will fake your reading)
Now, as already pointed out by Adel Bibi, you can multiply the voltage of the pump with the current value readed (find power), multiply with the time elapsed from the last measure and sum up with precedent measure (integral of the power by time)
you can do the same on the wind/solar panel, just invert the sign of the current (as you are Producing and not Consuming power) and voilà!

With the accumulator in the system, current draw will increase as that is topped off. The accumulator provides sufficient pressure to drive the system. As system pressure draws down, the pump turns on to bring up the accumulator, with maximum draw nearing cut-off pressure. Taking the total run time of the pump in question (@DLJ) you may chop this up into discrete chunks and measure the draw over those periods, plot that out. I like that greenwall, and I want one. -- Aloha nui loa, MKK
edit -- As an aside, even a 12V pump driving the smallest 1 liter accumulator to 250 kPa, will draw up to 3A for a few moments, given the size of your system. What motor shield are you using?


text:
How to call C functions from Arduino sketch?
I would like to know if there is a way to call functions that are contained within C files using an Arduino sketch?
My C file declares and defines a function. To save putting the messy function definition into my Arduino sketch, I'd like to call the function straight from the sketch.
Is there a standard way to do this using Arduino and C?
Here is the sketch:
#include "crc16.h";

void setup(){

}

void loop(){

  CalculateCRC16("<09M", 4);

}

and this is the trimmed down C file:
#include <stdio.h>
#include <stdint.h>

uint16_t crctable[256] =
{
    0x0000, 0x1189,.....

uint16_t // Returns Calculated CRC value
CalculateCRC16( // Call example CalculateCRC16("<09M", 4);
    const void *c_ptr, // Pointer to byte array to perform CRC on
    size_t len)        // Number of bytes to CRC
{

    uint16_t crc = 0xFFFF // Seed for CRC calculation
    const uint8_t *c = c_ptr;

    while (len--)
        crc = (crc << 8) ^ crctable[((crc >> 8) ^ *c++)];

    return crc;
}

Is there a reason why your file has to use C instead of C++?

Actually, yes. When I try to compile the file using C++, there are errors, but it is error free in C. The error is caused by the lines: const void *c_ptrand const uint8_t *c = c_ptr;. The error message mentions an invalid conversion between types.

Could you please post the 2 code files (or a simplified minimal version of them) that produce the error, and copy&paste the error message in full?

The error messages aren't so pretty:
In function uint16_t CalculateCRC16(uint16_t, const void*, size_t)':  46 invalid conversion from const void*' to const uint8_t*'   In function int main()':  57 system' undeclared (first use this function)    (Each undeclared identifier is reported only once for each function it appears in.)

When a function was called in the c file, how I notice this in the original Arduino file (ino)? Can I create any callback function form the c file to the ino file?

INO files are C++. If you want to call a C++ function from C you have to create it with C linkage. extern "C" void foo() { Serial.println("Foo"); }

You can extern "C" #include like the following:
extern "C"{
#include "crc16.h"
};

void setup(){
}

void loop(){
  CalculateCRC16("<09M", 4);
}

And the crc16.h file could be (some minor fixes, the #pragma once, a cast):
#pragma once

#include <stdio.h>
#include <stdint.h>

uint16_t crctable[2] ={ 0x0000, 0x1189};

uint16_t CalculateCRC16( // Call example CalculateCRC16("<09M", 4);
    const void *c_ptr, // Pointer to byte array to perform CRC on
    size_t len)        // Number of bytes to CRC
{
    uint16_t crc = 0xFFFF; // Seed for CRC calculation
    const uint8_t *c = (const uint8_t *)c_ptr;

    while (len--)
        crc = (crc << 8) ^ crctable[((crc >> 8) ^ *c++)];

    return crc;
}

Thanks, it works just fine now. Could you please explain the need of the pragma?

Sure, it is a good practice, though it is not needed in your example. It avoids the same header file to be included twice in a compilation file. Imagine a.cpp->(b.h and c.h) and b.h->c.h. That will duplicate the contents of c.h while compiling a.cpp. The #pragma once avoid this. Also guard directives #ifndef _MY_FILE_H_INCLUDED #define _MY_FILE_H_INCLUDED are common for this. Note, however, that as Peter R. Bloomfield points out, it might be better to put the implementation of CalculateCRC16 in a cpp file, and leave just the declaration in the header file.

Ok, I can see that becoming an issue when the code gets more and more complicated. Thanks for the advice.

Your CRC function can easily be converted to C++ so that it can go into a *.cpp file. All you need to do is use an explicit cast when you initialise your c pointer. Here's the 'proper' C++ way to do it:
const uint8_t *c = static_cast<const uint8_t*>(c_ptr);

However, an old C-style cast would also work:
const uint8_t *c = (const uint8_t*)c_ptr;

The problem is basically that C can be a little more permissive about letting you convert pointers implicitly between types. To do it in C++, you need to tell the compiler explicitly that the conversion is intentional.

Yes, just copy its declaration line in your sketch:
extern "C" {
    void myfunction(int arg);
}


text:
Program stops working after a minute
I have made this small program to lighten up in sequence 8 LEDs, it starts fine, but it stops working after a minute or so and the first 2 LEDs stay permanently ON, its like the chip stoped, here is the code :
// Initialize an array with all 8 leds
// and give them the corresponding
// digital number.
const byte led[8] = {0,1,2,3,4,5,6,7};

// the setup routine runs once when you press reset:
void setup() {

  // initialize all 8 digital I/O pins as outputs.
  for (byte i = 0; i<9; i++) {
    pinMode(led[i], OUTPUT);
  }
  pinMode(13, OUTPUT);
}

void left (void);
void right (void);

// the loop routine runs over and over again forever:
void loop() {

  right();
  left();

}

void left (void) {
  for (byte i = 0; i<9; i++) {
    digitalWrite(led[i], HIGH);
    delay(50);
    digitalWrite(led[i], LOW);
  }
}

void right (void) {
  for (byte i = 8; i>0; i--) {
    digitalWrite(led[i], HIGH);
    delay(50);
    digitalWrite(led[i], LOW);
  }
}

I am using a very old arduino duemilanove.

You had several problems with your loop conditions.  Arrays are 0 indexed. If we declare const byte led[8], led[0] is the first element and led[7] is the 8th and last element.
Also, in void right(), you declared i as a byte which is an 8-bit, unsigned number from 0 to 255. While you wrote the conditional to be i>0, it needs to be i>-1 or i>=0. So, if we change the coditional and keep i as a byte the loop would decrement i like 8,7,6,5,4,3,2,1,0,255,254... forever.  So instead, i should be declared as a char which is an 8-bit, signed number from -128 to 127.
// Initialize an array with all 8 leds
// and give them the corresponding
// digital number.
const byte led[8] = {0,1,2,3,4,5,6,7};

// the setup routine runs once when you press reset:
void setup() {
  // initialize all 8 digital I/O pins as outputs.
  for (byte i = 0; i<8; i++) {
    pinMode(led[i], OUTPUT);
  }
  pinMode(13, OUTPUT);
}

void left (void);
void right (void);

// the loop routine runs over and over again forever:
void loop() {
  right();
  left();
}

void left (void) {
  for (byte i = 0; i<8; i++) {
    digitalWrite(led[i], HIGH);
    delay(50);
    digitalWrite(led[i], LOW);
  }
}

void right (void) {
  for (char i = 7; i>=0; i--) {
    digitalWrite(led[i], HIGH);
    delay(50);
    digitalWrite(led[i], LOW);
  }
}

+1 even though Peter said it above, until I saw 8,7,6,5,4,3,2,1,0,255,254... the penny hadn't dropped.

Your loop conditions aren't quite right, which could be resulting in undefined behaviour. I highly doubt it would cause it to stop working spontaneously, but it's possible in theory.
In each loop that counts upwards, you basically need to stop before the counter reaches 8. For example:
for (byte i = 0; i<8; i++) ...

Note that it's i<8 instead of i<9.
The reason is that the array is only 8 elements long, so the indices run from 0 to 7 (inclusive). Currently, your loops are going all the way up to and including 8, which means it's trying to read past the end of your array.
You'll need to fix that in setup() and left().
The loop that goes downwards in right() is a little more difficult. At the moment, it runs through indices 8 to 1, meaning it has the same problem of reading past the array. However, it also never actually reaches index 0.
It's harder to fix because byte is an unsigned type, so you can't use i>=0 as your condition (as it will never terminate). Personally, I would rewrite the loop to count upwards, but then reverse the index order inside the loop, so that 0 becomes 7, and so on. For example:
for (byte i = 0; i<8; i++) {
    digitalWrite(led[7-i], HIGH);
    delay(50);
    digitalWrite(led[7-i], LOW);
}

Like I said, I doubt this will actually solve your problem. It's worth trying though.

Thank you guys, its fixed now, i just dont understand why i cant use byte if i do, i>=0, this way i never goes to 255 anyway and if does, it doesn matter, unless im missing something.
Here goes the final working code :
/*
  Blink
  Turns on all 8 leds in sequence back and forth.

 */

// Initialize an array with all 8 leds
// and give them the corresponding
// digital number.
const char led[8] = {0,1,2,3,4,5,6,7};
#define speed 40

// the setup routine runs once when you press reset:
void setup() {

  // initialize all 8 digital I/O pins as outputs.
  for (int i = 0; i<8; i++) {
    pinMode(led[i], OUTPUT);
  }
  pinMode(13, OUTPUT);
}

void left (void);
void right (void);

// the loop routine runs over and over again forever:
void loop() {

  // Turn off the buzzer on pin 13
  digitalWrite(13, LOW);

  while(1) {
  right();
  left();
  }

}

void left (void) {
  for (int i = 0; i<8; i++) {
    digitalWrite(led[i], HIGH);
    delay(speed);
    digitalWrite(led[i], LOW);
  }
}

void right (void) {
  for (int i = 7; i>=0; i--) {
    digitalWrite(led[i], HIGH);
    delay(speed);
    digitalWrite(led[i], LOW);
  }
}

yeah it will, in a for loop where the a byte is decrementing, if you use: i>=0 then this will always evaluate to true. When i==1 it will decrement to 0. When i==0 it will decrement (and rollover) to 255. This wouldn't be a problem if you used i>0 (or used a signed type), but then you wouldn't be using the 0th byte because you'd be leaving the loop before 0 was iterated over, ie led[0].

But then i == 255  will be false ?????

but i>0 would be true :)

also, it would matter because if it did go to led[255], that is pointing to another area of ram not associated with led and would be unpredictable


text:
"Broken Pipe" when uploading to Arduino UNO
I just got my Arduino UNO and I'm trying to upload the blink example but the upload fails with
ioctl("TIOCMSET"): Broken pipe
ioctl("TIOCMSET"): Broken pipe
avrdude: stk500_recv(): programmer is not responding
ioctl("TIOCMSET"): Broken pipe

I have tried both Arduino IDE 1.0.1 (which I installed via my package manager) as well as version 1.0.5 which I downloaded from the arduino.cc website. I'm running Ubuntu Linux 12.10 if that makes a difference.
I'd appreciate any and all help in getting my arduino up and running!

Are your drivers installed correctly? Did you double check the COM port? A quick Google search didn't return any results...

I got it working by switching USB port. I didn't even realize there is a green led that's on when the arduino is connected. So yes, I'm new to this!

As with any communication error, try these:

Disconnect and reconnect the USB cable.
Use a different USB cable.
Press the reset button on the board.
Restart the Arduino IDE.
Make sure you select the right board in Tools ► Board ►, e.g. If you are using the Duemilanove 328, select that instead of Duemilanove 128. The board should say what version it is on the microchip.
Make sure you selected the right port in Tools ► Serial Port ►. One way to figure out which port it is on is by following these steps:

Disconnect the USB cable.
Go to Tools ► Serial Port ► and see which ports are listed (e.g. COM4 COM5 COM14).
Reconnect the USB cable.
Go back to Tools ► Serial Port ►, and see which port appeared that wasn't there before.

In extreme cases, you may need to burn the bootloader.

Answer adapted from here.

The first point fixed this problem for me: Disconnect & reconnect (in a different port) the USB cable.

It sounds like you have incorrect drivers or the wrong COM port (USB) selected in the IDE
Both are easy to fix. I'd imagine that it would be the COM port.

To do this:

Tools → Serial Port → [COM port... try a few different ones. Also you can use device manager to see which one disappears when you unplug your Arduino]

Few notes on photo:
#1. The selector for the COM port. Choose which one your board is on.
#2. That shows the COM port selected and board. I don't have my UNO connected: ignore that the COM port isn't showing up on the menu.


text:
'Basic electronics' resources
I've seen that there are many resources on programming basis for arduino for people that have some electronics basis or background. Are there similar resources on the opposite? Basics electronics for programmers? Things that cover:

How to read schematics (different elements that appear there)
What different pins are used for (yeah, even on a more basic level than arduino documentation)
General idea of how a protoboard/protoshield works and how to connect components
General common components (resitors, capacitors...) and when and how to use them...
Safety rules, what happens when you do something wrong

Hi, this question is way too broad for this site. In fact, it's really 5 very broad questions in one. If you could re-word questions to make them more specific they would be a better fit for our Q & A format.

I'm asking for a colection of links/books con the topic. Thought. There's no specific cuestión but i thought it would be nice to have it posted here for future newcommers. If it's not appropiate I can deleite it.

no need to delete. These kinds of questions, while very useful, are difficult to manage. Something like this could turn into a never ending post with hundreds of edits and comments. That's just not what this site is for.

From zero to Arduino (maybe a HOWTO someday?)
Rule zero:

Don't overestimate the other Arduino users! They all were not born with this knowledge too.
Never be too shy to ask!
Making mistakes is ok as long as they trigger learning.

(-: short break :-)
You'll find lots of HOWTOs and other tutorials in the wild wild web.
I assume, the confusing thing is to read them in the wrong order.
Forget your Arduino(s) for a while and start with reading about:

General common components (resitors, capacitors...) and when and how to use them...

This will at least partially answer:

Safety rules, what happens when you do something wrong
How to read schematics (different elements that appear there)

If not already done:

Read about ANDs, ORs, NANDs, NORs, FLIPFLOPs...

This will show how their schematic symbols look like.

...compare them to creating the same behaviour by programming (if,
and (&&), or (||), ...)
Have a look at bit operations (&, |, ... on whole number variables.

The programming up to this point can be done on your PC.
After this, dedust your Arduino again and jump into:

What different pins are used for (yeah, even on a more basic level
than arduino documentation)

(Happy end. At least for now.)
(I make this a community wiki answer to invite others to expand this text.)

Well making mistakes in electronics can cost a lot: from a few bucks to your life!

Yes... the dangerous mistakes should be avoided... but when turning a logic chip into magic smoke and then learning why this happened at least was a honourable dead for that chip. And to avoid the most dangerous mistakes, you can power your Arduino by a battery pack and keep it far away of 120V/240V power lines... at least in the beginning...

@jfpoilpret When applying for the Darwin awards (what I have seen done on Arduino.EE couple times already) does not obey yeti's rule #0 sub 3:  "Making mistakes is ok as long as they trigger learning."

mmm, should we open showcase thread on arduino darwin awards? could be funny, and illustrative too :p

Instead of joking arround, you could have improved the answer. That's what wiki is desiged for...

This is an extract of an introductory book that shows basic schematic  components:

Hi, please add more information to your answer. Link-only answers are discouraged as it becomes useless if the link target changes or gets removed.

@sachleen -- As of now, the link is dead.


text:
7segment blink when the button is pressed
I have programmed an IR remote control along with an LED and an 8bit 7segment on an Arduino Uno.
the segment displays the number I press via the remote, and the LED turns on and off
here's my code:
case 16738455:
  Serial.println(0);
  if (oldvalue == results.value){
    on(num0);
    delay(1000);
    on(num00);
    delay(1000);
    oldvalue = results.value;
  }

oldvalue stores the last value pressed, which is the DEC value of the buttons, num0 displays the number zero, and num00 turns all the segments off.
I want the 7segment to blink again when I press the same button again.
Can anyone help me with this?
Thanks

You have to provide more code if you want some help. What is the code for the on function? What else is inside your loop() function?

The code is long, this is the dropbox link to it:
https://www.dropbox.com/s/haw498jlwmol75z/IRwith7segment.ino

Please put it on pastebin - dropbox is too transient.

http://pastebin.com/9iYgyrd5

A simple solution would be to not worry about blinking as a piece of code, ie. remove those delays (I hate blocking code) and instead, if you are currently receiving a signal from the remote, do not display any number (or display your num00). Once the value is received and processed, then display that number.
This way, whilst ever the remote button is down, the display will blank out, and the number will appear as soon as the number is released. If it's the same number, then you will see the number, see a blank display, and then see the same number again. Obviously, if it's a different number, the new number would be displayed.
Since most people would only press the remote button for 100-1500ms, it should give you a nice delay anyway.
Finally, you may encounter some flashing if you process the data so quickly and the remote auto repeats. This could be handy if that number is processed multiple times by the receiving unit. The flashing would indicate that that is the case. If that is undesired, implement a simple state machine.
edit: your pastebin code came up whilst I was writing this answer. Having a quick look at your code, I would suggest that in the section:
if (irrecv.decode(&results)) {
  //receiving data? display nothing
  on(num00);
  digitalWrite(ledPin, HIGH);
  Serial.println(results.value, DEC);
  irrecv.resume();
  delay(100);
  int oldvalue = results.value;
  switch(results.value){
    case 16738455:
      Serial.println(0);
      num2display=0;      // make sure to declare this var somewhere
      //if (oldvalue == results.value){
      //  on(num0);
      //  delay(1000);
      //  on(num00);
      //  delay(1000);
      //} else {   // I think you missed an else here
      //  oldvalue = results.value;
      //}
      //on(num0);
      //delay(1000); // you don't want such large blocking delays
      irrecv.resume();
      break;
    case 16724175:
      Serial.println(1);
      num2display=1;       // add this for each section
      irrecv.resume();
      break;
      . . .
  }
}
else{
  digitalWrite(ledPin, LOW);
  on(num2display);
}

you only set the variable to be displayed, but display num00. Then in the else, you can display that number

Responding to a button being released is a little tricky with IR remotes. Unlike a physical button, you don't get a steady signal while the remote button is held. Rather, you get a repeating signal, which could end up looking like lots of presses in quick succession.

@PeterR.Bloomfield I did think of that after the fact (or towards the end of the answer), but that could be easily avoided: you would know the pause between transmissions, set a timeStart flag, and don't display before timeStart+timeLag. Resetting this at the beginning of each new repeated burst would ensure it only appears at the end of the transmission.

Thank you for your help Madivad
With all respect but I don't think you understood the code well
Here's the youtube link to it's video and what it does:
link
When I press a button, the 7segment displays that number, but what I want is, when I press the same button twice, the 7segment should blink in the second time, all the segments turn off and on again


text:
How to connect Android phone to Arduino?
Is it possible to connect an Arduino to an Android Phone and use it for input/output?
Are connections possible over USB? Or do I need to have a wifi or Bluetooth shield?

Possible duplicate: https://arduino.stackexchange.com/questions/253/how-do-i-write-an-arduino-sketch-and-an-android-application-to-talk-to-each-othe/254

@FedericoFissore It's wondering not just USB, but also alternatives like wireless.

@AnnonomusPerson I see. To me it sounded more like a "can I use this or do I have to use that". Since the answer is "yes" for both, it's not as duplicate.

You bet it's possible. I used a pretty cheap bluetooth module that I got from Amazon, and wrote an app using the information on the official Android Developers page to connect to the Arduino. There are many guides online telling you how to hook up a module to the pins of the duino.
You can probably get a cheaper module if you look on eBay and don't care how long it takes to arrive, and I think there's at least one app on the Play store for controlling an Arduino if you can make it work for your purpose.
USB connections are probably possible, though I haven't done any of that.

Can you add a guide link and app link? I think "out there un the internet there are things" is not enough

I already had this answer typed up on another question so I thought I'd post it here to help you. I've replaced "tablet" with "phone" for easy reading.

You never mentioned your phone model... or Arduino model
There are some phones designed to work with USB flash drives and
  printers. This is called OTG (on the go.
You need:

A phone supporting OTG
An OTG adapter that fits into your phone's USB slot and is compatible
The Arduino Uno Communicator App
Arduino Uno (or clone) [Note: It says that it works with Atmega16U2 or Atmega8U2 programmed as a USB-to-serial converter so I would assume
  that that would cover a few boards more than the Uno.)

Another alternitive is to look into
  Bluetooth
  (Note: I just picked a random link but there are hundreds of similar
  BT adapters)

From my answer on a similar question

The Arduino ADK is meant for that. It combines an Arduino Mega with a USB host chip and port. If you don't want to buy a full Arduino, you can buy a USB host shield. Excellent tutorial for it here.
What those do is convert high speed USB signals to SPI, which is readable by a microcontroller. Android has libraries known as the Accessory Development Protocol, which can bridge communication from a phone to the USB and then to a microcontroller.

You can connect Android and Arduino with usb and use the easy tool App inventor 2 for android
Did you try this new application : https://play.google.com/store/apps/details?id=bp.usbbridge.appinvDemo and full version : https://play.google.com/store/apps/details?id=bp.usbbridge.appinv
Find Videos about Explications : USB OTG Bridge Serial UART for APP Inventor 2 and ARDUBLOCK on youtube


text:
Shield interfere with Serial Communication
I'm new to arduino. I have nexus duino robot as described in http://www.aliexpress.com/item/3WD-48mm-Omni-Wheel-Mobile-Arduino-Robot-Kit-10019/688287804.html, the shield connected with motors and support xbee.
With simple serial comm sketch, I'm able to communicate between arduino and PC if the shield not inserted, but not if I insert the shield as it seem arduino can't receive serial data (still can send data to PC tough). Someone says that the shield might be use RX TX so it interfere with serial comm.
My Questions are, is there a way to check whether the shield use RX TX? If yes, can we make it not interfere with serial comm? Could be other problem causing this serial comm problem?
Thanks in advance.

As always, read the schematics.

Can you give us some more information about the shield, please? There is no information about it on the page you linked to. Model number or datasheet would be good.

You really do need to provide information on the shield, there are many versions out there (and I own half of them ).
In essence, unless you are using an alternate serial port (SerialN) or software serial, then YES, your XBee will be using the same lines as your Arduino. If you are using Serial.print or Serial.write to talk to the XBee, then that is a giveaway too.
The reason for this is the XBee talks to your Arduino through the serial port, but the Arduino IDE also talks to your Arduino (for programming and Serial.print) as well. You can only do one successfully.
In answer to your second question, most likely not. It will be the XBee shield causing you your problems.
edit: I thought I would add, I actually have ONE shield that uses RX and TX but also allows for programming at the same time. This is achieved through a series resistor and (in the case of the shield) an amplifier as well.

I'm back with same problem and with other problem. I'll list my experience:
have to set baud rate to 38400, it's the only value that works when the shield on (no garbage).
for once, I confirm that serial comm is OK even with the shield on, I can instruct the robot to rotate with PC, was very happy and then went sleep. And because it only once it feel like a dream, it wasn't working anymore when I tried to add more instructions.
later I check the motor and realize that one of the wheels won't rotate.
Are these two problems related? Please assist on how to troubleshoot these issues.

All wheels working fine now, just a loose plugged cable, serial comm still not working when the shield attached.
@Madivad, can you give a noob tutorial on how to make the shield that use RX and TX also allow programming at the same time. Thanks in advance.


text:
LEDs on TX/RX lines interfering with the programmig of the device
I have recently designed a shield to my Arduino Duemilanove, which has 8 LEDs, on the digital GPIO, from 0 to 7, but it won't program with the shield on because the voltage drop is too much on the RX and TX lines. My question is: can I have a LED on the TX/RX line with a minimum resistor value that allows me to program the Arduino?

how do you have the pins configured/wired? Pullups/pulldowns? Are you sinking current or providing current to the LEDs?

I have from digital pin 0(RX)-->330R-->LED-->GND, and its pretty annoying on the developing fase to be constantly taking on and off the shield.

try something in the order of 5-15k and see how that goes. If brightness becomes an issue you might have to put a transistor in as well.

I just found this reference (using ICSP for output as well as programming -- essentially the same thing), and it suggests a 4.7kOhm.
I didn't have a 4.7k handy, and used a 15k instead and it works.
In my scenario, I have run a sketch with a polarized buzzer connected between RX (digital 0) and GND. When connected directly (with no resistor) the sketch fails to load (but the buzzer works as expected).
If I put the resistor in series with it, the sketch uploads without fail.
You also probably realise, but mentioning for clarity/completeness, you will lose all serial port functionality for debugging purposes and won't be able to use Serial.[anything]. Make sure to not even initialise the port.

After trying several resistor sizes i got to the smallest possible size of 470R, now i can program whitout any problems at least for this kind of LED, it will probably change if you have an LED with a bigger voltage drop, thank you very much again for your help @Madivad :).

Oh well, that saves me from finishing this project. I was just putting together a breadboard to try different values myself. Glad I could help.

Thats some dedicated fellow :), if your interested i can show you my shield it will be shared soon on OSH Park.
Is there a way to contact people here with private messages ?

Well, I was using it as a learning experience for me as well. Which is why I answer a few XBee questions. As far as I know there is no PM system, but just below in the footer is a "chat", head over to "pin13"


text:
Ethernet shield and IPv6 support
Have you heard about support for IPv6 protocol for any Ethernet shield?
As far as I know only IPv4 is supported.
Maybe some one would like to write library?

There is no library, and there physically cannot be one. IPv4 is built into the Ethernet shield itself. (It has a Wiznet 510 chip.)

Shields based on the MicroChip ENC28J60 chip (such as those sold by Ekitszone and Nuelectronics) are suitable for the implementation of an IPv6 or dual IPv4/IPv6 stack. This approach requires the TCP state machine to be implemented in software and results in more complex arduino code.

Source: this tutorial. (You may find it useful, I'd recommenced reading it.)
There is this library for IPv6 on other hardware, not for the official Ethernet shield.

While the W5100 chip does not support IPv6 at Layer 3, it does have a layer 2 mode (MACRAW) for sending Ethernet frames directly, so can be used to send and receive IPv6 in the same way as the ENC28J60.

I have been working on an IPv6 library for Arduino, called EtherSia, that works with the ENC28J60 chip, but with a lower overhead compared with libraries that use Contiki / uIP. It is comparable to the EtherCard library for IPv4.
https://github.com/njh/ethersia
While the Wiznet chips do not support IPv6 natively, they do have a MACRAW mode that allows you to send Layer 2 Ethernet frames directly. I have managed to get IPv6 working with the Wiznet W5100 and W5500 chips, which is what the official Arduino Ethernet Shield and Ethernet Shield 2 use.
So it is possible...


text:
Do gyroscopes purposefully show erroneous data?
I tested an MPU-6050 (GY-521) using an Arduino Nano. I used the I2CDevLib and opened the MPU6050_DMP6.ino with the Arduino IDE. I opened the MPUTeapot.pde Processing-file with Processing. A few changes was necessary to make it work:
MPU6050 mpu;

was changed into:
MPU6050 mpu(0x68);

Additionally I commented out this line:
#define OUTPUT_READABLE_YAWPITCHROLL

and uncommented this line:
#define OUTPUT_TEAPOT

When turning everything on, the arrow (Processing) would turn with 5 degrees/s clockwise around the z-axis (plus a very small amount around the other two axes). After about 20 seconds, it would stop, and turn around the x-axis pretty fast for 3 seconds. Then it would stop. Now, the gyroscope+accelerometer would work perfectly. This happens every time I test it.
This happens only when the gyroscope is perfectly still on the ground. It does not stabilize if I move it around. Only after it is left completely still, it'll stabilize after 23 seconds.
Is this how it should work, or is it a problem with the gyroscope? Could it even be caused by the I2CDevLib? Can anybody else confirm this?

According to the datasheet, that was conveniently linked in your question, there is a temperature sensor in the device. Does your code compensate for temperature, because it does seem to be heating up. What happens when you warm the device with your finger once it is stable?

@jippie I'll check.

@jippie It doesn't do anything even if heated up. There is a lot of code to read through for me who is new to Arduino and don't know much C++. But it claims to use some processor inside the chip to process the raw data from the gyroscope and accelerometer and temperature sensor..

@jippie: How did you see that link before I edited it into the question?

MPU6050 is a chip that has an intenal (closed and unknown) algorith to calculate orientation. Because you ar reading ANGLE, that means you are using that algoritm, and that "time" may be the time needed for the calibration.
what do you have as output on the serial?

It happens every time I close and reopen the serial on the computer. So it would be strange if it is actually it heating up. What do you mean by output on the serial?

every time you open/close the serial you are resetting the arduino (see autoreset feature) so yes, it reinforce the "warm up" theory. Track on the serial the time used by every step!

Do you imply that the Arduino is trying to compensate for the heating up which does not take place because it's already turned on?

no, i think the algoritm used by the chip is doing some reading to calibrate itself. Many chip has internal activable BIAS, for example on Accelerometer activating this bias you add a -+1G, so you can calculate the real value of G, linearity of value, if it is stable, and a lot of thing used to compensate for real world "noise". Fixing "warmup" to "calibration" in the answer, so it will be clear


text:
What's the 2nd ICSP header for in Arduino Uno R3?
Looking at my Arduino Uno R3 board and its reference design schematic I noticed that there's a second ICSP 6-pin header. In the schematic, the connector I'm referring to is named ICSP1.
What's that for?
What useful things can an average Arduino user like me do with it?
The relevant part of the schematic is below (marked in red).

I've been wondering a similar thing, not so much what it's for, but what else we could do with it. It has to be asked: http://arduino.stackexchange.com/questions/991/can-the-2nd-mcu-on-the-uno-r3-be-used-for-keyboard-emulation

It's for the other MCU on the board.
The main MCU on the Uno is labelled "ZIC1". This is the one that is programmed when you press "Upload" in the IDE. But unlike other Arduinos that use a FTDI chip to connect to the serial port on the main MCU, the Uno uses another MCU instead, labelled "U3" on the left. This MCU runs a small bit of code that acts as a serial port via USB and passes through the bytes to its USART1. This then connects to the USART on the main MCU, where the bootloader on that chip accepts the bytes coming through and writes to flash and EEPROM on the main MCU.
You can use this additional MCU as you would any other, but the only I/O it has available are the USB connection, the SPI connection via its ICSP header, the UART1 connection to both the main MCU and pins 0 and 1, and two LEDs on PD4 and PD5.

that's really interesting! Thanks for the info. +1

I noticed this only yesterday after trying to utilise the TX and RX LEDs in my project. I pulled out the schematic to realise they weren't connected where I expected.


text:
How do I use a i2c port expander to read buttons with pull ups and inverting the resulting uint16_t?
I am using a mcp23017 to read button presses for my joystick project and am using the internal pullup to minimize complications. Is there a way to invert all the bits in the uint16_t so i can send the values as normally off?
I'm using this Adafruit library.
And the reading code: uint16_t buttons = mcp.readGPIOAB();

The inversion operator in C++ is ~.
Serial.print(buttons, BIN);
Serial.print(~buttons, BIN);

Amazing dude thanks!!! I added a ~ in front of mcp.digitalReadGPIOAB(); and that has done the trick.

Welcome to Arduino! You can click the "accept" button (the green checkmark by the answer) to mark that this solution worked. Thanks! :)


text:
Can the 2nd MCU on the UNO R3 be used for keyboard emulation?
Following on from What's the 2nd ICSP header for in Arduino Uno R3? I was wondering how this could be hacked to our advantage.
For example, could that firmware be rewritten to have the UNO recognised as a mouse/keyboard input? Could this be done after the boot loader process and leave the uploading process in tact?
Given the limited IO, it seems it's functions might be limited. Plus I have no idea how much code is space is available.

As an extra to this question, feel free to add other ideas this could be used for whilst (in as far as possible), leaving the arduino environment in tact. That is, what else could be hacked into it to increase it's functionality?

It's flash is too small to hold multiple hacks, but the LUFA website (linked in my question) has a lot of different hacks that are compatible with the 16u2

Too small? 16kB is a lot of flash. I'm surprised they didn't stick with the 8U2 as in the original (although there may be availability issues involved).

I just checked Digi-Key and the price difference between the 8U2 and 16U2 is about $0.01. At that price it's a no-brainer, even if you don't need the extra flash.

This question is spawned from a project I saw on hackaday last year, and a friend and I have been discussing it on and off ever since. I just found this (only two weeks old): http://hackaday.com/2014/03/16/developed-on-hackaday-security-and-arduino-compatibility/

Yes, it is possible. using LUFA, you can burn new firmware to the Serial converter. The only problem is that you need to re-burn the USB-Serial converter to upload another program.
Info: http://www.fourwalledcubicle.com/LUFA.php
Specific page: http://mitchtech.net/arduino-usb-hid-keyboard/

Is there more information on the firmware that exists in the 2nd mcu? I haven't been able to find anything on it. I'm sure that someone somewhere has hacked it specifically. Personally, I'd love to see the code. Emphasis (for me) would to largely leave the environment in tact to allow for future reflashing. Which I don't think would be too hard to incorporate after there is nothing from the IDE after reset.

@Madivad it is a simple assembly file that converts USB signals to serial. You need to use bare AvrDude to flash it.

from one of those links I found: http://arduino.cc/en/Hacking/DFUProgramming8U2 I searched for this kind of info, obviously wrong search terms :) Thanks for your links Doc.

The second MCU is similar to that used in the Leonardo, but is smaller and less capable (ATmega16U2 vs. ATmega32U4). It is certainly possible to reprogram it to do what you like, but its limits means that you can have fewer USB "devices" at the same time.
I have not looked at the existing firmware, but it should certainly be possible to add your own custom code into it such that both the normal serial connection to the main MCU as well as your additional code can coexist.


text:
How can I filter out noise from ADC lines without delay or signal change?
I'm working on a project with a joystick and I'm trying to keep everything a simple and low latency as possible. I am reading the pots with the onboard 10bit ADC on the ATmega 32u4 but may be upgrading to either a 16bit ADC or 24 bit ADC. How can I filter noise out of the signals?

Have you tried averaging multiple readings yet? Using ADC noise reduction mode?

will give that a try now

how do you use the built in noise reduction on the 32u4 from the arduino programming enviroment?

Not directly. You need to drop to raw AVR code (not assembly though, just direct register manipulation).

#i have no idea where to even begin with that

not sure the best way to implement the multiple reads either

also averaging reads is not going to work either, i do not want to "soften response from the joystick

What kind of noise do you get? High or low freq? Maybe your best bet is to use a simple RC filter, high or low-pass based on the noise you want to reduce

The datasheet has a chapter on the ADC and it talks about noise reduction. There are many aspects of noise reduction, amongst which sleep states and filtered analog power supply rails. For using 16 bit ADC (let alone 24 bit, which is pretty much state of art) to spec, you need a very well designed circuit and PCB and quality components. Otherwise it is just a waste of your money. You can start by changing the reference voltage to one of the internal band gap references. What is the exact problem you are trying to solve?

This sounds a bit like another XY problem http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem.

What is the issue you are trying to solve? Even if you throw away 2bits of the 10bit of ADC due to noise, you still have 256 discrete levels - this is a lot of precision. I think the PS3 controllers only have 16!

And with respect to latency - do you know how much latency is too much latency? There's no point in spending hours trying to get low noise 16bit ADC readings 1000/s when you could just average 10bit ADC readings 100/s.

The Atmel ATmega328 datasheet, section 24.6.1, recommends that you drive the analog input pin with an output impedance of 10 KOhm or less. Also, it recommends that you remove high-frequency components with a low-pass filter. (That low-pass is sometimes called an antialiasing filter).
The simplest possible low-pass filter is a resistor and a capacitor.
  +5V                        +5V
   |                          |
(sensor)---resistor---+---(Arduino)
   |                  |          |
   |            capacitor        |
   |                  |          |
  GND----------------GND--------GND

Contrary to popular belief, it is not possible to make an antialiasing filter in software.
For an initial low-resolution prototype, a quick rule of thumb is to pick the RC time constant at least 10 times as long as the time between samples.
So if you are sampling at around 1000 Samples/second (i.e., a sampling interval of 1 millisecond), then 100 Ohms of resistance and (roughly) 100 uF ceramic capacitor may be adequate.
(The RC time constant here is RC == 100 Ohms x 100 uF = 10 milliseconds).
Many joysticks already have a relatively high output impedance; you'll need to use a resistor with that much less resistance to compensate.
(Sometimes you don't need any additional resistance; but you still need that capacitor between the Arduino analog input pin and the Arduino ground pin).
(Many sensors have an output impedance more than 10 KOhm; people who use them are pretty much forced to use an op-amp chip to get clean signals).
Entire books have been written on signal filtering.
In addition, there are many other techniques for getting higher resolution analog signals, higher speed data collection, and trading off between them --
but they are probably overkill for reading the position of a joystick.

One possible approach is to go for a completely software side solution.
Microsmooth is a signal processing library that I am working on that is specifically intended for low latency, low memory signal smoothing. It is still in development, but even now, most of the filters work in less than 100 microseconds per call while giving fairly good accuracy and smoothing. Also, the header file allows for simple configuration for certain filter parameters.

The noise from your joystick pots will drown out any resolution over eight bits regardless.  They were designed for the very crude game port on a pc and use a copper wiper on a slab of carbon.  Not a terrible recipe for a noise generator.


text:
Problem with Xbee or Arduino?
I am sending three analog signals through the xbees to be written to analog pins on the receiving side so they can be read in Simulink. I connected both of the arduino megas to my laptop and uploaded the sketches. I have a shield and a series one xbee connected to each arduino. I pulled up the serial monitor for each sketch. I connected a 1 volt DC power supply to all three analog pins. On the transmitting serial monitor I got numbers close to 200 which I believe is correct but on the receiving side I was not getting anything. I believe the problem is with the arduino. After I uploaded the code on the transmitting side the TX led was green but the RX led on the receiving side was not lit up at all. The power LED on the transmitting arduino is red but it is green on the receiving side. The 'L' led on the transmitting side is red on the transmitting side is read and yellow on the receiving side. On both of the xbee shield the power led's are red and the DIO5 led blinks green. On the receiving xbee shield the DOUT LED is red and the DI LED is green. If more information is needed let me know.
Here is my configuration for the xbees: (series 1. firmware version: 10ed)
Transmitting Xbee:
PAN ID: 1234
MY:10
DL:11
Receiving Xbee:
PAN ID: 1234
MY: 11
DL: 10
Transmitting arduino program:
int val1 = 0;
int val2 = 0;
int val3 = 0;
int analogPin1 = 0; //these are you analog in pins
int analogPin2 = 1;
int analogPin3 = 2;
void setup()  {
  Serial.begin(9600);  //start serial
}
void loop()                               // run over and over again
{
        Serial.print("<");                // This character signifies the begining of our data cycle
            val1 = analogRead(analogPin1);    // read the input pin
        Serial.println(val1);             // output the signal
        Serial.print("\t");               // Signifies end of 1st piece of data
            val2 = analogRead(analogPin2);    // read the input pin
        Serial.println(val2);             // output the signal
        Serial.print("\t");               // Signifies end of 2nd piece of data
            val3 = analogRead(analogPin3);    // read the input pin
        Serial.println(val3);             // output the signal
        Serial.print(">");                // This character signifies the end of our data cycle
        delay(100);
}

Receiving Arduino program:
#include <SoftwareSerial.h>
// software serial #1: TX = digital pin 0, RX = digital pin 1
SoftwareSerial portOne(0,1);
int Apin1 = 0; // These variables hold the current incoming value
int Apin2 = 0;
int Apin3 = 0;
int AnalogOut1 = 0;  //Set our analog pins
int AnalogOut2 = 1;
int AnalogOut3 = 2;
int Digits = 0; // Helps watch for comma
int Mode = 0; // This designates which section of reading we are doing - begin = 0, Apin1 = 1, Apin2 = 2, APin3 = 3, end = 4
void setup()
{
 // Open serial communications and wait for port to open:
  Serial.begin(9600);
  // Start each software serial port
  portOne.begin(9600);
}
void loop()
{
  portOne.listen();
  while (portOne.available() > 0) {
  // read the incoming byte:
    char inByte = portOne.read();

    if (isdigit(inByte) && Mode == 1) {
    int temp = inByte - '0';
    Apin1 = (Apin1 * 10) + temp;
    Serial.print('\n'); // This is just some debugging stuff, if you plug in your programmer this will output the data to a serial monitor
    Serial.print(temp);
    Serial.print('\n');
    Serial.print(Apin1);
    Serial.print('\n');
    }
   if (isdigit(inByte) && Mode == 2) {
    int temp = inByte - '0';
    Apin2 = (Apin2 * 10) + temp;
    Serial.print(temp); // This is just some debugging stuff, if you plug in your programmer this will output the data to a serial monitor
    Serial.print('\n');
    Serial.print(Apin2);
    Serial.print('\n');
    }
  if (isdigit(inByte) && Mode == 3) {
    int temp = inByte - '0';
    Apin3 = (Apin3 * 10) + temp;
    Serial.print(temp); // This is just some debugging stuff, if you plug in your programmer this will output the data to a serial monitor
    Serial.print('\n');
    Serial.print(Apin3);
    Serial.print('\n');
    }
    if (inByte == ',') {
    Mode++;
    }
    if (inByte == '<') {
    Mode = 1;
    }
    if (inByte == '>') {
    Mode = 4;
    if (Apin1 > 0 && Apin2 > 0 && Apin3 > 0) {
    analogWrite(AnalogOut1, Apin1);
    analogWrite(AnalogOut2, Apin2);
    analogWrite(AnalogOut3, Apin3);
    }
    Serial.print('\n'); // This is just some debugging stuff, if you plug in your programmer this will output the data to a serial monitor
    Serial.print(Apin1);
    Serial.print('\n');
    Serial.print(Apin2);
    Serial.print('\n');
    Serial.print(Apin3);
    Serial.print('\n');
    Apin1 = 0; // These variables hold the current incoming value
    Apin2 = 0;
    Apin3 = 0;
          }
    }
}

also, maybe you should talk to @user734 and work on your posts together

The problem is the same as last time (XBee+Arduino communication problem)
You are sending the data via:
Serial.println(val1);

which outputs an ASCII representation of the number.
But in your reading, you are reading in a byte value. Actually, I just realised you are reading in a char which is a signed (-128 to 127) value:
char inByte = portOne.read();

first, change that to:
byte inByte = portOne.read();

Now, you have three options:

If (as you say) the numbers you expect are around 200 and will always be below 256 (and positive) then you could send a byte value instead. That way, when you read the byte in, you get the same value. You would do this using Serial.write(val1); instead of print.
If you need to send larger than a byte value, eg int, then send as two bytes, HIGH and LOW. Then on the receiving end, take in two bytes when reading that data.
Send as plain text but read in as plain text. Since you have delimiters, keep reading in the serial until you have all the data you need and then break it down. (You could adapt the code I posted in the answer above to do that).

edit: a couple of other points with your code:

You're doing an analogWrite to digital pins 0, 1, and 2. Was that your intention? analogWrite is reserved for sending out PWM signals on only those pins that are capable (see: http://arduino.cc/en/Reference/analogWrite )
analogRead will read a value of 0-1023 and if your intention is to just use PWM at the other end, then step it down to a value of 0-255. In that case you can get away with writing byte values to Serial.write.
You're never setting the pinMode of the outputs in the receiver.
You're sending val1, val2, and val3 out via Serial.println which will send your value out (as ASCII), followed by a newline, so the bytes sent from that one line will be 32 30 30 0D 0A. You have to interpret that at the other end.
You're also using software serial on the hardware serial port (you're assigning digital pins 0 and 1. These are the hardware serial pins). BUT you're also initialising it via hardware serial. I'm guessing that it really wouldn't matter (if the pins are aligned), but you can't expect to receive data via software serial and send data via hardware serial if they're all using the same pins.