body:
As most other answers, I would go for method 2.

But I would try to avoid the call, by Arduino library, to an an empty `loop()` that makes the Atmel consume "a lot" of current for nothing.

Edit:

As some comments pointed out though, using `delay()` in `loop()` will change nothing to power consumption.

Hence, if you would like to reduce power consumption once your `setup()` has run, you will have to play with Atmel sleep modes.
You can take a look at [this article][1] that shows how to deal with sleep modes from your Arduino sketches; it does more than just putting the Atmel to sleep but it is a good (and simple) read if you want to play with sleep modes.

  [1]: http://playground.arduino.cc/Learning/arduinoSleepCode


sender: user

message:
Code for one-time execution in Arduino

**Question:** Where do I put code if I want it to execute only once per Arduino startup?

**Background:** I tend to use my Arduino to perform tasks that should be executed once per power cycle.  (For example, my robot should only drive forward *once* every time I turn it on--more than that, and it might fall off the table.)

The standard Arduino IDE "template" consists of a `loop()` and a `setup()` function.  The `setup` code is run once per power cycle, and the `loop` is re-started every time it finishes.

I see two approaches to code "1 time tasks:"

Method 1: "Loop once"
--
    void setup() {
      //do setup stuff
    }

    void loop() {
      //do task

      while(1) ; //Repeat forever, preventing function from re-starting
    }

Method 2: "Setup only"
--

    void setup() {
      //do setup stuff

      //do task
    }

    void loop() {
      //do nothing
    }

**More detailed form of question:**  Is one of these methods "better" from a hardware/software sense?  (e.g. is there anything "special" about the `setup` function, like it can only run for so much time?)
And, if they are the same from a hardware/software perspective, is there a "best practice" or standard way of writing code for these situations in the Arduino community?

sender: assistant

body:
I'm kind of confused by your question. You ask where you want to put once-per-startup setup functions, and then discuss the setup function. *That's what the setup function is for.*

As such, one-time setup functionality goes in the setup function.

FWIW, if you look in the file that *calls* the `setup` and `loop` functions:

    #include <Arduino.h>

    int main(void)
    {
     init();

    #if defined(USBCON)
     USBDevice.attach();
    #endif

     setup();
     for (;;) {
      loop();
      if (serialEventRun) serialEventRun();
     }
     return 0;
    }

For all intents and purposes, the two options are completely identical. Either way, you get a empty busy-wait loop. Frankly, I'd expect the two different options to probably emit the same machine code anyways, so the whole thing is a non-issue.

Note:
`if (serialEventRun) serialEventRun();` appears to be a facility to allow you to attach a function that is called upon reception of serial data, but if you do not define a function `void serialEvent(){}` in your code, it will compile out completely and not be present in the produced machine code.


message:
What I should be aware before I touch my Arduino?

Before you start to mess with a computer there are basic guidelines to be aware of, such as turn the power off and watch out for static electricity. What guidelines should I be aware of when I work with an Arduino board if I don't want to harm neither myself nor the board. The three kind of activity that requires touching the Arduino and what I'm asking about:

- Setting up wire, component layout or breadboard.
- Debugging a running setup.
- Moving, mounting up the board somewhere.

body:
Turning the power off and taking proper static precautions also applies to Arduinos.  Anorton's tip about not resting it on a conductive surface is also useful.  Some other things to keep in mind:

 - Double check the polarities of any connections you make.
 - Keep a consistent wiring color code.  Use red for power and black for ground.
 - Calculate the expected current through all components before you apply power.  Check the datasheet to make sure it's within safe limits.
 - Calculate the heat dissipation for higher power components like power supplies and motor drivers.
 - Connect and test one small part at a time, instead of in one big bang.
 - Make sure the parts you buy expect the same voltage, or perform the appropriate conversion.

For keeping people safe:

 - Know where the fire extinguisher is.
 - Don't put cords where people can trip on them.
 - Use a proper stand to hold your soldering iron, and keep pets and small children away.
 - If your project has a propeller or something physically dangerous, build failsafes and kill switches into the system.
 - Be careful to charge any batteries properly, and not let them overheat.
 - Be careful what you touch while troubleshooting.  Arduinos usually don't deal with very high voltages, but inductors and capacitors can build up higher charges than you expect, and hold it after power is removed.


body:
One of the most common bad things I have seen is connecting LEDs directly to addition pins without a current limiting resistor.

Basically, in electronics there are a few main sources of problems. Too much current, too much voltage, overheating, and physical damage.

Too much current usually comes from shorting things, too much voltage(or reversed polarity) usually comes from not paying attention to what is being connected, overheating comes from too much current or not using a heatsink when you should be.

Basically, just think before you connect things and you'll be fine. Learn some basic circuit theory if you haven't already, get in the habit of knowing the ratings of the parts you want to use, and double check stuff before turning it on.

I like this list here of things not to do: http://ruggedcircuits.com/html/ancp01.html


message:
How to check my Arduino board is working or dead?

When you have a board in your hand but you don't know is it working or not, how to verify if it's working or dead?

body:
> **Note :** After the @Ricardo's comment on my last post, I am posting this !

Plug the board into a USB port on your computer and check that the green LED power indicator on the board illuminates. Standard Arduino boards (Uno, Duemilanove, and Mega) have a green LED power indicator located near the reset switch.

An orange LED near the center of the board (labeled “Pin 13 LED” in the image below) should flash on and off when the board is powered up (boards come from the factory preloaded with software to flash the LED as a simple check that the board is working).

![enter image description here][1]

If the power LED does not illuminate when the board is connected to your computer, the board is probably not receiving power.

The flashing LED (connected to digital output pin 13) is being controlled by code running on the board (new boards are preloaded with the Blink example sketch). If the pin 13 LED is flashing, the sketch is running correctly, which means the chip on the board is working. If the green power LED is on but the pin 13 LED is not flashing, it could be that the factory code is not on the chip. If you are not using a standard board, it may not have a built-in LED on pin 13, so check the documentation for details of your board.

Online guides for getting started with Arduino are available at for [Windows][2],  for [Mac OS X][3], and for [Linux][4].

  [1]: https://i.stack.imgur.com/gDEH4.png
  [2]: http://arduino.cc/en/Guide/Windows
  [3]: http://arduino.cc/en/Guide/MacOSX
  [4]: http://www.arduino.cc/Learning/Linux


body:
<!-- language: lang-bash -->
Supposed one owns a USB programmer, there's another way to inspect the Arduino.

Connect the programmer to the ICSP pins of the Arduino and call `avrdude` with the right parameters to read the fuses of your Arduino.

    avrdude -c programmer-id -p partno -P port

For an Arduino Uno, `partno` is `m328p`. `Programmer-id` depends on the device used. In my case (mySmartUSB light) `stk500v2` is a supported and `port` is `/dev/ttyUSB0`. Here

    avrdude -c stk500v2 -p m328p -P /dev/ttyUSB0

gives the following output

    avrdude: AVR device initialized and ready to accept instructions
    Reading | ################################################## | 100% 0.01s
    avrdude: Device signature = 0x1e950f
    avrdude: safemode: Fuses OK
    avrdude done.  Thank you.

The UNO board responds with the correct signature and is ready for some action :)

### How to connect?

My USB programmer came with a 6-wire ribbon cable with 2x3 female connectors on both sides. As usual, the wire for **pin 1** is marked red. Due to a notch in at the 2x3 male connector of the programmer, the cable only fits here in one direction.

If you look at the Arduino UNO, the ICSP header is to the right of the reset button.

The pinout is as follows.

<pre>
MISO  1    2 VCC
SCK   3    4 MOSI
RESET 5    6 GND
</pre>

**NOTE** Pin 1 is the top left one, marked with a white dot!


body:
If you have another, working, Uno, and both have socketed microcontroller chips, you could use the known board to program a test sketch onto the unknown board's chip, put it back on the unknown board, and run it.

I like the following (pseudo-coded) test sketch for quick-checking my hand-built boards; it's just as handy for testing an unknown factory-built one. It's not an exhaustive test, it just checks for basic digital I/O, serial I/O, and shorts or opens:

    forever,
      for each digital I/O pin:
        write high;
        delay 100ms;
        write low;
      end;

      write "Hello, World!\n" to serial output;
      while serial character available,
        write character to serial output;
      end;
      write "\n" to the serial output;
    end;

- A test LED - an LED with its resistor soldered to it - connected between any I/O and ground should blink every 2 seconds. If it doesn't, that pin may have failed or have a bad connection.

- Two test LEDs connected to numerically adjacent pins (they may not be physically next to one another) should blink in sequence. If they blink together, it indicates a short, probably a solder bridge, between them.

- The terminal should say "Hello World!" every two seconds. If not, that pin or the FTDI cable or on-board USB/Serial chip may have failed.

- Type something on the keyboard and it should be repeated back to the serial terminal (if the previous test passed). If not, again that pin or the FTDI cable or on-board USB/Serial chip may have failed.


message:
Connecting breakout board to Arduino with UART

I'm using a [DigiX][1] (Arduino Due based 3.3V) board to connect to a GPRS/GSM SIM908 breakout board. The SIM908 EVB board has the following pins on its RS232:![RS232 pinout][2]

I've got all three UART TX lines hooked up to the RX Lines (and RX to TX) on my Arduino but the board keeps resetting, which I would guess is some sort of voltage issue (I turned the board off immediately). However there are three MAX3232s on the underside of the board, which I thought would have made it so I could just connect the lines directly to the Arduino. Does anyone know why this might be happening or how to properly connect these two devices?

Additional info:

[Pinout of the DigiX][3].

[Schematic of the DigiX][4].

(The below links are in Chinese):

Here is [a SIM908 Hardware guide][5].

[The full schematic of the breakout board][6].

  [1]: http://digistump.com/wiki/digix
  [2]: https://i.stack.imgur.com/zNZ90.png
  [3]: http://digistump.com/wiki/digix/tutorials/pinout
  [4]: http://digispark.s3.amazonaws.com/DigiX-V1-Final-Production.pdf
  [5]: http://pan.baidu.com/share/link?shareid=1471365276&uk=4130796101&third=15
  [6]: http://pan.baidu.com/share/link?shareid=1470501867&uk=4130796101&third=15

body:
Both the DigiX and the SIM908 are natively 3.3V boards. They should be able to connect to each other directly.

For some reason, the SIM908 breakout seems to only offer RS232 level serial outputs for the GPRS and GPS. On U3 (the SIM908 module itself) Pins 68/71 offer 3.3V levels for the GPRS (GPRS-TXD and GPRS-RXD) and 15/16 offer 3.3V levels for the GPS (GPS-TXD and GPS-RXD).

These are converted to RS232 levels by the MAX3232 and presented on J3 and J13. I can't see any point where the 3.3V signals are presented on a connector.

You could either:

 - Breakout the 3.3V signals onto connectors by modifying the SIM908
   breakout board.
 - Build a level converter to take the 3.3V signals from
   the DigiX to RS232 and then connect them as before.

You may have damaged the DigiX board connecting RS232 levels directly to it however. The ARM based Arduinos are far less tolerant of voltage abuse than the ATmega based Arduinos.


message:
How do I use I2C devices with Arduino?

I have a few useful I2C components, such as a 16-bit port expander (MCP23017), which I'd like to use in various projects.

What do I need to do to make these work with Arduino? Will it work with any Arduino, or do I need a specific board or shield?

body:
Additional shields are not needed.

You only need the Wire library and a couple of wires to connect the device to **SDA** and **SCL**.

The position of these pins is different on the various Arduinos, please have a look [here][1].

[1]:http://arduino.cc/de/Reference/Wire


body:
Arduino have the [Wire Library][1] that communicate with I2C.

> This library allows you to communicate with I2C / TWI devices. On the
> Arduino boards with the R3 layout (1.0 pinout), the SDA (data line)
> and SCL (clock line) are on the pin headers close to the AREF pin. The
> Arduino Due has two I2C / TWI interfaces SDA1 and SCL1 are near to the
> AREF pin and the additional one is on pins 20 and 21. As a reference
> the table below shows where TWI pins are located on various Arduino
> boards.

Board I2C / TWI pins

 - Uno, Ethernet A4 (SDA), A5 (SCL)
 - Mega2560 20 (SDA), 21 (SCL)
 - Leonardo 2 (SDA), 3 (SCL)
 - Due 20 (SDA), 21 (SCL), SDA1, SCL1

You can take a look at , [this][3] examples.

Like @TheDoctor said:
> The I2C data lines both need resistors to 3.3V. This keeps them from
> drifting if they are disabled. Andy resistor value should work, but it
> is recommended to use one between 10k ohm and 47k ohm.

  [1]: http://www.arduino.cc/en/Reference/Wire
  [2]: http://blog.digtro.com/arduino-uno-tea5767-fm-receiver-i2c/
  [3]: http://www.instructables.com/id/I2C-between-Arduinos/


body: For future readers: use the Adafruit_MCP23017 library.


message:
Why can't I declare a class in another tab in Arduino IDE?

I wanted to move some of my code out into a second tab in the Arduino IDE, to keep things better organised. At first, I only tried moving a function, and it seemed to work fine. I could call the function from the `setup()` function in my main tab, and there were no problems compiling or uploading.

However, I tried putting a whole class into the second tab, and suddenly it didn't work any more. For example:

**Tab 1:**
<!-- language: cpp -->

    TestClass obj;

    void setup()
    {
        obj.init();
    }

    void loop()
    {
        //...
    }

**Tab 2:**

    class TestClass
    {
    public:
        void init()
        {
            //...
        }
    };

When I tried to compile this, it gave me the following errors:

    tab1:1: error: 'TestClass' does not name a type
    tab1.ino: In function 'void setup()':
    tab1:5: error: 'obj' was not declared in this scope

Why does it recognise a function in another tab, but not a class? Is there a way to make it work in the Arduino IDE, or do I need to use an alternative like Eclipse?

body:
It is not possible to declare and use classes declared in one `.pde` file in another `.pde` file from within the Arduino IDE.

One workaround is to make the second file into a C++ source file (`.cpp`) and then add a `#include "<filename>"` directive in the beginning of the first file.

---

This code compiles correctly:

Tab 1:

    #include "test.cpp"

    TestClass obj;

    void setup()
    {
        obj.init();
    }

    void loop()
    {
        //...
    }

test.cpp :

    class TestClass
    {
    public:
        void init()
        {
            //...
        }
    };


body:
The way the Arduino IDE works is that it compiles your code (the code you write in the IDE) as the "main" code. Then it pulls code from all of the libraries you have imported and compiles that along with the main code. To do what you are suggesting would require you to create a library for Arduino.

### Here is some more information on Arduino libraries:
http://arduino.cc/en/Guide/Libraries

### And here is some on how to create a library:
http://arduino.cc/en/Hacking/LibraryTutorial //this one is the easiest to understand imo

http://playground.arduino.cc/Code/Library

http://www.divilabs.com/2013/03/write-your-own-arduino-library.html#

Here is an example library I wrote https://github.com/jamolnng/Arduino/tree/master/libraries/ShiftRegister as you can see there is no problem with calling Arduino functions from the .cpp file (I know, I've tested the library)


message:
Is there a semi-permanent way to attach wires to the Nano?

At least for prototyping, is there a semi-permanent way to attach wires to the Nano posts?

![Arduino nano][1]

And yes, usually the Nano is hanging in free space by its wires (yes I know, quick and dirty, should be using something cleaner, even for prototypes).  So I'm hoping for the best of both worlds, sturdy "enough" to stay attached, yet possible to remove and switch around.  Having no luck finding such advice on the internet, perhaps searching for the wrong terms.

**EDIT:**  I neglected one important point, each wire is attached individually just like the SparkFun wires with the female header as mentioned in @TheDoctor's answer below.

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

body:
There are jumper wires that have a female header on one end and a male header on the other. Example: https://www.sparkfun.com/products/9140

![jumper wires][1]

You could also attatch several wired to a strip of breakaway female headers, such as https://www.sparkfun.com/products/115

![headers][2]

  [1]: https://i.stack.imgur.com/lyllM.png
  [2]: https://i.stack.imgur.com/cdMeO.png


body: A wire wrap tool can work well for this - the wrappings tend to be fairly secure if done right, though the wire itself can break if stressed.


body:
The *entire* premise behind Gravitech's design of the Arduino Nano was for it to be plugged into a **breadboard**. If done so, then none of the pins are left *dangling*. From [Arduino's webpage for the Nano][1]:

>The Arduino Nano is a small, complete, and *breadboard-friendly* board based on the ATmega328 (Arduino Nano 3.x) or ATmega168 (Arduino Nano 2.x). It has more or less the same functionality of the Arduino Duemilanove, but in a different package. It lacks only a DC power jack, and works with a Mini-B USB cable instead of a standard one. The Nano was designed and is being produced by Gravitech.

From [Gravitech's webpage for the Nano][2]:

> Arduino Nano is a surface mount *breadboard* embedded version with
> integrated USB. It is a smallest, complete, and *breadboard friendly*.
>
> ...
>
> Nano’s got the *breadboard-ability* of the Boarduino and the Mini+USB
> with smaller footprint than either, so users have more *breadboard*
> space.

If you have a Nano in such a *dangling* state, then you are using the wrong sort of Arduino board for the wrong purpose.

Obviously a Nano will work just fine when *loose* on a surface, i.e. not plugged into a breadboard, but that is not what it was intended for, and maybe you should employ an UNO in its place.

However, if you have to use your Nano without a breadboard, then in addition to the wire wrapping, wires with female DuPont connectors, or female header strips, you could just solder wires to the holes in the nano board, if you do not already have header pins already soldered in to them.

  [1]: https://www.arduino.cc/en/Main/arduinoBoardNano
  [2]: http://www.gravitech.us/arna30wiatp.html


body:
[Here's what I use][1], repeatedly, successfully. It fits the Nano headers, and gives you screw terminals for proto work.

  [1]: http://www.aliexpress.com/item/Free-shipping-NANO-3-0-controller-Terminal-Adapter-for-NANO-terminal-expansion-board-for-arduino-Nano/1921109123.html


message:
How do I print multiple variables in a string?

Say I have some variables that I want to print out to the terminal, what's the easiest way to print them in a string?

Currently I do something like this:

    Serial.print("Var 1:");Serial.println(var1);
    Serial.print(" Var 2:");Serial.println(var2);
    Serial.print(" Var 3:");Serial.println(var3);

Is there a better way to do this?

body:
<!-- language: lang-c -->
This is probably not better, just different.
You can use the **String** object for output. These objects allow concatenation and support automatic typecasting.

    Serial.begin(9600);
    String label = "Var";
    const byte nValues = 3;
    int var[nValues] = {36, 72, 49};

    for (int i = 0; i < nValues; i++) {
        String stuff = label + i + ": ";
        Serial.println(stuff + var[i]);
    }


body:
`ardprintf` is a function that I hacked together which simulates `printf` over the serial connection. This function (given at the bottom) can be pasted in the beginning of the files where the function is needed. It should not create any conflicts.

It can be called similar to `printf`. See it in action in this example:
<!-- language-all: lang-cpp -->

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

    void loop()
    {
      int l=2;
      char *j = "test";
      long k = 123456789;
      char s = 'g';
      float f = 2.3;

      ardprintf("test %d %l %c %s %f", l, k, s, j, f);

      delay(5000);

    }

The output as expected is:

    test 2 123456789 g test 2.30

---

The function prototype is:

    int ardprintf(char *, ...);

It returns the number of arguments detected in the function call.

This is the function definition:

    #ifndef ARDPRINTF
    #define ARDPRINTF
    #define ARDBUFFER 16
    #include <stdarg.h>
    #include <Arduino.h>

    int ardprintf(char *str, ...)
    {
      int i, count=0, j=0, flag=0;
      char temp[ARDBUFFER+1];
      for(i=0; str[i]!='\0';i++)  if(str[i]=='%')  count++;

      va_list argv;
      va_start(argv, count);
      for(i=0,j=0; str[i]!='\0';i++)
      {
        if(str[i]=='%')
        {
          temp[j] = '\0';
          Serial.print(temp);
          j=0;
          temp[0] = '\0';

          switch(str[++i])
          {
            case 'd': Serial.print(va_arg(argv, int));
                      break;
            case 'l': Serial.print(va_arg(argv, long));
                      break;
            case 'f': Serial.print(va_arg(argv, double));
                      break;
            case 'c': Serial.print((char)va_arg(argv, int));
                      break;
            case 's': Serial.print(va_arg(argv, char *));
                      break;
            default:  ;
          };
        }
        else
        {
          temp[j] = str[i];
          j = (j+1)%ARDBUFFER;
          if(j==0)
          {
            temp[ARDBUFFER] = '\0';
            Serial.print(temp);
            temp[0]='\0';
          }
        }
      };
      Serial.println();
      return count + 1;
    }
    #undef ARDBUFFER
    #endif

**To print the `%` character, use `%%`.*

---

Now, available on [Github gists][1].

  [1]: https://gist.github.com/asheeshr/9004783


body:
I usually used Tabs to make things line up better in the Serial. Having things line up like I do allow the arduino to fire as fast as possible while being able to notice certain changes in the variables.

Try something like this:

    Serial.println("Var 1:\tVar 2tVar 3:");
    Serial.print("\t");
    Serial.print(var1);
    Serial.print("\t");
    Serial.print(var2);
    Serial.print("\t");
    Serial.print(var3);
    Serial.println();

Or something like this:

    Serial.print("Var 1:");Serial.println(var1);
    Serial.print("\tVar 2:");Serial.println(var2);
    Serial.print("\tVar 3:");Serial.println(var3);


body:
I usually (painfully) stick with multiple lines of `Serial.print` but when it becomes convoluted I go back to `sprintf`. It's annoying in that you have to have an available buffer for it.

Usage is as simple (??) as:

    char buffer[35]; // you have to be aware of how long your data can be
                     // not forgetting unprintable and null term chars
    sprintf(buffer,"var1:%i\tvar2:%i\tvar3:%i",var1,var2,var3);
    Serial.println(buffer);

A word of warning though, it doesn't (by default) support floating types.


body:
I wouldn't normally put two answers to a question, but I only just found [this][1] today, where you can use printf without any buffer.

    // Function that printf and related will use to print
    int serial_putchar(char c, FILE* f) {
        if (c == '\n') serial_putchar('\r', f);
        return Serial.write(c) == 1? 0 : 1;
    }

    FILE serial_stdout;

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

        // Set up stdout
        fdev_setup_stream(&serial_stdout, serial_putchar, NULL, _FDEV_SETUP_WRITE);
        stdout = &serial_stdout;

        printf("My favorite number is m!\n", 12);
    }

    void loop() {
      static long counter = 0;
      if (millis()00==0){
        printf("millis(): %ld\tcounter: %ld (X)\n", millis(), counter, counter++);
        delay(1);
      }
    }

This still has the floating point limitation.

edit: I thought I would do a little testing on this, and it works quite well. I added a better test to the loop with formatted output.

  [1]: http://forum.arduino.cc/index.php/topic,120440.0.html


body:
Using `Streaming.h`, in place of

    Serial.print("Var 1:");Serial.println(var1);
    Serial.print(" Var 2:");Serial.println(var2);
    Serial.print(" Var 3:");Serial.println(var3);

one can write

    Serial << "Var 1:" << var1) << " Var 2:" << var2 << " Var 3:" << var3 << endl;

The definition of `<<` in `Streaming.h` in effect translates that into a series of ordinary `Serial.print()` calls.  That is, `<<` is syntactic sugar, implemented without increasing code size.

If you don't have `Streaming.h` installed, get [`Streaming5.zip`](http://arduiniana.org/Streaming/Streaming5.zip) from [arduiniana.org](http://arduiniana.org/libraries/streaming/).  Unzip it in your libraries directory, for example in `~/sketchbook/libraries`.  Add the line `#include <Streaming.h>` within sketches where you use `<<` as a stream operator.

Base-conversion specifiers _HEX, _DEC, _OCT, and _BIN are provided, as well as a _FLOAT function (with number of decimal places) and `endl`.  For example, to print latitude and longitude values in a form like "Your coordinates are -23.123, 135.4567” one could write:

    Serial << "Your coordinates are " << _FLOAT(latitude,3) << ", " << _FLOAT(longitude,4) << endl;

This could also be written as

    Serial << F("Your coordinates are ") << _FLOAT(latitude,3) << ", " << _FLOAT(longitude,4) << endl;

which would keep the longer string in PROGMEM instead of bringing it into RAM.

Note, `Streaming.h`  doesn't build any strings as such; it just delivers the text of its `<<`-arguments to a stream.  A [PString class at arduiniana](http://arduiniana.org/libraries/pstring/) can build strings from stream inputs, if strings instead of streamed output are desired or needed.


body:
From http://playground.arduino.cc/Main/Printf
I observed this is working fine on my mega2560

That's all it just worked, no need for vsnprintf_P or PROGMEM ...

<!-- language-all: lang-cpp -->

    #include "Arduino.h"
    void local_printf(const char *format, ...)
    {
    static char line[80];
    va_list args;
    va_start(args, format);
    int len = vsnprintf(line, sizeof(line), format, args);
    va_end(args);
    for (char *p = &line[0]; *p; p++) {
        if (*p == '\n') {
            Serial.write('\r');
        }
        Serial.write(*p);
    }
    if (len >= sizeof(line))
        Serial.write('$');
    }

    void setup()
    {
    Serial.begin(115200);
    local_printf("%s:%d: %s\n", __FILE__, __LINE__, __PRETTY_FUNCTION__);
    }

    void loop()
    {
    static int count=0;
    local_printf("%s:%d: %s %d\n", __FILE__, __LINE__, __PRETTY_FUNCTION__, count++);
    delay(1*1000);
    }

    // src/main.c:24: void setup()
    // src/main.c:30: void loop() 0
    // src/main.c:30: void loop() 1


body:
<!-- language-all: lang-cpp -->

The usage will depend of the data type of your variables.

If they are `int`, it would be `%d` or `%i`
If they are `string`, it would be `%s`

**Wrapper for printf**

You can change the limit based on your requirements

    #include <stdarg.h>
    void p(char *fmt, ... ){
        char buf[128]; // resulting string limited to 128 chars
        va_list args;
        va_start (args, fmt );
        vsnprintf(buf, 128, fmt, args);
        va_end (args);
        Serial.print(buf); // Output result to Serial
    }

Source: https://playground.arduino.cc/Main/Printf

Usage examples:

    p("Var 1:%s\nVar 2:%s\nVar 3:%s\n", var1, var2, var3); // strings
    p("Var 1:%d\nVar 2:%d\nVar 3:%d\n", var1, var2, var3); // numbers

**ESP8266**

Its built-in in `Serial` class of the framework. No need for additional library or function.

    // strings
    Serial.printf("Var 1:%s\nVar 2:%s\nVar 3:%s\n", var1, var2, var3);
    // numbers
    Serial.printf("Var 1:%d\nVar 2:%d\nVar 3:%d\n", var1, var2, var3);

----

More details about formatting tips on the printf format reference page : http://www.cplusplus.com/reference/cstdio/printf/

`\n` is the escape sequence for the line feed.

> Escape sequences are used to represent certain special characters within string literals and character literals.

Source: http://en.cppreference.com/w/cpp/language/escape

**[EDIT]**
- As @Juraj mentioned, it's not available on most of the AVR modules. So I added ESP8266 mention and a printf wrapper for common AVR modules


body:
I only use this for debugging but:

    int a = 10;
    int b = 20;
    Serial.println("a = " + String(a) + " and b = " + String(b));


body:
I am newbie in Arduino world, but I recently found that this is just a regular C++ (without exceptions and probably polymorphism). But you still can enjoy templates. So my solution is to use following templates:

    void myprint(void)
    {
      Serial.println("");
    }

    template<typename ...Args>
    void myprint(const uint64_t & val, Args && ...args)
    {
      serialPrintUint64(val);
      myprint(args...);
    }

    template<typename T, typename ...Args>
    void myprint(const T & t, Args && ...args)
    {
      Serial.print(t);
      myprint(args...);
    }

    ....

    // somewhere in your code
    myprint("type: ", results.decode_type,
            "\t value: ", results.value,
            "\t addr: ", results.address,
            "\t cmd: ", results.command);

Nice thing here is that it does not use any extra memory and extra processing here.


body:
> One possible solution is:
>
> `Serial.println((String)"Var 1:" + var1 + " Var 2:" + var2 + " Var 3:" + var3);`

The above solution from Iain increases code size.


body:
I've been using PrintEx for years, and it works great.  See [enter link description here][1]

  [1]: https://www.arduino.cc/reference/en/libraries/printex/


message:
Is there any way to download a sketch from an Arduino?

I made a sketch, but then I lost it. However, I uploaded it to the Arduino before losing it. Is there any way I can get it back?

body:
It should be possible as long as the security bit isn't set. This question was asked on EE a while back.

[Is it possible to extract code from an arduino board?][1]

But you won't get the Arduino code you wrote back. The code is compiled into assembly and you'll have to convert that back to C yourself.

  [1]: https://electronics.stackexchange.com/questions/61079/is-it-possible-to-extract-code-from-an-arduino-board


body: You can download the hex dump of the file, but there is no easy way to get all the C++ code and comments. If you can understand assembly, you could recreate the program, but that would take a while. There are dissasemblers available for some devices, i don't know about arduino.


body:
This answer doesn't directly answer the question, but still will result in the same end result.

The Arduino IDE uses temporary directories to store build files, including the original sketch as well as the HEX and intermediate files.

On a Mac, these are in /var/folders by default, and on a Windows machine they are in …\Local Settings\Temp\ (which depending on the version of Windows could be in several places).

I've found that especially in Windows, these build files don't get deleted when you close the sketch or IDE, so they may exist on your machine for far longer than you would think.

Also, by default, Crashplan, Backblaze and Time Machine back-up these locations, so even if they have been deleted, they may still be in a backup.

The advantage here is that you will recover C code rather than ASM.


body:
I think there is another way to do this, without extracting the code from the Arduino board. Remenber the date you create the sketch, and look for it in  C:\Users\User\AppData\Local\Temp\
(For example : C:\Users\User\AppData\Local\Temp\untitled4390292704786567977.tmp\sketch_jan19a ). You could find your unsaved code unless it was deleted by some "freeing space program".
Good luck!


body:
Unless your objective is to simply copy the identical code to another device, the simple answer is: **no**

As has been pointed out in other answers, you can turn the hex code on the device back into assembler code.

For example (once you have copied the code from the device back onto your disk):

    avr-objdump -j .sec1 -d -m avr5 yourFileHere.hex

Run on one of the bootloader files I get these results (in part):

    00007e00 <.sec1>:
        7e00:       11 24           eor     r1, r1
        7e02:       84 b7           in      r24, 0x34       ; 52
        7e04:       14 be           out     0x34, r1        ; 52
        7e06:       81 ff           sbrs    r24, 1
        7e08:       f0 d0           rcall   .+480           ;  0x7fea
        7e0a:       85 e0           ldi     r24, 0x05       ; 5
        7e0c:       80 93 81 00     sts     0x0081, r24
        7e10:       82 e0           ldi     r24, 0x02       ; 2
        7e12:       80 93 c0 00     sts     0x00C0, r24
        7e16:       88 e1           ldi     r24, 0x18       ; 24
        7e18:       80 93 c1 00     sts     0x00C1, r24
        7e1c:       86 e0           ldi     r24, 0x06       ; 6
        7e1e:       80 93 c2 00     sts     0x00C2, r24
        7e22:       80 e1           ldi     r24, 0x10       ; 16
        7e24:       80 93 c4 00     sts     0x00C4, r24
        7e28:       8e e0           ldi     r24, 0x0E       ; 14
        7e2a:       c9 d0           rcall   .+402           ;  0x7fbe
        7e2c:       25 9a           sbi     0x04, 5 ; 4

As you can see, not particularly helpful for reproducing what your sketch did. There are likely to be one of two scenarios:

* Your sketch was short, in which case you might, after weeks of work, turn the assembler code back into C
* Your sketch was long, in which case it would be virtually impossible to turn it back into C

In the "short sketch" case, you are better off just rewriting from scratch. That would be faster, almost certainly. In the "long sketch" case - it just isn't worth it. None of the variable names are preserved, and the way the compiler optimizes code, even the structure of the code would be hard to determine.


body:
**Download**:

```sh
avrdude \
    -c <programmer type> \
    -P <connection port> \
    -b <override RS-232 baudrate> \
    -p <partno, AVR device> \
    -U <memtype>:r:file_name[:format]
```

**Upload**:

Use `w` (write) instead of `r` (read) for the `-U` option.

More details at [manual - avrdude Option-Descriptions][1].

---

**Example**:

Download UNO v3 (ATmega328) flash ROM (bootloader) given port `/dev/ttyACM0` as Intel HEX:

```sh
avrdude -c arduino -P /dev/ttyACM0 -b 115200 -p m328p -U flash:r:SaveFlash.hex:i
```

---

If used directly from from the arduino IDE archive also add:

    -C path-to/arduino-V/hardware/tools/avr/etc/avrdude.conf

  [1]: https://www.nongnu.org/avrdude/user-manual/avrdude_4.html#Option-Descriptions


body:
Another approach might be to treat the program onboard the Arduino as a black-box exercise. That is, run the program and take careful notes of what happens (via Serial Monitor or whatever). If, in fact there is any output that you can observe, make it a task to create your own new code to emulate what the program DOES. This won't be productive unless the original programmer liberally included Serial.print() statements throughout the code, something I STRONGLY RECOMMEND as a programming habit to develop. Doing so, facilitates just the exercise I am suggesting. (Ask me why I developed that habit for everything I have coded for the past 30 years.)

Unfortunately, most people sprinkle a few comments here and there, which is helpful 5 years later if you have the source code. Personally, I comment EVERY LINE of source code. But comments in the source don't help later in this sort of situation, as the compiler doesn't put them in the machine code it generates. (Perhaps that might be a valuable option for the compiler. Yes, it takes bytes, but how valuable might it be years later for an important project?)

My two cents worth, which probably is worth the price the reader of this post paid to see it!


message:
How to connect two Arduino without shields?

I'm planning an Arduino system that consists of several Arduino boards. The maximum distance between the boards is about 50 meters. I want to send basic data between these, like short strings or integers. I know I could send data through ethernet cables but that requires an ethernet shield or the Arduino Ethernet board that doubles the costs. Is there a low budget way I could connect the boards using only the most basic boards (like Uno) and some other components but not a full shield?

body:
There are two categories i can think of to classify comminucation features of the Arduino boards:

__Between 2 devices:__

* Serial: Easy to use and only requires 2 data lines.
* OneWire: Harder to use and slow, but uses only one data line

__Between more than 2 devices__

* I2C: You can have up to 128 devices on a network, individually addressable, but requires a master device, uses 2 data lines. this is know also as Wire.
* SPI: difficult to use, but very fast and easy device selection. uses a lot of data lines (3 + num of devices)
* OneWire: using addressed oneWire is even slower than regular oneWire, still only one data line
* SoftwareSerial: You can have several devices connected by different Serial lines, but it is slower.
* CAN: only available on the Due, and addressable

There are other methods available, but these listed only require a minimum of external hardware.

For distance ratings, see http://forum.arduino.cc/index.php?topic=82937.0 and http://www.tldp.org/HOWTO/Remote-Serial-Console-HOWTO/serial-distance.html

These data rates are directly controlled in Serial and can be tweaked in many others.


body:
For long distance wired communication, look at [RS-485][1].

> Since it uses a differential balanced line over twisted pair (like
> RS-422), it can span relatively large distances (up to 4,000 feet
> (1,200 m)). A rule of thumb is that the speed in bit/s multiplied by
> the length in meters should not exceed 108. Thus a 50 meter cable
> should not signal faster than 2 Mbit/s

You can use the MAX485 chip. It's pretty easy to work with but there's a good library as well:

https://github.com/Protoneer/RS485-Arduino-Library

  [1]: http://en.wikipedia.org/wiki/RS-485


body:
Freakduino makes some Arduino boards with built in wireless. Their long range wireless is 900 MHz and their shorter range is 2.4GHz. I think they are actually XBee radios and for programming you would use a library called chibiArduino, which is available (and documented) on the Freakduino website. When communicating wirelessly with another radio you can use Broadcast or specify a radio by it's ID which is a value you need to set in the EEPROM of the Freakduino.

Taken directly from the Freakduino site:

> The addition of an integrated wireless radio based on the IEEE 802.15.4 protocol (same radio protocol as the XBee) allows for wireless control of devices or wireless sensor data collection. Optional battery circuitry was added so that it could function as a true wireless node without any external power cables. The board is also designed to fit a ruggedized enclosure so that the design can be transported safely or deployed in an actual usage scenario without worrying about damaging the circuitry.
>
>This 900 MHz radio is a personal favorite of mine. I use it all the time because 900 MHz offers much better range compared to 2.4 GHz. The radio can output up to 10 mW of transmit power which can get a surprising amount of range. With direct line of sight, a few hundred meters would not be surprising. If additional range is needed, the modulation mode can also be changed from OQPSK to BPSK. This results in additional range at the expense of data rate, with the max going from 250 kbps to 40 kbps in standard mode.


body:
Like you said, Ethernet shields are expensive, but you don't have to use the shield.  Check out the [enc28j60][1] for wired networking, or the [ESP8266][2] if you would prefer wireless.  Both are about $4USD.  I am using the ESP8266 now and have about 8 devices talking to each other and a Raspberry Pi.  It is a really great little chip!  I cannot speak personally to the ENC28j60, as they are still sitting in the package on my desk.

  [1]: https://www.google.com/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=enc28j60
  [2]: https://www.google.com/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#safe=off&q=esp8266


body: You could use a Ethernet breakout board ($2 at Sparkfun).  This lets you use the Ethernet cables but you don't have to use a full TCP/IP protocol, instead you can just hook up data pins to the breakout board, use the Ethernet to connect them, and then have them talk using serial.  I use this quite a bit to place one wire sensors further from the Arduino for a strong yet cheap connection.


message:
Button state changing randomly

I have a push button wired to my Arduino but it seems to be triggering randomly.

I have one pin of the button connected to pin 2 on the arduino and the other connected to ground.

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

        pinMode(2, INPUT);
    }

    void loop() {
        Serial.println(digitalRead(2));
    }

I expect it to print 1 continuously and go to 0 when I press the button down but sometimes it shows 0 even when I don't touch it.

body:
When a button is connected in that configuration, the input is what's called *floating*, meaning it's not a 0 or a 1. When the button is pressed, it is connected to ground, so that's definitely a 0, but when it's not pressed down, we don't know the value of the pin.

## Pull Up Resistor
We need to include what's called a "pull-up" resistor to pull the signal up to a logic 1 when the button is not pressed.

![pull up resistor][1]

[Image from Sparkfun][2]

What this means is when the button is not pressed, the Arduino reads a logic 1. When the button is pressed, the current flows through the resistor to ground and the Arduino reads a logic 0.

## Internal Pull Up Resistor
The Arduino also has internal pull up resistors so you don't necessarily have to add an extra component to your circuit. There are a couple of ways to use this.

You used to have to do it like this:

    pinMode(pin, INPUT);           // set pin to input
    digitalWrite(pin, HIGH);       // turn on pullup resistors

Now we can do it simply in one line:

    pinMode(pin, INPUT_PULLUP);

This enables the 20k pull up resistor on that pin. The input will no longer be floating when the button is not pressed.

**Note:** This only works when the other end is connected to ground.

  [1]: https://i.stack.imgur.com/h9oX1.jpg
  [2]: https://learn.sparkfun.com/tutorials/pull-up-resistors/what-is-a-pull-up-resistor


message:
What happens when I call exit() from my program?

In either of `setup` or `loop`, if I were to add an `exit(0)` call, where would control be passed to? What would the next state of the microcontroller be? Would it stop execution and power down?

I am using a revision 2 Arduino Uno.

body:
Well I just tested it with my Arduino Uno and it just completely stopped the code and left all the outputs as they were when the code stopped running (so it left an LED I had on on). There seems to not be a IO cleanup when you call exit. This was what I expected because the Arduino IDE provides the setup and loop functions, if you program the ATMEGA*28 with with any other AVR IDE you start with the main function like all C/C++ programs. The setup and loop functions are not standard on AVR MCU's.

**Note:** The press of the reset button restarts the code, if you were wondering.


body:
My initial guess is wrong. I would have thought it would simply return from loop and the core library would just call loop() again. However, I see the following code was created. Noticing that __stop_program is a hard loop...

An extract of Blink.ino's listing, with exit(0) added:

<!-- language: lang-cpp -->

    // the loop routine runs over and over again forever:
    void loop() {
      digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
      delay(1000);               // wait for a second
      digitalWrite(led, LOW);    // turn the LED off by making the voltage LOW
      delay(1000);               // wait for a second
      exit(0);
    }

The disassembly of the above:

    // the loop routine runs over and over again forever:
    void loop() {
      digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
     100: 80 91 00 01  lds r24, 0x0100
     104: 61 e0        ldi r22, 0x01 ; 1
     106: 0e 94 ca 01  call 0x394 ; 0x394 <digitalWrite>
      delay(1000);               // wait for a second
     10a: 68 ee        ldi r22, 0xE8 ; 232
     10c: 73 e0        ldi r23, 0x03 ; 3
     10e: 80 e0        ldi r24, 0x00 ; 0
     110: 90 e0        ldi r25, 0x00 ; 0
     112: 0e 94 f7 00  call 0x1ee ; 0x1ee <delay>
      digitalWrite(led, LOW);    // turn the LED off by making the voltage LOW
     116: 80 91 00 01  lds r24, 0x0100
     11a: 60 e0        ldi r22, 0x00 ; 0
     11c: 0e 94 ca 01  call 0x394 ; 0x394 <digitalWrite>
      delay(1000);               // wait for a second
     120: 68 ee        ldi r22, 0xE8 ; 232
     122: 73 e0        ldi r23, 0x03 ; 3
     124: 80 e0        ldi r24, 0x00 ; 0
     126: 90 e0        ldi r25, 0x00 ; 0
     128: 0e 94 f7 00  call 0x1ee ; 0x1ee <delay>
      exit(0);
     12c: 80 e0        ldi r24, 0x00 ; 0
     12e: 90 e0        ldi r25, 0x00 ; 0
     130: 0e 94 1e 02  call 0x43c ; 0x43c <_exit>

    ...

    0000043c <_exit>:
     43c: f8 94        cli

    0000043e <__stop_program>:
     43e: ff cf        rjmp .-2       ; 0x43e <__stop_program>

Note that if _exit had not called cli, interrupts would be able to do stuff. But that is not the case.


message:
What happens if there is a runtime error?

What happens if there is a runtime error in a program? Will execution of the program just stop? Is there some way I can get the Arduino to tell me what the error is?

body:
You'd need a hardware debugger for something like this. But usually you'll see the program not behaving as you expect it to and will have to look at that section of the code to identify the problem.

A common/quick/easy way to do this is to add print statements to print out the values of variables or just anything so you know the program gets to that point in the code without a problem. This will help you isolate the problem further.

I believe [VisualMicro][1] has some debugging functionality built in.

  [1]: http://www.visualmicro.com/


body: I would assume the AVR CPU doesn't have any error detection or recovery tools. It may just stop, or keep going ignoring the error and the consequences. Like sachleen said, you should add some debug statements in your program that print out data in the middle of an operation, to test if it's working. If you use an emulaor and set breakpoints, you could easily find a problem.


body:
First, let's see a few examples of what can go wrong.

# Uninitialized local variables #

    void setup() {
      int status;
      pinMode(13, OUTPUT);
      digitalWrite(13, status);
    }

As pointed out by [Edgar Bonet](https://arduino.stackexchange.com/users/7508/edgar-bonet) in the comments, local variables like `status` in the code above are not implicitly initialized by the C++ compiler. So, the outcome of the code above is indeterminate. To avoid that, make sure you always assign values to your local variables.

Things are a bit different with global and static variables:

> Global and static variables are guaranteed to be initialized to 0 by the C standard.

Source:
[AVR Libc Reference Manual - Frequently Asked Questions - Shouldn't I initialize all my variables?](http://www.atmel.com/webdoc/AVRLibcReferenceManual/FAQ_1faq_varinit.html)

That means you shouldn't worry about initializing them to 0 in your code. In fact, you should really avoid it, as the initialization may waste memory. Only initialize them to values other than 0.

# Memory overflow #

    int array[10];
    int v = array[100];
    array[-100] = 10;

The first problem here is that you don't know what will be assigned to v, but worse is that you don't know what you messed up with the assignment to position -100 of `array`.

# Jump to an illegal instruction #

    void doSomething( void ) {
        for (int i = 0; i < 1000; i++);
    }

    void setup ()
    {
        void (*funcPtr)( void );

        funcPtr = &doSomething;
        funcPtr(); // calls doSomething();

        funcPtr = NULL;
        funcPtr(); // undefined behavior
    }

The first call to `funcPtr()` will actually be a call to `doSomething()`. Calls like the second one may lead to undefined behavior.

# Other bad things that may happen #

Well, you can run out of RAM, for example. What else. In any case, I think your program will keep running, probably not the way you intended it to.

# Kinds of Protection #

In computer systems, problems like these are usually dealt with at various levels:

1. By the compiler
1. By the programming language runtime (as in Java for example).
1. By the operating system or the processor (if your memory access a position outside the boundaries of the address space reserved to your program, the OS or the processor may have safety mechanisms to prevent that)

Arduinos only have limited protection of the compiler, and probably nothing else. The good news is that they aren't multi-tasked, so the only program being affected is yours. In any case, any of those bugs will lead to erratic behavior.

# The Answers #

The assumptions are the all of the problems I stated above are runtime problems.

> What happens if there is a runtime error in a program?

The program will continue and what happens will depend on the side-effects of the runtime error. A call to the null function pointer will probably make the program jump to an unknown location.

> Will execution of the program just stop?

No, it will keep going as if nothing extraordinary happened, probably doing what you didn't intend it to do. It may reset or act erratically. It may turn some inputs into outputs and burn a sensor or two (but that's *highly unlikely*).

> Is there some way I get the Arduino to tell me what the error is?

I don't think so. As I said earlier, the protection mechanisms aren't there. There's no runtime support from the language, no OS, no hardware checks for out-of-bounds memory access (the bootloader doesn't count as either). You just have to be careful with your program and probably set your own safety nets.

The reason for the lack of protection is probably because Arduino controllers are too cheap, have too little memory, and should not run anything too important (yes, there seems to be a disclaimer by AVR somewhere for you not to use the MCUs normally used by Arduino in life support systems).


body:
There are no runtime exceptions. There is only undefined behaviour.

Really, there are no exceptions *at all*. If you try to perform an invalid operation, it's results will be unknown.

There is no runtime checking at all, except what **you** implement. Your program is running on bare-metal hardware. It's the Desktop equivalent of running in [ring-0](http://en.wikipedia.org/wiki/Ring_(computer_security)) all the time, because the ATmega *doesn't have rings*.


body:
There is one mechanism that can get MCU from erratic state and it's the **watchdog timer**. If you're implementing some code that will repeatedly run in a loop, that will not run anytime longer than some fixed time, you can set this time as watchdog period and enable the timer.

Then, you have to repeatedly reset the timer in the loop. If your code freezes at some condition loop that will never end, then the watchdog will count to zero and eventually reset the MCU.

This way you are losing data, but if you run the AVR WDT in interrupt mode, you can store some data before resetting the MCU.

So the watchdog timer can guard your code from occasional unintended endless loops.

Documentation: [AVR132: Using the Enhanced Watchdog Timer][1]

  [1]: http://www.atmel.com/Images/doc2551.pdf


message:
How to really shrink a sketch

I want to make a sketch that is as small as possible, for test purposes. The problem is, when i compile the BareMinimum sketch (with an empty setup and loop), i get 466 bytes for the Uno and a whopping 4,242 for the Leonardo. Is there any way to write your own code that has no extra functions (namely Timer0 for `millis()` and `delay()`). I would also like to be able to disable the keyboard/mouse functions for the Leonardo.

body:
You should be able to create your own board definition with a custom boards.txt file as per https://github.com/arduino/Arduino/wiki/Arduino-IDE-1.5---3rd-party-Hardware-specification. As I see there are several usb features in the leonardo's definition. I would hope that the compiles inclusion of the 4K is based off of these flags and not the processor type.

Where the boards.txt would use the upload, bootloader sections from the Leonardo and the build from the uno.

This is all assuming the core library build does not use processor specific flags to include USB functions.

*If you get such working. post back, I am sure others would be interested in such.*

----------
I recently ran into this 4K used limitation on a library demo that actually maxed out the UNO and had to put in a

    #if !defined(__AVR_ATmega32U4__)
    ...

around a large chunk of extra features in the sketch to fit on the Leonardo.

I had assume (wrong) that this 4K was because I still included Serial.print which when over the USB's CDC on the Leo. But I see after a memory dump of an empty sketch they are still there.

    C:\Users\mflaga\AppData\Local\Temp\build8958339595868119500.tmp>avr-objdump -d sketch_feb13a.cpp.elf > sketch_feb13a.cpp.elf.lst

Which makes sense. As the Leonardo still requires the USB-CDC client (the 4K) as to detect the 1200 Baud connect from AVR-DUDE as to stroke the remote reboot.

----------

Hence making a custom boards.txt without USB in the build, also needs to have

    leonardo.upload.use_1200bps_touch=true

removed.

Once loaded on the target, this would require the upload to be synchronized with a manual reset of the target. As the ability to remote reboot is lost.


body:
I recently wanted to do exactly this. Since there is no nice way to do so, I wound up [writing a patch][1] for the [Stino][2] sublime-text arduino plugin to do exactly this. It's subsequently been accepted, so it should be in any up-to-date Stino installs.

This adds a new option to Stino:

![enter image description here][3]

Using this mode produces compilation results like the following:

For a Uno:

> Binary sketch size: 172 bytes (of a 32256 byte maximum, 0.53 percent).
> Estimated memory use: 0 bytes (of a 1024 byte maximum, 0.00 percent).

For a leonardo

> Binary sketch size: 240 bytes (of a 28672 byte maximum, 0.84 percent).
> Estimated memory use: 0 bytes (of a 2560 byte maximum, 0.00 percent).

Actually *programming* the leonardo with the above compiled output is *probably* a bad idea, as it *might* break the auto-reset functionality, but you *could*, if you wanted. Hat-tip to mpflaga for noting this in his answer.

Note that the memory reports are actually incorrect, but that's a [separate issue][4].

The code used for the above is:

    int main()
    {
     while (1)
     {

     }
    }

Some notes:

 - You ain't writing a "Sketch" anymore, not that you ever actually *do* write a sketch. You write **programs**. Period. I don't care what the Arduino wackos want to say, they don't get to redefine terms.
 - All interrupt management is manual. This means no `milis()` or similar.
 - You *can* still use the arduino serial libraries and so forth, if you want. You do have to `#include <Arduino.h>`.
 - You define `main`. You don't ever return from `main`. If you want setup stuff, it goes before the `while (1)`.

  [1]: https://github.com/Robot-Will/Stino/pull/123
  [2]: https://github.com/Robot-Will/Stino
  [3]: https://i.stack.imgur.com/9p7tO.png
  [4]: https://github.com/Robot-Will/Stino/pull/127
  [5]: https://github.com/Robot-Will/Stino
  [6]: http://www.baeyens.it/eclipse/


body:
Although it depends on your sketch, you can somewhat decrease the size by **reusing code with methods.**

Take this code:

    int led = 13;
    int val;

    void setup() {
      pinMode(led, OUTPUT);
    }

    void loop() {
      digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
      delay(1000);               // wait for a second
      digitalWrite(led, LOW);    // turn the LED off by making the voltage LOW
      delay(1000);               // wait for a second

      digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
      delay(1000);               // wait for a second
      digitalWrite(led, LOW);    // turn the LED off by making the voltage LOW
      delay(1000);               // wait for a second

      digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
      delay(1000);               // wait for a second
      digitalWrite(led, LOW);    // turn the LED off by making the voltage LOW
      delay(1000);               // wait for a second

      digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
      delay(1000);               // wait for a second
      digitalWrite(led, LOW);    // turn the LED off by making the voltage LOW
      delay(1000);               // wait for a second

      val = digitalRead(10);
    }

1,322 bytes on Arduino Uno. Now let's shrink it a bit:

    int led = 13;
    int val;

    void setup() {
      pinMode(led, OUTPUT);
    }

    void loop() {
      for(uint8_t i = 0; i < 8; i++) {
        blink(HIGH);
        blink(LOW);
      }
      val = digitalRead(10);
    }

    void blink(uint8_t state) {
      digitalWrite(led, state);   // turn the LED to the right state
      delay(1000);                // wait for a second
    }

1,194 bytes. That's about a 10% decrease!

Anyway, although it doesn't *greatly* shrink a sketch, it sometimes can be the easiest route when you are two bytes over the limit, or just want to make a more compact sketch to begin with without loosing any functionality. It's not for every situation, but I find it useful sometimes.


body:
@annonomus penguin, sure we can
Although the code compiles into 1180 bytes flash + 13 bytes RAM for an uno on my computer, we can improve on it :) so golf challenge accepted and also a few usefull tips since we are in the business of learning.

Step 1: decrease variable requirements.
Using an int for a led port seems a bit overkill, we certainly don't have 65535 addressable IO ports on the arduino :) So we change it to a byte just for the fun of it. We will change it over to a #define later on, but to show the impact of using too large variable types.

    byte led = 13;
    int val;

    void setup() {
      pinMode(led, OUTPUT);
    }

    void loop() {
      blink();
      val = digitalRead(10);
    }

    void blink() {
      digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
      delay(1000);               // wait for a second
      digitalWrite(led, LOW);    // turn the LED off by making the voltage LOW
      delay(1000);               // wait for a second
    }

Compiles into 1172 bytes + 13 byte RAM. This saves 8 bytes of flash due to fewer needed operations for the byte instead of a integer. I would expect 12 bytes of ram, but okay. Not that much, but every byte saved is good.

Step 2: change over variable into defines when it makes sense.
For example, the led byte is not needed, the pin won't unsolder itself.

    #define LED 13
    int val;

    void setup() {
      pinMode(LED, OUTPUT);
    }

    void loop() {
      blink();
      val = digitalRead(10);
    }

    void blink() {
      digitalWrite(LED, HIGH);   // turn the LED on (HIGH is the voltage level)
      delay(1000);               // wait for a second
      digitalWrite(LED, LOW);    // turn the LED off by making the voltage LOW
      delay(1000);               // wait for a second
    }

Compiles into 1142 bytesflash + 11 bytes ram. Already 38 bytes saved. This is due to fewer register operations needed to fetch the int value. Also we saved 2 bytes from RAM. (still wondering why the byte didn't compile into 1 less byte of ram.....)

Step 3: optimize code.
I see 2 delays. I wonder if i change it to 1 delay it would save space, but i have to figure out the value of the LED pin and toggle (invert) it. We can do that with digitalRead(), but will it save space?

    #define LED 13
    int val;
    void setup() {
      pinMode(LED, OUTPUT);
    }
    void loop() {
      blink();
      val = digitalRead(10);
    }
    void blink() {
      digitalWrite(LED, !digitalRead(LED));   // toggle the led based on read value
      delay(1000);               // wait for a second and spare yourself the other delay
    }

Compiles into 1134 bytes + 11 bytes ram. Yay! another 8 bytes. That makes a total of 46 bytes and 2 fewer lines of code.

Also another general tip on decreasing codesize. Don't use the String class. It's HUGE, learn how to deal with char arrays, strcpy(), strcmp(). If all you have are some basic string operations, the usage of the String class is mostly just wasting space on both flash and RAM.


message:
When to use different variable types?

There are several different types in the Arduino programming language. They each have different applications that can use up the limited RAM in the Arduino. When should i use each?

body:
An overview of the most commonly used variables:

* __byte__: uses one byte (8 bits), holds numbers from 0 to 255
* __char__: a signed byte
* __boolean__: uses 1 byte, but only holds a value of `true` or `false`
* __int__: uses 2 bytes, holds numbers from -32768 to 32767, mostly used in general programming. an `int` is what is known as a signed variable, where the last bit controls if it is negative or positive
* __long__: uses 4 bytes, holds numbers from -2147483647 to 217283648, it is also signed
* __long long__: uses 8 bytes, can hold -9223372036854775808 to 9223372036854775807, signed
* __float__: uses 4 bytes, holds decimals from -3.4028235E+38 to 3.4028235E+38.
* __double__: almost identical to `float`
* __string__: an array of chars that represent text
* __String__: not to be confused with `string`, this is a class that holds text data with extra [functions](http://arduino.cc/en/Reference/StringObject)

Most variable declarations can be prefixed with `signed` or `unsigned` to change the function of the sigh bit. For example, `unsigned int x = 0;` would create a variable that holds numbers from 0 to 65535 because the sign bit is used as an extra data bit.


body:
One should appreciate that the Arduino is an Embedded Processor. *Specifically that it has limited resources of RAM and ROM(aka Flash/program space).*

Often is the case I see coding use the "int" defaultly. Almost sloppily. If that works great.

BUT!!!!
You can run out of room REAL FAST with only 2K of RAM.

I would recommend that you size down your type to the minimum of what it needs to be describing it. One also gets a better understanding of what it really is and its limitations. There is no need for an array of int(16bits) from bytes that were recieved from the SPI, UART or I2C. Or a matrix of RGB's that consume 3 bytes each, being int's. You cut your capacity in half.

The pro/con: PRO: using default int everywhere makes it more inter changeable. The CON is that such interchangeability can lead to unintentional casting errors.

I would also recommend using C99 type def's which can be found at "http://www.nongnu.org/avr-libc/user-manual/group__avr__stdint.html" and elsewhere. It makes things vivid, regards to this aspect. Hence a "int" would be a "int16_t", "unsigned long" be "uint32_t" etc...

It is worth knowing that in some cases a byte or char can not be replaced with int8_t, as such when used with string array functions. But they are still just as vivid.


message:
Sending Large Amounts of Serial Data

So in the fields of robotics sometimes you need multiple boards and or computers linked together to share information or save statistical data. Currently I need to send a few different variables over a serial connection and was wondering what was the best way to go about doing such?

So far I've determined that sending structures would probably be the easier way to send data. Does anyone know of any other way that might be more efficient?

Please keep in mind that I will essentially be having to send the data for 4 motors, compressor, different temperatures, random things, and the 3 sections of the arm.

body:
With my personal thoughts on Structs being the most efficient way to send many different variables I've constructed a library to help make it easier to send structs and variables over serial.  [Source Code][1]

In this library it makes sending through serial easily. I've used with with hardware and software serial. Usually this is used in conjunct with xbee's so I can wirelessly send the data to and from the robot.

When sending data it make it simple as it allows you to either send a variable or a struct (it doesn't care).

**Here is an example of sending a simple char over the serial:**

    // Send the variable charVariable over the serial.
    // To send the variable you need to pass an instance of the Serial to use,
    // a reference to the variable to send, and the size of the variable being sent.
    // If you would like you can specify 2 extra arguments at the end which change the
    // default prefix and suffix character used when attempting to reconstruct the variable
    // on the receiving end. If prefix and suffix character are specified they'll need to
    // match on the receiving end otherwise data won't properly be sent across

    char charVariable = 'c'; // Define the variable to be sent over the serial
    StreamSend::sendObject(Serial, &charVariable, sizeof(charVariable));

    // Specify a prefix and suffix character
    StreamSend::sendObject(Serial, &charVariable, sizeof(charVariable), 'a', 'z');

**Example of sending a simple int over the serial:**

    int intVariable = 13496; // Define the int to be sent over the serial
    StreamSend::sendObject(xbeeSerial, &intVariable, sizeof(intVariable));

    // Specify a prefix and suffix character
    StreamSend::sendObject(xbeeSerial, &intVariable, sizeof(intVariable), 'j', 'p');

**Example of sending a struct over serial:**

    // Define the struct to be sent over the serial
    struct SIMPLE_STRUCT {
      char charVariable;
      int intVariable[7];
      boolean boolVariable;
    };
    SIMPLE_STRUCT simpleStruct;
    simpleStruct.charVariable = 'z'; // Set the charVariable in the struct to z

    // Fill the intVariable array in the struct with numbers 0 through 6
    for(int i=0; i<7; i++) {
      simpleStruct.intVariable[i] = i;
    }

    // Send the struct to the object xbeeSerial which is a software serial that was
    // defined. Instead of using xbeeSerial you can use Serial which will imply the
    // hardware serial, and on a Mega you can specify Serial, Serial1, Serial2, Serial3.
    StreamSend::sendObject(xbeeSerial, &simpleStruct, sizeof(simpleStruct));

    // Send the same as above with a different prefix and suffix from the default values
    // defined in StreamSend. When specifying when prefix and suffix character to send
    // you need to make sure that on the receiving end they match otherwise the data
    // won't be able to be read on the other end.
    StreamSend::sendObject(xbeeSerial, &simpleStruct, sizeof(simpleStruct), '3', 'u');

**Receiving Examples:**

**Receiving a char that was send via Streamsend:**

    char charVariable; // Define the variable on where the data will be put

    // Read the data from the Serial object an save it into charVariable once
    // the data has been received
    byte packetResults = StreamSend::receiveObject(Serial, &charVariable, sizeof(charVariable));

    // Reconstruct the char coming from the Serial into charVariable that has a custom
    // suffix of a and a prefix of z
    byte packetResults = StreamSend::receiveObject(Serial, &charVariable, sizeof(charVariable), 'a', 'z');

**Receiving an int that was sent via StreamSend:**

    int intVariable; // Define the variable on where the data will be put

    // Reconstruct the int from xbeeSerial into the variable intVariable
    byte packetResults = StreamSend::receiveObject(xbeeSerial, &intVariable, sizeof(intVariable));

    // Reconstruct the data into intVariable that was send with a custom prefix
    // of j and a suffix of p
    byte packetResults = StreamSend::receiveObject(xbeeSerial, &intVariable, sizeof(intVariable), 'j', 'p');

**Receiving a Struct that was sent via StreamSend:**

    // Define the struct that the data will be put
    struct SIMPLE_STRUCT {
      char charVariable;
      int intVariable[7];
      boolean boolVariable;
    };
    SIMPLE_STRUCT simpleStruct; // Create a struct to store the data in

    // Reconstruct the data from xbeeSerial into the object simpleStruct
    byte packetResults = StreamSend::receiveObject(xbeeSerial, &simpleStruct, sizeof(simpleStruct));

    // Reconstruct the data from xbeeSerial into the object simplestruct that has
    // a prefix of 3 and a suffix of p
    byte packetResults = StreamSend::receiveObject(xbeeSerial, &simpleStruct, sizeof(simpleStruct), '3', 'p');

Once you read the data using `StreamSend::receiveObject()` you need to know if the data was GOOD, Not Found, or BAD.

**Good** = Successful

**Not Found** = No prefix character was found in the specified ostream

**Bad** = Somehow there was a prefix character found, but the data isn't intact. Usually it means there was no suffix character found or the data wasn't the correct size.

**Testing Validity of Data:**

    // Once you call StreamSend::receiveObject() it returns a byte of the status of
    // how things went. If you run that though some of the testing functions it'll
    // let you know how the transaction went
    if(StreamSend::isPacketGood(packetResults)) {
      //The Packet was Good
    } else {
      //The Packet was Bad
    }

    if(StreamSend::isPacketCorrupt(packetResults)) {
      //The Packet was Corrupt
    } else {
      //The Packet wasn't found or it was Good
    }

    if(StreamSend::isPacketNotFound(packetResults)) {
      //The Packet was not found after Max # of Tries
    } else {
      //The Packet was Found, but can be corrupt
    }

**SteamSend Class:**

    #include "Arduino.h"

    #ifndef STREAMSEND_H
    #define STREAMSEND_H

    #define PACKET_NOT_FOUND 0
    #define BAD_PACKET 1
    #define GOOD_PACKET 2

    // Set the Max size of the Serial Buffer or the amount of data you want to send+2
    // You need to add 2 to allow the prefix and suffix character space to send.
    #define MAX_SIZE 64

    class StreamSend {
      private:
        static int getWrapperSize() { return sizeof(char)*2; }
        static byte receiveObject(Stream &ostream, void* ptr, unsigned int objSize, unsigned int loopSize);
        static byte receiveObject(Stream &ostream, void* ptr, unsigned int objSize, unsigned int loopSize, char prefixChar, char suffixChar);
        static char _prefixChar; // Default value is s
        static char _suffixChar; // Default value is e
        static int _maxLoopsToWait;

      public:
        static void sendObject(Stream &ostream, void* ptr, unsigned int objSize);
        static void sendObject(Stream &ostream, void* ptr, unsigned int objSize, char prefixChar, char suffixChar);
        static byte receiveObject(Stream &ostream, void* ptr, unsigned int objSize);
        static byte receiveObject(Stream &ostream, void* ptr, unsigned int objSize, char prefixChar, char suffixChar);
        static boolean isPacketNotFound(const byte packetStatus);
        static boolean isPacketCorrupt(const byte packetStatus);
        static boolean isPacketGood(const byte packetStatus);

        static void setPrefixChar(const char value) { _prefixChar = value; }
        static void setSuffixChar(const char value) { _suffixChar = value; }
        static void setMaxLoopsToWait(const int value) { _maxLoopsToWait = value; }
        static const char getPrefixChar() { return _prefixChar; }
        static const char getSuffixChar() { return _suffixChar; }
        static const int getMaxLoopsToWait() { return _maxLoopsToWait; }

    };

    //Preset Some Default Variables
    //Can be modified when seen fit
    char StreamSend::_prefixChar = 's';   // Starting Character before sending any data across the Serial
    char StreamSend::_suffixChar = 'e';   // Ending character after all the data is sent
    int StreamSend::_maxLoopsToWait = -1; //Set to -1 for size of current Object and wrapper

    /**
      * sendObject
      *
      * Converts the Object to bytes and sends it to the stream
      *
      * @param Stream to send data to
      * @param ptr to struct to fill
      * @param size of struct
      * @param character to send before the data stream (optional)
      * @param character to send after the data stream (optional)
      */
    void StreamSend::sendObject(Stream &ostream, void* ptr, unsigned int objSize) {
      sendObject(ostream, ptr, objSize, _prefixChar, _suffixChar);
    }

    void StreamSend::sendObject(Stream &ostream, void* ptr, unsigned int objSize, char prefixChar, char suffixChar) {
      if(MAX_SIZE >= objSize+getWrapperSize()) { //make sure the object isn't too large
        byte * b = (byte *) ptr; // Create a ptr array of the bytes to send
        ostream.write((byte)prefixChar); // Write the suffix character to signify the start of a stream

        // Loop through all the bytes being send and write them to the stream
        for(unsigned int i = 0; i<objSize; i++) {
          ostream.write(b[i]); // Write each byte to the stream
        }
        ostream.write((byte)suffixChar); // Write the prefix character to signify the end of a stream
      }
    }

    /**
      * receiveObject
      *
      * Gets the data from the stream and stores to supplied object
      *
      * @param Stream to read data from
      * @param ptr to struct to fill
      * @param size of struct
      * @param character to send before the data stream (optional)
      * @param character to send after the data stream (optional)
      */
    byte StreamSend::receiveObject(Stream &ostream, void* ptr, unsigned int objSize) {
        return receiveObject(ostream, ptr, objSize, _prefixChar, _suffixChar);
    }
    byte StreamSend::receiveObject(Stream &ostream, void* ptr, unsigned int objSize, char prefixChar, char suffixChar) {
      return receiveObject(ostream, ptr, objSize, 0, prefixChar, suffixChar);
    }

    byte StreamSend::receiveObject(Stream &ostream, void* ptr, unsigned int objSize, unsigned int loopSize, char prefixChar, char suffixChar) {
      int maxLoops = (_maxLoopsToWait == -1) ? (objSize+getWrapperSize()) : _maxLoopsToWait;
      if(loopSize >= maxLoops) {
       return PACKET_NOT_FOUND;
      }
      if(ostream.available() >= (objSize+getWrapperSize())) { // Packet meets minimum size requirement
       if(ostream.read() != (byte)prefixChar) {
         // Prefix character is not found
         // Loop through the code again reading the next char
         return receiveObject(ostream, ptr, objSize, loopSize+1, prefixChar, suffixChar);
       }

       char data[objSize]; //Create a tmp char array of the data from Stream
       ostream.readBytes(data, objSize); //Read the # of bytes
       memcpy(ptr, data, objSize); //Copy the bytes into the struct

       if(ostream.read() != (byte)suffixChar) {
         //Suffix character is not found
         return BAD_PACKET;
       }
       return GOOD_PACKET;
      }
      return PACKET_NOT_FOUND; //Prefix character wasn't found so no packet detected
    }

    boolean StreamSend::isPacketNotFound(const byte packetStatus) {
     return (packetStatus == PACKET_NOT_FOUND);
    }

    boolean StreamSend::isPacketCorrupt(const byte packetStatus) {
     return (packetStatus == BAD_PACKET);
    }

    boolean StreamSend::isPacketGood(const byte packetStatus) {
     return (packetStatus == GOOD_PACKET);
    }

    #endif

  [1]: http://paste.strictfp.com/39940


body: If you really wanted to send it _fast_, i recommend Full Duplex Serial (FDX). It's the same protocol that USB and ethernet use, and it's a lot faster than UART. The downside is that it usually requires external hardware to facilitate the high data rates. I've heard that the new [softwareSreial](http://arduiniana.org/libraries/NewSoftSerial/) supports FDX, but this may be slower even than hardware UART. For more on communication protocols, see https://arduino.stackexchange.com/questions/182/how-to-connect-two-arduino-without-shields


body:
I have no official credentials here, but in my experience things have gone pretty efficiently when I pick a certain character position(s) to contain the state of a variable, so that you might designate the first three characters as the temperature, and the next three as the angle of a servo, and so on. On the sending end I would save the variables individually and then combine them in a string to send serially. On the receiving end I would have the string picked apart, getting the first three characters and turning them into whatever variable type i need, then doing so again to get the next variable value.
This system works best when you know for certain the amount of characters each variable will take up, and you always look for the same variables (which I hope is a given) each time the serial data loops through.

You can pick one variable to put last of indeterminate length and then get that variable from it's first character to the end of the string. Granted, the serial data string could get really long depending on the variable types and the sheer amount of them, but this is the system I use and so far the only setback I've hit is the serial length, so that's the only disadvantage I know of.


body:
Sending a structure is fairly simple.

You can declare the structure as you normally would, and then use memcpy(@myStruct,@myArray) to copy the data to a new location, and then use something similar to the below code to write the data as a datastream.

    unsigned char myArraySender[##];   //make ## large enough to fit struct
    memcpy(&myStruct,&myArraySender);  //copy raw data from struct to the temp array
    digitalWrite(frameStartPin,High);  //indicate to receiver that data is coming
    serial.write(sizeof myStruct);     //tell receiver how many bytes to rx
    Serial.write(&myArraySender,sizeof myStruct);   //write bytes
    digitalWrite)frameStartPin,Low);   //done indicating transmission

Then you can attach an interrupt routine to the pin on the other device that does the following:

    volatile unsigned char len, tempBuff[##];
    //volatile because the interrupt will not happen at predictable intervals.

    attachInterrupt(0,readSerial,Rising);
//tell the mcu to call fxn when pinhigh. This will happen during virtually any moment. if that is not desired, remove the interrupt and simply watch for new characters in your main executive loop (aka, UART polling).

    void readSerial(unsigned char *myArrayReceiver){
        unsigned char tempbuff[sizeof myArrayReceiver];
        while (i<(sizeof myArrayReceiver)) tempBuff[i]=Serial.read();
        memcpy(&tempbuff,&myArrayReceiver);
        Serial.flush();
    }

Syntax and use of pointers will need some review. I pulled an all-nighter so I'm sure the above code won't even compile, but the idea is there. Fill your structure, copy it, use out-of-band signalling to avoid framing errors, write the data. On the other end, receive the data, copy it to a struct, and then the data becomes accessible via normal member access methods.

The use of bitfields will also work, just be aware that the nibbles will appear to be backwards. For instance, attempting to write 0011 1101, may result in 1101 0011 appearing at the other end if the machines differ in byte order.

If data integrity is important, you can also add a checksum to make sure you aren't copying misaligned garbage data. This is quick and effective check that I recommend.


body:
If you can tolerate the data volume, debugging communicatons is **so** much easier when sending strings than when sending binary; sprintf()/sscanf() and their variants are your friends here. Enclose the communication in dedicated functions in their own module (.cpp file); if you need to optimize the channel later - **after** you have a working system - you can replace the string-based module with one coded for smaller messages.

You'll make your life lots easier if you hold tight to protocol specs on transmission and interpret them more loosely on reception, regard to field widths, delimiters, line endings, insignificant zeros, presence of `+` signs, etc.


body:
Send struct data across serial
-------------------------------
Nothing fancy. Sends a struct. It uses an escape character '^' to delimit the data.

Arduino code
------------

    typedef struct {
     float ax1;
     float ay1;
     float az1;
     float gx1;
     float gy1;
     float gz1;
     float ax2;
     float ay2;
     float az2;
     float gx2;
     float gy2;
     float gz2;

    } __attribute__((__packed__))data_packet_t;

    data_packet_t dp;

    template <typename T> void sendData(T data)
    {
     unsigned long uBufSize = sizeof(data);
     char pBuffer[uBufSize];

     memcpy(pBuffer, &dp, uBufSize);
     Serial.write('^');
     for(int i = 0; i<uBufSize;i++) {
       if(pBuffer[i] == '^')
       {
        Serial.write('^');
        }
       Serial.write(pBuffer[i]);
     }
    }
    void setup() {
      Serial.begin(57600);
    }
    void loop(){
    dp.ax1 = 0.03; // Note that I didn't fill in the others. Too much work. ;p
    sendData<data_packet_t>(dp);
    }

Python Code:
------------

    import serial
    from  copy import copy
    from struct import *

    ser = serial.Serial(
    #   port='/dev/cu.usbmodem1412',
      port='/dev/ttyUSB0',
    #     port='/dev/cu.usbserial-AL034MCJ',
        baudrate=57600
    )

    def get_next_data_block(next_f):
        if not hasattr(get_next_data_block, "data_block"):
            get_next_data_block.data_block = []
        while (1):
            try:
                current_item = next_f()
                if current_item == '^':
                    next_item = next_f()
                    if next_item == '^':
                        get_next_data_block.data_block.append(next_item)
                    else:
                        out = copy(get_next_data_block.data_block)
                        get_next_data_block.data_block = []
                        get_next_data_block.data_block.append(next_item)
                        return out
                else:
                    get_next_data_block.data_block.append(current_item)
            except :
                break

    for i in range(1000): # just so that the program ends - could be in a while loop
        data_ =  get_next_data_block(ser.read)
        try:
            print unpack('=ffffffffffff', ''.join(data_))
        except:
            continue


message:
What happens to the Arduino if you don't use a resistor with an LED?

Making a blinking light seems to be one of the most common beginner projects with Arduino. A typical approach is to connect an LED + resistor (in series) to an IO pin, and connect the other end to ground. In code, you make the pin an output, and bring it `HIGH` and `LOW` repeatedly to flash the LED.

What happens if you leave that resistor out? Obviously you're going to wreck the LED, but will it also damage the Arduino in some way?

body:
From page 411 of the [ATmega328P data sheet][1], we have a graph of the output current vs voltage.

![Output current graph][2]

We can see over the the 20mA range of output currents, we drop ~0.5V, giving an approximate internal resistance of 25Ω.

A typical LED has a forward voltage of about 2V. Therefore, we end up in the situation where we will drop 3V over the 25Ω internal resistance of the ATmega328P, giving an output current of 120mA.

I = (5-2)V / 25Ω = 120mA

This is a simplification, but this 120mA is far larger than the recommended maximum current per pin of 40mA of the microcontroller, and far in excess of what a normal LED should take.

That said, most LEDs and the ATmega328P seem to survive this kind of abuse, especially for short periods. In general, if the pin continues to work after this is done, it should be fine.

  [1]: http://www.atmel.com/Images/doc8161.pdf
  [2]: https://i.stack.imgur.com/w5V5U.png


body:
Leaving series resistors out will definitely greatly (exponentially) shorten lifetime of both the controller and the LED. Absolute maximum ratings for most AVRs are (a.o.):

- max. 40mA per GPIO pin
- max. 200mA per package.

A new Arduino sets you back $20 or more, a fist full 220 ohm resistors sets you back 1$. When treated within spec, an Arduino (and LEDs for that matter) can survive a lifetime.


body:
I have done this once (being a beginner concerning electronics). The LED died, luckily the Arduino survived (without any pin problems).

Wouldn't recommend this as it is not good for the Arduino.


message:
Why do some pins have a different PWM frequency?

According to the [Arduino reference for `analogWrite()`][1], the PWM frequency on most pins is ~490 Hz. However, it's ~980 Hz for pins 5 and 6 on the Uno, and for pins 3 and 11 on the Leonardo.

Why are these different? Is it a deliberate design feature, or is it somehow dictated by the hardware?

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

body:
I am not aware of the design considerations, but if you check the datasheet for the microcontroller on your Arduino, you will notice that PWM pins are grouped together and per group connected to a timer. The speed at which this timer is increased varies by the configured prescaler. If you change the prescaler for a certain timer, you change the PWM frequency for the related PWM pins. I believe some timers double for other purposes like the `millis();` function. If you change the prescaler for that timer, values returned by `millis()` will be off by the same factor.

You can calculate the setting for the prescaler as follows:

$$\text{prescaler} = \dfrac{f_{CPU}}{PWMresolution × f_{PWM}} = \dfrac{16\text{MHz}}{256×490} \approx 128$$

> prescaler = f[CPU]/(PWMresolution×f[PWM]) = 16000000/(256×490) = approx 128.

Check the datasheet and you'll find that 128 is indeed one of the prescaler values you can select.


body:
Those aren't the only frequencies available for the PWM signals. However, they are the frequencies as determined by the applied prescaler (which you can readily change as detailed below).

Each of the 3 pairs of PWM pins is tied to one timer, each of which has its own base frequency, as follows:

* Pins 5 and 6 are paired on timer0, with base frequency of 62500Hz
* Pins 9 and 10 are paired on timer1, with base frequency of 31250Hz
* Pins 3 and 11 are paired on timer2, with base frequency of 31250Hz

Then each set of pins have a number of prescaler values that can be chosen, that will divide the base frequency of that pair of pins. The prescaler values available are:

* Pins 5 and 6 have prescaler values of 1, 8, 64, 256, and 1024
* Pins 9 and 10 have prescaler values of 1, 8, 64, 256, and 1024
* Pins 3 and 11 have prescaler values of 1, 8, 32, 64, 128, 256, and 1024

The different combinations yield different frequencies in a given PWM pin. Notice that timer 2 (tied to pins 3 and 11) have more prescaler values available, resulting in more frequencies available.

Now, why timer 2 is different, that's a separate question.

Edit: Here's a list of possible PWM frequencies per pin (from [this article](http://arduino-info.wikispaces.com/Arduino-PWM-Frequency)):

> For pins 6 and 5 (OC0A and OC0B):

> * If TCCR0B = xxxxx001, frequency is 64kHz
> * If TCCR0B = xxxxx010, frequency is 8 kHz
> * If TCCR0B = xxxxx011, frequency is 1kHz (this is the default from the Diecimila bootloader)
> * If TCCR0B = xxxxx100, frequency is 250Hz
> * If TCCR0B = xxxxx101, frequency is 62.5 Hz

> For pins 9, 10, 11 and 3 (OC1A, OC1B, OC2A, OC2B):

> * If TCCRnB = xxxxx001, frequency is 32kHz
> * If TCCRnB = xxxxx010, frequency is 4 kHz
> * If TCCRnB = xxxxx011, frequency is 500Hz (this is the default from the Diecimila bootloader)
> * If TCCRnB = xxxxx100, frequency is 125Hz
> * If TCCRnB = xxxxx101, frequency is 31.25 Hz

`TCCRnB` is where you set the prescaler bits for timer `n`, replacing `n` by 0, 1 or 2, depending on the timer you want to set. If you are still unsure about bitwise operations, read this [bit math tutorial](http://playground.arduino.cc/Code/BitMath).

My sources:

* http://playground.arduino.cc/Code/PwmFrequency
* http://arduino.cc/en/Tutorial/SecretsOfArduinoPWM
* http://arduino.cc/en/Tutorial/PWM
* http://arduino-info.wikispaces.com/Arduino-PWM-Frequency

Note that there seems to be divergence in those sources about whether pins 9 and 10 have the same behavior as 5 and 6 or 3 and 11, but you get the idea anyway. I'm reading the datashet to try and figure out which is correct, or whether this is a difference between boards.


message:
I got a missignatured ATmega328-PU. How can I fix that?

Sometime in the past, I was burning bootloaders on a fresh batch of four **ATmega328-PU** using the Arduino IDE (notice there's no **P** after 328 - it's the slightly cheaper non-picopower version of the MCU, not to be confused with the **ATmega328P-PU** with a **P**), and was surprised with the following message from avrdude:

    avrdude: Device signature = 0x1e950F
    avrdude: Expected signature for ATMEGA328 is 1E 95 14
    Double check chip, or use -F to override this check.

That means avrdude thought the chip was not what its label said. Then I changed the chip type on my Arduino IDE to **ATmega328P-PU** and avrdude burned the bootloader without complaints. What that means is that the chip was labelled as one MCU and internally it responded as another, slightly different.

What I would like to know is:

- <s>How rare is this event? Has anyone had a similar experience?</s> (*Original question, off-topic*)

- Is it possible to fix this? How can I fix the signature so that avrdude recognize the chip correctly?

This is a [cross-post from EE.SE][1]. I posted this question there but didn't attract much attention, so I wanted to see if anyone from our community had a similar experience.

  [1]: https://electronics.stackexchange.com/questions/90692/mislabelled-atmega328-pu

body:
While browsing sparkfun, i have found several news posts that show their struggle with mislabeled chips. Here are a few:

* https://www.sparkfun.com/news/350
* https://www.sparkfun.com/news/384
* https://www.sparkfun.com/news/364

Sparkfun had received a questionable shipment if ICs from a new seller in china. They decided to test them before sending them into production, and none of their test boards worked. Using nitric acid, they were able to remove the case of the ICs and fould a hunk of metal that looked like copper.

In another article, they dissected some suspicious ICs from Atmel, and found an ON semiconductor silicon wafer inside. The chips were not functional ATmegas, but they did have silicon, unlike the other ones.


body:
Not the preferred way to fix things and certainly not the first solution to consider, but you can consider programming the signature bytes. Before attempting this be absolutely sure you really want to do this and you have investigated what is involved to undo this. This may involve changing configuration files on your computer ...

Anyways the way to set the controller's signature bytes is as follows (untested, I don't have a spare AVR lying around):

    avrdude -p atmega328 -c arduino -P /dev/ttyUSB003 -b 19200 -v -U signature:w:0x1E,0x95,0x14:m


body:
There are several different flavors of ATMega328. The most commonly found in Arduinos Uno (et al) is the ATMega328P, which is Atmel's "picopower" version; this one has the 0x1E950F signature that AVRDude expects when it's tasked with programming an Arduino Uno. Gee, figure that.

Less common is the base model ATMega328 (no suffix) and the ATMega328PU, both of which yield a 0x1e9514 signature instead of the expected 0x1E950F.

As to commonality... that depends upon the crowd with which you run. If you are Arduino through-and-through, never use any boards that aren't teal-colored, then it's extremely uncommon for you to find a non-ATMega328P. If, on the other hand, you run in my gang and build all manner of cool stuff on funny-colored boards that don't have staggered header pin spacing in one spot... then it's very common to get non-p '328s.

There are workarounds. There was for a while a variant ArduinoISP_Multi that would translate a 0x1e9514 signature to a 0x1E950F signature, permitting you to gleefully program your breadboarded or otherwise non-teal '328 boards exactly as if they were genuine Arduino Unos. For whatever reason that "sketch" can no longer be found.

You can also edit avrdude.conf (with backup, please!) such that it (AVRDude) expects the signature that your '328 coughs up. The backup is particularly important because you may want someday to program "real teal". The avrdude.conf file can be found in your Arduino installation at ...\hardware\tools\avr\etc.

OR... wait! There's MORE! All for one money! You can also write your own hardware profile for non-P '328s and put it in your Arduino "sketchbook"'s hardware directory, then draw from that as a custom board definition. Aw, shucks... it ain't that hard! Really! I've written several of those for my own board designs.