body: I was instructed to "burn the bootloader" to my Arduino to fix an error I was getting. How can I do this? (And what exactly is the bootloader?)

title: How do I burn the bootloader?

Answers: 2

body:
The bootloader is a small program that is (almost) always on an Arduino. It manages uploading and starting the sketches you make, and blinks the pin 13 LED whenever the board resets.

----------

To burn the bootloader:

 1. Obtain an AVR ISP, [USBtinyISP][2], [ParallelProgrammer][3], or similar; or use [another Arduino board][4]. This will be your ISP.
 2. Unless otherwise instructed, connect the ISP to the ICSP pins on your board.
 3. Power your board with either a USB cable or an external power supply.
 4. Open up the Arduino IDE.
 5. Make sure you selected the correct board that you are burning to at `Tools ► Board ►` in the IDE. Double-check this even if you could upload programs correctly; uploading doesn't always require the right board.
 6. Select the appropriate programmer at `Tools ► Programmer ►`.
 7. Click `Tools ► Burn Bootloader`, and wait. It shouldn't take more than a minute, and often takes only a few seconds.

----------

Sources:

 - http://arduino.cc/en/Hacking/Bootloader
 - http://arduino.cc/en/Guide/Environment

  [1]: http://www.atmel.com/tools/MATUREAVRISP.aspx
  [2]: http://learn.adafruit.com/usbtinyisp
  [3]: http://arduino.cc/en/Hacking/ParallelProgrammer
  [4]: http://arduino.cc/en/Tutorial/ArduinoISP

body:
### What is a bootloader?

> And what exactly is the bootloader?

The bootloader is a small piece of code residing in the "high" part of program memory. Normally it is not erased when you upload new sketches. Its purpose it to be activated immediately after a reset (the fuses are configured to commence code at the bootloader address rather than address 0x0000). The bootloader will wait a short time (such as one second) to see if "programming" data is arriving on the serial port.

* If so, it reads that data, and decodes it to reprogram the rest of the flash memory. Working in conjunction with the uploading program (normally avrdude) the new sketch is sent via the serial port. The bootloader erases pages of flash memory, and replaces them with the new code. Once done, it executes the new code.

* If no instructions arrive, the bootloader jumps to address 0x0000 to execute the existing sketch on the board.

---

### How to replace the bootloader

An alternative method to program a bootloader is to use a sketch I wrote a while ago which runs on a:

* Uno (or similar, such as Duemilanove)
* Leonardo
* Mega2560

The "programming" board runs the sketch which has bootloaders for a number of boards hard-coded into it. You connect the programming board to the target board (the board wanting the bootloader) with 6 hook-up wires as shown.

![Bootloader programmer for Uno][1]

That particular photo illustrates one Uno programming another one.

You run the sketch (operating via the Serial Monitor to give it commands). First it identifies the target chip:

    Atmega chip programmer.
    Written by Nick Gammon.
    Entered programming mode OK.
    Signature = 0x1E 0x95 0x0F
    Processor = ATmega328P
    Flash memory size = 32768 bytes.
    LFuse = 0xFF
    HFuse = 0xDE
    EFuse = 0xFD
    Lock byte = 0xCF
    Bootloader address = 0x7E00
    Bootloader length = 512 bytes.
    Type 'L' to use Lilypad (8 MHz) loader, or 'U' for Uno (16 MHz) loader ...
    Type 'G' to program the chip with the bootloader ...

The you  press **G** to program it.

    Erasing chip ...
    Writing bootloader ...
    Committing page starting at 0x7E00
    Committing page starting at 0x7E80
    Committing page starting at 0x7F00
    Committing page starting at 0x7F80
    Written.
    Verifying ...
    No errors found.
    Writing fuses ...
    LFuse = 0xFF
    HFuse = 0xDE
    EFuse = 0xFD
    Lock byte = 0xCF
    Done.
    Type 'C' when ready to continue with another chip ...

For a Uno this takes one second. To program a Mega2560 takes 3 seconds.

Detailed instructions at [Atmega bootloader programmer](http://www.gammon.com.au/bootloader)

Code can be downloaded from [Github: nickgammon/arduino_sketches
](https://github.com/nickgammon/arduino_sketches)

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


body: Though an emulator is quite useful for debugging code that has no side effects, most real-world applications include some circuitry besides the Arduino. If a microcontroller on an Arduino had a JTAG interface, it would be pretty straight-forward, but what if it's e.g. an Arduino Uno?

title: How do I debug on-chip with Arduino?

Answers: 2

body:
The Arduino Uno uses the Atmel Atmega328p microcontroller, which only has one debug option, DebugWire.  There are a few tools that can work with it, but the least expensive and most commonly available is the [AVR Dragon][1].

You can use AVR Studio 6 for this.  You can use the `.elf` file file produced during the Arduino build process directly, but setting up the debugger is a little easier if you port the Arduino program to the AVR Studio.  It's not difficult, but there are a lot of little pieces to deal with.  There are guides online to help you through this.

  [1]: http://www.atmel.com/tools/AVRDRAGON.aspx

body:
This might not be right for you, but the [Visual Micro][1] plugin for Atmel Studio and Visual Studio has a [USB debugger][2] which only uses Arduino code.

In the background the debugger uses Serial which might affect some time-sensitive applications.

![Enter image description here][3]

  [1]: http://www.visualmicro.com/
  [2]: http://www.visualmicro.com/page/Debugging-for-Arduino.aspx
  [3]: https://i.stack.imgur.com/6Mqkn.png


body:
Is it possible to build a HID device (like a keyboard) using an Arduino uno?

At the time being, I have button inputs on the Arduino giving outputs on the serial line. So, how can I transform my current firmware into something that can behave like a HID keyboard?

 - Shall I write a new window device driver?
 - Shall I create a software layer that could take my serial data and have windows read it as HID input?
 - Is there any better way to achieve this, if it is possible at all?

title: Arduino as USB HID

Answers: 2

body:
> Is it possible to build a HID device (like a keyboard) using an Arduino uno?

yes it is! And there's a great tutorial on how to do that over [here][1]

> At the time being, I have button inputs on the Arduino giving outputs on the
> serial line. So, how can I transform my current firmware into something that
> can behave like a HID keyboard?

As the tutorial shows you, you need to transform your firmware code so instead of
printing the events, you actually trigger events. What you need to do, is add to your
code:

    void triggerKey(uint8_t mod, uint8_t chr) {
        uint8_t buf[8] = {mod, chr, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
        // press key
        Serial.write(buf, 8);
        // emulate key press delay
        delay(10);
        buf[1] = 0x00;
        // release key
        Serial.write(buf, 8);
    }

What you're doing here, is send from your main Arduino microcontroller events over
the serial line to the smaller microcontroller that handles USB communication. That
microcontroller will take those key "buffers" and transfer them as USB HID Keyboard
key presses over USB.

Beware that the key character (`chr` in the code here), is actually a keycode sent
over USB that gets interpreted by your USB HID driver, which then translates it into
a real character using the current layout you've setup for your keyboard.

The `mod` character is one of the modifier keys you have on the keyboard (shift,
control, alt...), `0x00` being no modifier.

>  - Shall I write a new window device driver?

No, you don't need! With the DFU upgrade, your arduino will be seen as a USB keyboard
by windows.

>  - Shall I create a software layer that could take my serial data and have windows read it as HID input?

You neither need to do that, and it's actually a very bad idea for many reasons:

 - your solution would not be portable, and thus you'd need to hack something for every platform you may use,
 - your solution would imply a lot of new code ; the more code one write, the more bugs is likely to be in your system,
 - your solution would be really hackish, as it would behave as a device driver (i.e. *kernel land*) taking input from
   a user program (i.e. *user land*) and is likely to not work, be a hell to debug, and prone for security issues...
   If that's even possible to do!

> I'm using an Uno, but I'll look at what you posted because last time we considered the DFU update but we're kinda scared of bricking stuff

Finally you're having concerns, in a comment, about bricking your arduino. Please
believe me and the author of the [article][1] that you **cannot** brick your arduino
doing a firmware flash:

*NOTE: There is no chance of ‘bricking’ the device using this method. The Arduino bootloader firmware can always be updated using the DFU protocol!*

In case something gets really badly wrong, and you get a bootloader corruption in the
little AVR (atmega8u2), you still can reflash it [using another arduino][2] or an
[atmel programmer][3] using the 6 pins next to the USB plug.

In the end, know that the **only** way to brick an AVR, thus an Arduino as well, is
to play with the fuses and reset the programming fuses. And even then, you may use
[HVSP][4] to save your device, though it's often less trouble to just take a new chip.

[1]:http://mitchtech.net/arduino-usb-hid-keyboard
[2]:http://arduino.cc/en/Tutorial/ArduinoISP
[3]:http://www.atmel.com/tools/avrispmkii.aspx
[4]:http://microtherion.github.io/ScratchMonkey/HVSP.html

body: I created a project that fully replaces the Arduino Bootloader. You are able to upload sketches and use it as HID. See Project HID on Github: https://github.com/NicoHood/HID


body:
I'm creating a weather station / environmental datalogger and am saving my data to a SD card Breakout. The SD card works fine but I would like to name the files I am saving on it after the date when the readings were taken.I've tryed multiple things but I can't work out how to combine the date from my RTC and put them in a file name. I've tryed this:

    dataFile = SD.open(String(now.day()) + "-" + String(now.month()) + "-" + String(now.year()) + ".csv",FILE_WRITE);
But this gives me an error -

    char dateName[13] = {String(now.day()) + "-" + String(now.month()) + "-" + String(now.year()) + ".csv"};
    dataFile = SD.open(dateName,FILE_WRITE);

But this gives me this error:

     cannot convert 'StringSumHelper' to 'char' in initialization

Help! How do I do this?

title: Combining Strings into a datestamp

Answers: 5

body:
*EDIT: As noted by Klaus Warzecha, the SD library may only support 8.3 format filenames (i.e. 8 characters for the name, 3 characters for the extension). The solution may in fact be to ensure that the years is only 2 digits, resulting in names like: `20-12-14.csv`*

---

From what I can see in the SD library code, the `open()` method isn't designed to accept a `String` object as a parameter. It only wants a plain old [C-style string][1] (which means a `char` array). That explains why your first example doesn't work -- it's trying to pass a `String` object.

The second example unfortunately is invalid C++. You simply can't initialise an array like that. What you want to do instead is to build the `String` object, then extract the characters out using `String::toCharArray()`.

Something like this should work:

    String filename = String(now.day()) + "-" + String(now.month()) + "-" + String(now.year()) + ".csv";
    char str[16] = {0};
    filename.toCharArray(str, 16);
    dataFile = SD.open(str, FILE_WRITE);

I'm not sure what your `now.year()` returns; i.e. if that's a 2 digit or 4 digit year. I've assumed 4 digits, so I've made the `char` array big enough for 15 characters in total, plus an extra null terminator (which is essential for C-style strings).

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

body:
In your second case, you need to break the initialization into two lines and use [toCharArray()][1] as shown:

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

    char dateName[13];
    String(String(now.day()) + "-" + String(now.month()) + "-" + String(now.year()) + ".csv").toCharArray(dateName, 13);

Then, you can move ahead with opening the file.

The problem you are seeing is quite literally what the error message says. An initialization of a character array requires a character array. It cannot be initialised with a string object.

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

body:
Is this based on the [SDFat][1] library?

Then you have to live with short 8.3 filenames for the moment.

[1]:http://code.google.com/p/sdfatlib/

body:
  //////////////////////////////////////////////////////////////

    String filename = String(now.month()) + "-" + String(now.year()) + ".csv";

    char str[16] = {0};

    filename.toCharArray(str, 16);

    File dataFile = SD.open(str, FILE_WRITE);

//////////////////////////////////////////////////////////////

body:
Well:

      char buffer[15];
      snprintf(buffer, sizeof(buffer), "d-d-d.csv", now.day(), now.month(), now.year());

After `snprintf` call, `buffer` contains the name of the file.

This solution use constant fixed space in RAM (just 15 bytes for buffer), while all others solutions demands tons of RAM for creating multiple String objects.

And it's faster, because it only do the format part, minus all creations, conversions, and deletion using String.

Finally, generated names are always the same length, from 1-1-2018 thru 31-12-2018.

Don't use String with Arduino.


body:
I have an espresso machine that gets its water from one of those 5 gallon blue water bottles (I would plumb it, but our water here is WAAAAY too hard).

If I ever accidentally let the bottle run out of water, the rotary pump in the espresso machine will be ruined, which would be a costly mistake.

I know that I can install some sort of magnetic float sensor inside the water bottle, but since I have to change it out once every few weeks, having another thing inside the bottle would make changing it out harder, and microbial contamination more likely.  The pump that pumps water out of the bottle forms a tight seal at the lid, and anything running under it or through it would compromise that seal.

Is there something I could use to detect if the water level is low from the outside of the bottle?  Like a laser sensor?

title: Best way to determine if a 5 gallon water jug is getting empty

Answers: 9

body:
I think you want a ["liquid level switch"][2], possibly also known as a "fluid switch" ... I realize this may not satisfy your requirements, but this is one way to solve the problem for >$10. I would probably hack something together that would put this sensor inline to the bottle. it's probably too hacky, but you could have a disc of plywood the same diameter as the water bottle, with a pipe fitting in the middle where you could mount the switch, so that the water bottle routes water through it so that when it runs low, it would trigger the switch before it runs to the pump.

![inline liquid level switch][1]

  [1]: https://i.stack.imgur.com/Y2s79.png
  [2]: http://www.mouser.com/ProductDetail/Hamlin/59630-1-T-02-A/?qs=sGAEpiMZZMun2xR%2b%2bFUzeBXr8YNXGDFf8m4HoboDx0M=

body: It seems to me that if you have pumped out 4.9 gallons you know the jug is close to empty. If an inline flow meter between the pump and the espessso maker is out due to water contact, then maybe you know that an espresso shot takes x amount of water, and once one has called for y shots (and calculated x times y) one is in the danger zone of running out of water?

body:
**Using a Force Sensor to Measure a Quantity of Water**

To satisfy your requirement of having the sensor on the exterior of the water container, I would recommend using a force sensor to weigh the bottle at set intervals. A force sensor, such as the FlexiForce A401, is a type of resistor that changes resistance in response to the amount of force applied. While not as accurate as a scale, it should provide enough accuracy (+-3% according to the [datasheet][1]) for the application described.

The basic procedure would be to hook up the force sensor to the Arduino and first measure the resistance with an empty bottle, then measure again with a full bottle. This will give you an idea of the force that your specific platform is actually applying to the sensor, and you can then fine tune the voltage (as per the datasheet) for your installation.

A basic tutorial using a similar force sensor with an Arduino can be found [here][2].

**Other Possibilities**

  - [Optical Liquid Level Sensors][3]
  - [Ultrasonic Level Monitoring][4]
  - Thermistors and Heating Coils at various levels to Measure the Thermal Mass (i.e. water) near the Sensor

  [1]: http://dlnmh9ip6v2uc.cloudfront.net/datasheets/Sensors/Pressure/A401-force-sensor.pdf
  [2]: http://bildr.org/2012/11/flexiforce-arduino/
  [3]: http://www.fluidswitch.com/pages/Optical-Liquid-Level-Sensors.htm
  [4]: http://www.cigrjournal.org/index.php/Ejounral/article/viewFile/2343/1823

body:
Another option is to measure the current going into the pump; when it runs dry, the current goes up, which generates the heat that fries the pump.

Or measure the temperature on the pump, but measuring the current will detect the beginning of the pump's meltdown, while the temperature may only detect the middle or end of the meltdown.  :-(

Or install a current limiter or breaker inline with the pump, just in case everything else fails.  :-)

body:
Honestly - you're overthinking this.

A dipstick or a float would be all you need.  Once the water level drops below your minimum, the float moves down with the water level and pulls a switch or allows a LDR to see through a hole.  Then do something like turn on a light.

Less is more.

body:
Whenever light follows a path that takes it from one material to the next, it makes a sharp turn. However, the angle of deviation is different based on the characteristics of the materials.

You can use this principle.

Set a LED on the level that you want to be your lowest. When the water is full, its light will follow a certain path across the container and reach its light sensor. When the water gets bellow the level, it will miss it (or you could set up a second sensor if you really wanted to).

Based on this info, you can know when the water gets too low. Just take appropriate action.

Watch out on the recommendation to measure the water used. This could be dangerous. You may have a leakage (either now or later) or somebody might tip the machine and spill some water. In either case your water level would be lower than the level you calculate, which would certainly result in your espresso machine be ruined.

body:
**Lasers**

If your blue water bottles are like mine, they are transparent.

Here's what I would try first:

I would get a cheap laser, and shine the light horizontally through the bottle.
I would aim the laser through a short [chord][1] -- not pointed directly through the middle of the bottle; perhaps 1/8 turn to the left of center.

        -------
    L../.......\..........S1
      /         \
     |     o     |        S2
      \         /
       \       /
        -------
    top-down view

When the bottle is empty, the laser beam will shoot pretty much straight through the bottle -- I would put one photo-sensor S1 there.

When the bottle is not quite empty, the laser beam will bend ([refract][2]) -- for redundancy, I would put another photo-sensor S2 there.

As long as the Arduino sees the laser hitting S2 alone, there's still some water in the bottle, at least up to the level of the laser -- turn on the green light.

Anything else -- light detecting only at S1, or nothing detected at either sensor, or light detected at both sensors (yes, it can happen) -- something doesn't seem right, better have the Arduino turn off the green light and turn on the red light.

I would start with [the simplest thing that could possibly work][3].
If I'm lucky, it might work.
If not, there's lots of little tricks involved in getting the light where you want it to go.
There's also lots of tricks for blocking sunlight, etc. from going where you don't want it to go.
Little black tubes, red plastic filters,
pulsing the laser at a few kHz,
collimating lenses,
lock-in amplifiers, etc.

There seem to be lots of tutorials that describe how to detect a laser using Arduino -- see

* ["Laser Harp"][4]
* ["Laser Timing Gate"][11]
* ["Arduino Laser Tripwire"][5]
* ["Arduino Forum: laser detection"][6]
* ["Arduino security with frickin’ laser"][7]
* ["Arduino self-calibrating laser trip wire"][8]
* ["The Arduino Controlled Laser Security System"][9]
* ["Raspberry Pi & Arduino: laser pointer communication"][10]
* etc.

(This would probably work just as well with a medium-power LED or "infrared LED" and some careful optical focusing and alignment. But -- lasers!)

  [1]: http://en.wikipedia.org/wiki/chord_(geometry)
  [2]: http://en.wikipedia.org/wiki/refraction
  [3]: http://www.artima.com/intv/simplestP.html
  [4]: http://www.radioshack.com/graphics/uc/rsk/Support/ProductManuals/Laser_Harp_Online_Instructions.pdf
  [5]: http://www.instructables.com/id/Arduino-Laser-Tripwire/
  [6]: http://forum.arduino.cc/index.php/topic,13046.0.html
  [7]: http://hackaday.com/2010/01/03/arduino-security-with-frickin-laser/
  [8]: http://keithkay.com/2013/03/03/arduino-self-calibrating-laser-trip-wire/
  [9]: http://makezine.com/projects/the-arduino-controlled-laser-security-system/
  [10]: http://pyevolve.sourceforge.net/wordpress/?p=2383
  [11]: https://www.manylabs.org/project/laserGate/

body:
you can use a metal detector like setup using the fact that electronic [permittivity][1] of water is different than that of air

have a coil with AC next to the bottle and an unpowered coil inside it

then by measuring the current and/or voltage generated by the second coil you can sense the difference between with water next to it and without

  [1]: http://en.wikipedia.org/wiki/Permitivity

body: Try a non contact water sensor: https://www.dfrobot.com/product-1493.html I use them and they work very well. You stick it on the outside of the jug, If it falls off the jug will show empty protecting your pump. The ones I use are similar and have an open collector, so no micro is required.  I think I paid about $6 a year or so ago. They make adjustable ones. Nice point nothing touches the water or can contaminate it.


body:
I am making an interface project that, when plugged into a computer, shows up as both usb flash storage and can type like a keyboard when some physical buttons on the board are pressed.

I have seen projects that do one or the other, but not both at the same time.

I have gotten it to work using a usb hub and two chips that are sharing the same storage (since I want the hot-key buttons to type out information stored in the flash drive side as well), with one acting like a HID and one acting as usb storage, but this has a few problems. First, it feels redundant. Second it's difficult to program since every time I plug the mess in it randomly assigns a name to each chip with no easy way of telling which to send the HID code to and with to send the USB Drive code to. I have to plug them in one at a time which wont work once this project is all on the same board. The last problem is the buttons work inconsistently since, im assuming, the two chips are not doing a nice job of sharing access to the text file it's trying to read for the text to 'type out' on the computer.

Is there a nicer way of doing this that uses one arduino acting in both roles accessing the one flash storage? Thanks!

title: Make an Arduino board act as both a usb storage device and a keyboard?

Answers: 3

body:
You're looking to create a USB composite device.  I don't see any examples within the arduino community, but I don't see a reason why you couldn't [use the 16u2 as a composite device][1], it'll just require more effort than you'd normally put into an arduino project.

  [1]: https://www.google.com/search?q=atmega 16u2 composite device

body:
The Leonardo can easily be used as a keyboard. There are also special codes to turn the USB-to-Serial chip on newe Unos into a keyboard (see [here](http://www.fourwalledcubicle.com/LUFA.php))

USB mass storage is another game all together. The [Brondani EasyUSB](https://www.sparkfun.com/products/10155) is a simple chip that exposes 2MB of storage space on both the USB and microcontroller. They say they will be releasing larger capacities.

The easyUSB also has a serial link built into it from uC to computer.

If you really want, you can make your own USB stack to handle this on you own, but the pitifully small amount of ram on these chips would prohibit it.

body: You can try using an Arduino Mega ADK. This is because it has a separate USB port for USB devices along with many serial ports for other serial device.


body:
I'm trying to parse many variables into a URL so that I can update a website through a simple HTTP API with sensor data. After talking to a buddy of mine, he suggested going with the code below.

When I put this in, the Arduino Yun boots up. I see the L13 red LED turn on, but then it hoses. When I comment out the `sprintf();` line, everything works fine — except no URL is parsed.

I've tried to debug to the best of my ability and am looking for thoughts on what may be happening.

I'm not sure how much code to post without posting the whole 130 line sketch, so I'm just dumping the parts from the `loop` that is trying to piece together the URL.

      // Get update time
      Process date;
      date.runShellCommand("date --utc \"+%Y-%m-%d% %H:%M:%S\"");
      String utcDateString = "";
      while (date.available()) {
        char d = date.read();
        utcDateString += d;
      }

          char url[512];
          url[0]='\0';
          float humid, baro, windspeed, raingauge;
          int winddir;
          Serial.print("humid: ");
          Serial.println(humid);
            Serial.print("baro: ");
          Serial.println(baro);
            Serial.print("windspeed: ");
          Serial.println(windspeed);
            Serial.print("raingauge: ");
          Serial.println(raingauge);
            Serial.print("winddir: ");
          Serial.println(winddir);
     //sprintf(url,"http://weatherstation.wunderground.com/weatherstation/updateweatherstation.php?ID=123456&PASSWORD=xxxxxx&dateutc=%s&temp=%2.2f&humidity=%2.2f&baromin=%f&winddir=%d&windspeedmph=%3.2f&rainin=%3.2f&softwaretype=Custom% Arduino&action=updateraw",
    //         utcDateString,Thermistor(analogRead(0)),humid,baro,winddir,windspeed,raingauge);
            Serial.print("url: ");
          Serial.println(url);

    double Thermistor(int RawADC) {
      double Temp;
      Temp = log(11100.0/((1024.0/RawADC-1)));  // Was 10000... Manually dialed down to increase accuracy. 9400 is a good value. Changing again to match wunderground
      Temp = 1 / (0.001129148 + (0.000234125 + (0.0000000876741 * Temp * Temp ))* Temp );
      Temp = Temp - 273.15;            // Convert Kelvin to Celcius
      Temp = (Temp * 9.0)/ 5.0 + 32.0; // Convert Celcius to Fahrenheit
      return Temp;
    }

Here's the output from those `Serial.print()` calls:

    humid: 0.00
    baro: 0.00
    windspeed: 0.00
    raingauge: 0.00
    winddir: 0
    url:

I'm not sure how else to debug this because when I uncomment `sprintf();` the Yun locks up and I have to press the `32U4 Reset` button and power cycle the Arduino to get it to work again.

title: sprintf() to assemble String and float pieces locks up

Answers: 2

body: Looks like `%f` isn't wired up for performance reasons.  You can convert floats to strings first using `dtostrf()`.

body:
This variable:

    String utcDateString = "";

Is a C++ String, not a character array like sprintf() is expecting.  To convert this string to a character array such that sprintf is expecting, you must use .c_str() in your sprintf, i.e.:

    sprintf(foo,"This is a format for %s", utcDateString.c_str());

Doing this should prevent the sprintf line from causing a memory fault.


body:
In a similar way to the question  "[**best way to determine if a 5 gallon water jug is getting empty**][1]", I'm looking for a way to measure water in a container. This is so it can be connected to an Arduino for logging and reporting.  But it's a very different container.

I have a home with the household water supplied from an underground concrete tank (around 3000 US gallons, 11000 litres).  Although there is a float switch cutout when it gets empty (to protect the pump), I'd like to know it's gettting low long before that (as it takes a while before a tanker delivers a fresh load).  Ideally something that measures exactly or in steps (at least in eights of a load), so software can predict when it'll run out based on average usage, and it can be monitored online when away.

The tank has a heavy concrete hatch, and a small hole that has an existing primitive dipstick, so access is limited.  It's in a harsh desert environment, but the pump room and power are only a few feet away.

Some ideas I had:

  - suspend an array of float switches with strings of different lengths from a bar inside the tank, and wire them all back to a controller.  Hard to install, ugly, low tech. Or something similar on a vertical pole.
  - contacts (like a US 2 pin plug) on a vertical pole that again are connected back to a controller (probably using a ribbon cable).  Corrosion/anodes might be a problem, although power could just be a short pulse at times.  Condensation, spiders webs and dead bugs may give false readings.
  - run a fully insulated cable vertically down it, and use as an antenna to send a pulse through, and use the difference between how it works as an antenna in air, and in water, (like an SWR meter) to calculate how far down the water is.
  - ultrasonic (or light?) distance finder mounted under the hatch.  Range needs to be up to 2 metres (6 feet).
  - depth finder (sonar) on a float.  Biggest challenge here is getting the signal out (long cable might get tangled when the tank fills).

The last two would be even better if they were wireless (to save running a cable that might get damaged) but I don't think I'd get the battery life I'd like (1 year or more).

Any other ideas?  Has anybody ever done this?

  [1]: https://arduino.stackexchange.com/questions/488/best-way-to-determine-if-a-5-gallon-water-jug-is-getting-empty

title: Sensor for underground water tank level

Answers: 10

body:
I have a background working on ships where robust and workable tank level gauges are  a huge part of instrumentation available to you. Water is the most forgiving and easiest liquid to measure - it's cool, not too viscous, not corrosive in itself, and easy to clean off. There are a lot of options available to you.

Personally I would avoid any system which involves immersing anything in liquid if at all possible. Waterproofing isn't easy. I would also try to stay with a tried and tested system.

So to run through your solutions:

 1. Multiple float switches - has poor resolution. Would be reliable. You can buy assemblies with LowLow, LowHigh, HighLow, HighHigh float limit switches already on them for maintaining tanks levels, but these are industrial quality with industrial prices.

 2. This would work, but corrosion is going to be an issue. Resolution limited by how many contacts you have.

 3. Interesting idea, but would likely require a lot of DSP work. Not a tried and tested method.

 4. An ultrasonic sensor would be my preferred method. Non-contact, high resolution, range of 2m is easy. Tried and tested system.

 5. Interesting idea, would require a lot of work. Easier to measure depth of air as per 4 and do the simple maths.

A few other methods come to mind:

1. A pressure sensor at the bottom of the tank. This is often used on ships, works well but needs immersion which can be avoided.

2. Inflow/outflow monitoring. A flow meter on the output can tell you how much you have used. Inferring level like this is prone to errors though.

There are a million other methods, but they get more and more complex.

The ultrasound would be a great way to do this. The commonly available [Parallax Ping][1] sensor would do the job. Realistically, you would only need to make measurements at most once every hour, so you could achieve great battery life. The concrete is likely to present a wireless range challenge. Most RF transceivers will get through concrete though, so place the receiver nearby.

If you want ideas on how it is done, google for ultrasonic *oil* level monitoring - there are loads of wireless commercial solutions.

  [1]: http://www.parallax.com/product/28015

body: Id go with an ultrasonic detector as Cybergibbons suggests together with a usage/flow monitor (http://www.ebay.com/bhp/water-flow-sensor) so as to understand if there are any losses through leaks etc. I'd use a YUN or Ethernet or shield to call or email you a monthly report / fill a datbase as well as place the order directly to the water supplier as well as cc'ing you.

body:
http://playground.arduino.cc/Main/Waterlevel

The above link had a nice approach.

![Water level detection using Pressure Transducer][1]

The principle is the same as traditional pneumatic level gauge, excepted that the dial indicator is replaced by a pressure transducer, and the manually-operated pump is replaced by an aquarium air pump.

When the pump is on, air flows through the weighted PVC pipe to the bottom of the tank, where bubbles appear. At this moment, the air pressure in the PVC pipe is equal to the hydrostatic pressure at the bottom of the tank. As the water pressure at the bottom of the tank is directly proportional to the water level, the same goes for the air pressure in the PVC tube. The air pressure is then converted to an analog voltage by the pressure transducer. This voltage can be read easily by the arduino.

A big advantage of this method with regards to other existing techniques is that no electronic or metallic parts needs to be placed in the tank, where the environmental conditions (mainly humidity) are not favorable. This avoids any risk of corrosion.

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

body:
It's tricky when you only have a small hole to work with, so trying to get inside to install a series of floats or contact pins on the side is not ideal. The ultrasonic is a good idea, but I don't know how that would be achieved. Personally, I would try the cable, as it is simple enough to drop it in the hole, and wait for your results.

If you wanted to try running a cable through it, you might want to use this [Water Level Sensor][1], or at least base your own project on it.

  [1]: http://vegetronix.com/Products/AquaPlumb/

It is non-corrosive, and has no moving parts, which is supposed to lead to a heightened accuracy, and less chance of it failing or breaking down. The enclosure is water-proof, and you can buy one with a relay attached to fit your monitoring needs. The only issue that I see is that it isn't wireless, but other than that, it seems to be pretty functional.

body:
The bubble tube method (http://dexautomation.com/?p=9) springs to mind.

Also capacitive measurement is doable (http://olimex.wordpress.com/2012/02/02/duinomite-project-tank-fluids-level-metering-by-capacitance-measurement/) but more tricky. If you can use the steel inside the concrete it can be made completely contactless.

Please note, that if the water is meant for consumption without filtering or purification you may want to refrain from direct-contact methods.

Googling for "tank level measurement arduino" yields lots of potentially useful results.

Also, is consumption so erratic that you can't predict when the tank needs filling?

body:
I know you asked this a few months ago .. but sometimes with something technical the project never gets completed, or at least not in short order.

So while you're building your new-world-order with an Arduino, can I suggest you put a pipe down the dip hole and insert a floating dip stick? 1.5" pipe. 1/4" dowel glued to a ping-pong ball. Flag on top of the dowel. Now you'll see the level any time you walk past.

body: I've been using the Ultrasonic method for close to a year and the biggest problem is the sensor failing due to water infiltration(condensation). My latest attempt lasted for about two weeks. I used plastic spray like the stuff you use on tool handles. I also used the wireless shield to make a website that displayed the level on any device connected to my router. I would like to get it to email me when the level is below 10% but can't get it to work....It's not bad but still needs work for stability...

body: The limited access issue is tough... If you were going to use the float idea, it would be hard to difficult to actually install the thing. The other issue is waterproofing components and making sure that they won't corrode and cause false readings, which defeats the purpose of installing the system. Although it is a different scenario, i use this Water Level Sensor to moniter my home aquarium. the sensor is totally insulated, and is thus waterproof. also the sensor itself is aproximately 1 mm in width,so it probably fit into your reservoir. From what i've seen so far from my use is that it is pretty accurate, and it works in both my salt water and fresh water tanks. Hope this helps!

body:
I have used FM antenna cable successfully as soil moisture sensor and as fluid level sensor. Dip the bottom end into melted glue stick to insulate.
For permanent installation in a water tank I would also dip the cable into a paint tin and hang it up to dry for extra insulation. Antenna cable without any extra waterproofing was used for soil moisture measuring for 3 years with no problems.
The top end is connected to two parts of a LM393. The first one is a Schmitt trigger with 470K feeback and 1M series. The neg side is fed back with 220K. The second one is simply an inverter, and the output feeds back through a 220K. The two 220ks get connected to the sensor cable, and a parallel 100pf cap.The cable is thus excited differentially.
The ciruit oscillates according to the capacitance of the sensor cable. The frequency is measured by your favourite micro. The extra 100pf is only there to keep the frequency in a range where the oscillations can be fed over a line.
A bucket of water is enough to calibrate the setup.

body:
You could take a piece of 2 conductor wire in a U shape that is weighted at the bottom of the "U" to rest at the bottom of the tank.  (The reason to use a U shaped wire instead of a straight wire is to prevent having to insulate one end from the water).  You would then measure the capacitance of the wire, where some baseline capacitance is the wire when dry and any wire that is wet would increase the capacitance proportional to the length that is wet.  Any wire that is rated for outdoor operation, i.e. does not absorb water would do and actually the thicker the jacket the better as the baseline capacitance would be lower.

The capacitance could be measured in the same way as a capacitive touch sensor or a capacitance to frequency converter (Sometimes called an "Oscillator").


body:
Arduino is an odd hybrid, where some C++ functionality is used in the embedded world—traditionally a C environment. Indeed, a lot of Arduino code is very C like though.

C has traditionally used `#define`s for constants. There are a number of reasons for this:

 1. You can't set array sizes using `const int`.
 2. You can't use `const int` as case statement labels (though this does work in some compilers)
 3. You can't initialize a `const` with another `const`.

You can check [this question][1] on StackOverflow for more reasoning.

So, what should we use for Arduino? I tend towards `#define`, but I see some code using `const` and some using a blend.

  [1]: https://stackoverflow.com/questions/1674032/static-const-vs-define-in-c

title: Is it better to use #define or const int for constants?

Answers: 4

body:
*EDIT: microtherion gives an excellent answer which corrects some of my points here, particularly about memory usage.*

---

As you've identified, there are certain situations where you're forced to use a `#define`, because the compiler won't allow a `const` variable. Similarly, in some situations you're forced to use variables, such as when you need an array of values (i.e. you can't have an array of `#define`).

However, there are many other situations where there isn't necessarily a single 'correct' answer. Here are some guidelines which I would follow:

**Type safety**
From a general programming point-of-view, `const` variables are usually preferable (where possible). The main reason for that is type-safety.

A `#define` (preprocessor macro) directly copies the literal value into each location in code, making every usage independent. This can hypothetically result in ambiguities, because the type may end up being resolved differently depending on how/where it's used.

A `const` variable is only ever one type, which is determined by its declaration, and resolved during initialisation. It will often require an explicit cast before it will behave differently (although there are various situations where it can safely be implicitly type-promoted). At the very least, the compiler can (if configured correctly) emit a more reliable warning when a type issue occurs.

A possible workaround for this is to include an explicit cast or a type-suffix within a `#define`. For example:

    #define THE_ANSWER (int8_t)42
    #define NOT_QUITE_PI 3.14f

That approach can potentially cause syntax problems in some cases though, depending on how it's used.

**Memory usage**
Unlike general purpose computing, memory is obviously at a premium when dealing with something like an Arduino. Using a `const` variable vs. a `#define` can affect where the data is stored in memory, which may force you to use one or the other.

 - `const` variables will (usually) be stored in SRAM, along with all other variables.
 - Literal values used in `#define` will often be stored in program space (Flash memory), alongside the sketch itself.

*(Note that there are various things which can affect exactly how and where something is stored, such as compiler configuration and optimisation.)*

SRAM and Flash have different limitations (e.g. 2 KB and 32 KB respectively for the Uno). For some applications, it's quite easy to run out of SRAM, so it can be helpful to shift some things into Flash. The reverse is also possible, although probably less common.

**PROGMEM**
It's possible to get the benefits of type-safety while also storing the data in program space (Flash). This is done using the `PROGMEM` keyword. It doesn't work for all types, but it's commonly used for arrays of integers or strings.

The general form given in the [**documentation**][1] is as follows:

    dataType variableName[] PROGMEM = {dataInt0, dataInt1, dataInt3...};

String tables are a bit more complicated, but the documentation has full details.

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

body:
It's important to note that `const int` does **not** behave identically in C and in C++, so in fact several of the objections against it that have been alluded to in the original question and in Peter Bloomfields's extensive answer are not valid:

 - In C++, `const int` constants are compile time values and **can** be used to set array limits, as case labels, etc.
 - `const int` constants do not necessarily occupy any storage. Unless you take their address or declare them extern, they will generally just have a compile time existence.

However, for integer constants, it might often be preferable to use a (named or anonymous) `enum`. I often like this because:

 - It's backward compatible with C.
 - It's nearly as type safe as `const int` (every bit as type safe in C++11).
 - It provides a natural way of grouping related constants.
 - You can even use them for some amount of namespace control.

So in an idiomatic C++ program, there is no reason whatsoever to use `#define` to define an integer constant. Even if you want to remain C compatible (because of technical requirements, because you're kickin' it old school, or because people you work with prefer it that way), you can still use `enum` and should do so, rather than use `#define`.

body:
**For variables of a specified type which are not altered during execution, either can usually be used.**

**For Digital pin numbers contained in variables, either can work - such as:**

    const int ledPin = 13;

**But there is one circumstance where I always use `#define`**

**It is to define analog pin numbers, since they are alphanumeric.**

Sure, you can hard-code the pin numbers as `a2`, `a3`, etc. all throughout the program and the compiler will know what to do with them.  Then if you change pins then each use would need to be changed.

Moreover, I always like to have my pin definitions up at the top all in one place, so the question becomes which type of `const` would be appropriate for a pin defined as `A5`.

In those cases I always use `#define`

**Voltage Divider Example:**

    //
    //  read12     Reads Voltage of 12V Battery
    //
    //        SDsolar      8/8/18
    //
    #define adcInput A5    // Voltage divider output comes in on Analog A5
    float R1 = 120000.0;   // R1 for voltage divider input from external 0-15V
    float R2 =  20000.0;   // R2 for voltage divider output to ADC
    float vRef = 4.8;      // 9V on Vcc goes through the regulator
    float vTmp, vIn;
    int value;
    .
    .
    void setup() {
    .
    // allow ADC to stabilize
    value=analogRead(adcPin); delay(50); value=analogRead(adcPin); delay(50);
    value=analogRead(adcPin); delay(50); value=analogRead(adcPin); delay(50);
    value=analogRead(adcPin); delay(50); value=analogRead(adcPin);
    .
    void loop () {
    .
    .
      value=analogRead(adcPin);
      vTmp = value * ( vRef / 1024.0 );
      vIn = vTmp / (R2/(R1+R2));
     .
     .

All the setup variables are right at the top and there is never going to be a change to the value of `adcPin` except at compile time.

No worries about what type `adcPin` is.  And no extra RAM is used in the binary to store a constant.

The compiler simply replaces each instance of `adcPin` with the string `A5` before compiling.

-----------------
There is an interesting Arduino Forum thread that discusses other ways to decide:

[#define vs. const variable][1]  (Arduino forum)

Excertps:

Code substitution:

    #define FOREVER for( ; ; )

    FOREVER
     {
     if (serial.available() > 0)
       ...
     }

Debugging code:

    #ifdef DEBUG
     #define DEBUG_PRINT(x) Serial.println(x)
    #else
     #define DEBUG_PRINT(x)
    #endif

Defining `true` and `false` as Boolean to save RAM

    Instead of using `const bool true = 1;` and same for `false`

    #define true (boolean)1
    #define false (boolean)0

---
A lot of it comes down to personal preference, however it is clear that `#define` is more versatile.

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

body:
1. > You can't set array sizes using `const int`.

   You can with `constexpr int`:

   ```
   constexpr auto size{ 15 };
   int array[size]{};
   ```
2. > You can't use `const int` as case statement labels (though this does work in some compilers)

   Again, you can with `constexpr int`:

   ```
   constexpr auto zero{ 0 };
   constexpr auto one{ 1 };

   int number{ 1 };
   switch (number)
   {
   case zero: Serial.println("zero!"); break;
   case one:  Serial.println("one!"); break;
   default:   Serial.println("neither!"); break;
   }
   ```

3. > You can't initialize a `const` with another `const`.

   You can even initialize a `constexpr` with another `constexpr`:

   ```
   constexpr int x{ 1 };
   const     int y{ x };
   constexpr int z{ x };
   ```

Furthermore, `constexpr` guarantees that the variable gets evaluated at compile-time, unlike `const`. `constexpr` also doesn't have some of the disadvantages that preprocessor macros have<sup>([learncpp](https://www.learncpp.com/cpp-tutorial/const-constexpr-and-symbolic-constants/))</sup>:

1. Debuggers like Visual Studio's don't let you *watch* preprocessor macros.
2. Macros can conflict with normal code.
3. Macros don't have scope, which increases the chance of naming conflicts.


body:
I have an object with a series of led and I want to turn on and off these leds from my Arduino. The input of the LED circuit is 24v DC 100mA.

What I've done is the following:

- I've cut a wire of this object and I connected one end to the collector and the other end to the emitter of a NPN transistor
- I connected the base of the transistor to a digital output (through a 1k resistance)
- I connected the power to the led series while the digital pin was LOW (actually completely disconnected)

**But with no current on the base of the transistor, the LED has turned on to my surprise.** I may have completely misused the transistor and other items. How do I fix this circuit?

title: How to switch an external circuit with Arduino?

Answers: 1

body:
If I understand your writeup correctly, this is what you have built:

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/8zae1.png)

<!-- End schematic -->

What you didn't mention in your question is that you made a connection from Arduino ground to the base of the transistor and the seconds circuit's ground connection. I drew the extra lead 'loose' for illustration only, but you see where it should connect. Current needs a return path, it is not sufficient to only have the forward path (from Arduino through R1 and base-Q1). The return path is emitter-Q1 to Arduino-GND.

Do notice though that the two batteries / power supplies must be floating with respect to each other otherwise you're going to short them out.


body:
When reading/trying a [recent answer][1], I was surprised to see that Arduino's `String` class supports the `c_str()` method, just like the C++ `std::string` class. As expected, it appears to get a pointer to the string's contents as a null-terminated `char` array (i.e. C-style string).

However, (as far as I can see) that method is not mentioned in the official Arduino documentation. Additionally, in all example code I've seen using `String`, a different approach seems to be used. A secondary `char` buffer is setup, and then the contents of the string are copied to it using [`String::toCharArray()`][2]. This obviously requires double the memory, plus an O(n) copy operation.

It seems like `c_str()` should be the preferred approach. Is there some reason why `toCharArray()` is more commonly used?

  [1]: https://arduino.stackexchange.com/a/511/42
  [2]: http://arduino.cc/en/Reference/StringToCharArray

title: Is it better to use c_str or toCharArray?

Answers: 1

body:
> It seems like `c_str()` should be the preferred approach. Is there some reason why `toCharArray()` is more commonly used?

basically, I'd say it's a lack of knowledge from the people doing the codes you've seen. Definitely `c_str()` is better. Though, what I see even more often is the use of character arrays `char*` strings instead of `String` (and I plead guilty of that as well in my own codes).

And that's because the Arduino library has been built upon a messy set of C and C++ libraries and coding style. Trying to make things easier actually messed them up and complicated them more.

That's actually why we have new projects like [xpcc][1] trying to make a real and smart use of the C++ abilities in the embedded world.

[1]:http://xpcc.kreatives-chaos.com


body:
Can someone help me understand how the external antenna IPX connector actually stays connected to the Yun? Do I have to "force" it in so it snaps in? I've been somewhat gentle with it in fear I'll break something. However when I get close to getting it in, it just pops back out.

I've never worked with an IPX connector before, and I'm trying to not break anything.

EDIT: I may have figured this out. Looks like the socket on the Yun is an IPEX socket, which is female. The cable I have is an IPX/uFL/u.FL connector, which also appears to be female.

It looks like I need to use an MCX cable adapter as found here: http://www.adafruit.com/products/1532 If someone could confirm this for me, that'd be great.

Here's a picture of the cable I purchased and my Yun.
![enter image description here][1]

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

title: Arduino Yun external antenna

Answers: 5

body:
There's a discussion on the Arduino Forum about this:

[Mystery component on Yun board?][1]

From what I read it's only for testing purposes.

> the connector is a MM8430-2610 ([see this][2]). You can plug in a
> MXGS83RK3000/MM126036: once plugged in, the switch connector will turn
> the internal antenna off and use the probe as an external antenna

  [1]: http://forum.arduino.cc/index.php?topic=188976.0
  [2]: http://www.murata.com/products/catalog/pdf/o33e.pdf

body: Testing with my Yún, it took quite a bit of force to install the connector. I had to use pliers to get extra leverage, but it eventually snapped in place.

body:
I went through this last night.  I got the adapter cable [ .../852] and antenna from Adafruit.
It appeared to be hard to snap into place, but it did go.
**It did not improve performance** though when testing signal strength with the Example>Bridge>WiFiStatus

Which leads me to believe that the connector didn't mate -or- I damaged it -or- it isn't the proper connector.
I am thinking the latter is the case.
Still looking for the answer.

Jim

I bought:
1 ea.     RP-SMA to uFL/u.FL/IPX/IPEX RF Adapter Cable     $3.95
http://www.adafruit.com/products/852
1 ea.     2.4GHz Dipole Swivel Antenna with RP-SMA - 5dBi     $8.95
http://www.adafruit.com/products/945

body:
I have several old mini-pci mini-pcie wifi cards laying around and the poster is correct: for some reason, they put the female end on the board whereas any wifi antenna you pull from a laptop, the cable will be female; all of my cards are the male version of the port on the YUN.

I can actually snap my old wifi cards onto the YUN's antenna port and they snap together perfectly just like the cable does in the laptops they belong.

For hobbyists, an old laptop wifi antennas are something we all have.

Why they did this I don't know.

body: @Jim was very close, the /851 part is the female to work with that connector. I have an adafruit Flora GPS with the same thing, a male connector on the board. I asked Adafruit for the adapter lead for it and they said the SMA to uFL #851 was what I needed. I just tried it on my shield and it fits.


body:
I've used enough products with embedded microcontrollers and unresponsive UIs to know that it can make or break a product. Even a slight delay or lag between the button presses and the display updating, or button presses being ignored or double counted, can be extremely frustrating.

What design patterns can be used to deal with user input (from buttons) and updating displays without causing these issues?

I currently use the following kind of pattern (this is simplified down to the bare minimum):

    #include <Bounce.h>

    #define GREEN_LED   6 // Pin for green LED

    #define BUTTON_PIN   15 // Pin for button - uses external pull down so active high

    #define DISPLAY_REFRESH_INT 100 // How many MS between display updates

    Bounce button = Bounce(BUTTON_PIN, 5);

    // To signal between the button read and the display update
    bool ledState = false;

    // Used to keep track of last display update
    long displayUpdate = 0;

    void setup()
    {
     pinMode(GREEN_LED, OUTPUT);
     pinMode(BUTTON_PIN, INPUT);
    }

    void loop()
    {
     // Read the button status
     if (button.update())
     {
      if (button.risingEdge())
      {
       ledState = !ledState;
      }
     }

     // Update the display periodically
     if (millis() - displayUpdate > DISPLAY_REFRESH_INT)
     {
      displayUpdate = millis();

      digitalWrite(GREEN_LED, ledState);
     }

    }

What other options are there? Is it ever worth using pin change interrupts to read buttons (if we are not considering battery life!).

title: What design patterns can I use to handle user input and display updating?

Answers: 4

body:
The answer depends on exactly how the sketch is meant to respond to the user interaction.

**External interrupts**
If the interaction depends on responding very accurately to the rising or falling edge of an input event (as in your example), then an [external interrupt][1] may be the way to go, if possible.

This is particularly important if the input event might be shorter that the duration of a call to `loop()`. If that happens, consecutive attempts to poll the input could completely miss the state change. It's quite rare for a user input event to be that short though, unless `loop()` is quite slow to execute.

External hardware to get help that though, e.g. by having an input which latches until it is read and reset by the microcontroller.

**Improving polling frequency**
External interrupts often aren't possible (e.g. because the chip only supports a limited number), or they are simply overkill/unnecessary for a given application.

In those cases, it may still be possible to improve the timing precision when using polling. One option is to split up all the different parts of the main loop into separate functions. On each successive iteration of `loop()`, it will call the next function, and then wrap round to the first. In between each of those functions, it can poll the button. Here's a simple example:

    unsigned int g_section = 0;

    void setup() { }

    void pollButton()
    {
        //...
    }

    void runSection0()
    {
        //...
    }

    void runSection1()
    {
        //...
    }

    void runSection2()
    {
        //...
    }

    void loop()
    {
        // Poll the button on every pass:
        pollButton();

        // Execute the next section of the main code:
        switch (g_section)
        {
        case 0: runSection0(); break;
        case 1: runSection1(); break;
        case 2: runSection2(); break;
        }

        // On the next iteration, run the next section:
        if (++g_section > 2) g_section = 0;
    }

One important issue with this approach is that it's very difficult to make each of those `runSectionX()` functions take the same execution time. That can result in the button being polled inconsistently from one iteration to the next. If it's fast enough though, then it shouldn't be too big of a problem.

**Display update**
Updating a display is unfortunately often quite slow, compared to many other operations. That means you need to be quite careful where you do it. Inside an Interrupt Service Routine often wouldn't be appropriate, as that could introduce other timing issues in your sketch.

Realistically, you'd have to do it in the main loop. If you absolutely have to run it quickly though, then it can be included in the faster polling example I've given above -- i.e. update the display on every iteration, the same as polling. You have to be careful to avoid partial updates though.

  [1]: https://arduino.stackexchange.com/questions/316/can-a-function-be-called-automatically-when-an-input-changes/317#317

body:
You could interrupt instead of polling if you can de-bounce the buttons in hardware. Otherwise you'll be take many more interrupts than there were button presses and still have to de-bounce them in software.

But to the primary question, a collection of state machines can be very useful, at least for the ui, and give you most of the benefits of multi-tasking without needed a m/t kernel.  can be  in RAM limited devices, unfortunately, because

The technique could be especially useful on these small devices but for the severe limits on RAM, making it something of a challenge to divide your state-machine data between flash and RAM, to fit.

body:
For program control, I made something of a menu handling framework for one of my projects and [shared the source on Github][1]. *Note that this is for chipKIT but the menu handling code is generic.* After building my 3rd or 4th huge if-else-if and switch structure, I decided there had to be a better way. *[Credit for the source of the static menu structures.][2]*

I just use the main loop to check the button.

I'm wanting to say the first step is to get a TFT. If you try it, you'll never go back... I particularly love the Adafruit 1.8" TFT with joystick. Arduinos are slow enough that I cannot recall caring to debounce user input.

  [1]: https://github.com/cacycleworks/chipKIT_ST7735/blob/master/Libraries/ST7735/examples/simpleMenu/simpleMenu.ino
  [2]: https://github.com/cacycleworks/chipKIT_ST7735/blob/master/Libraries/ST7735/examples/simpleMenu/menu_credit.txt

body:
As Chris K i've also implemented a static menu library with a wide variety of output options like Serial,LCD,TFT, etc..
I've started it to help in a friends project and I'm also sharing it open source for people that with similar problems, hope you can find it useful.

https://github.com/neu-rah/ArduinoMenu


body:
These are two ways I can hold a variable outside of loop (or any function).

First, I can declare it with global scope outside of loop:

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

    int count = 0;

    void loop()
    {
     Serial.println(count);
     count++;

     delay(250);
    }

I can also declare it static inside the loop:

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

    void loop()
    {
     static int count = 0;

     Serial.println(count);
     count++;

     delay(250);
    }

What difference, if any, will this make?

title: What is the difference between declaring a variable outside of loop and declaring static inside loop?

Answers: 3

body:
The most basic difference is of scope.

In the first case, you are declaring a global variable. It is a variable that is accessible in every scope after its definition.

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

    void inc();
    int count = 0;

    void loop()
    {
        Serial.println(count);
        count++;

        inc();

        delay(500);
    }

    void inc() //Can edit the value of count
    {
      count=count+1;
    };

In the second case, you are declaring a static variable with local scope. The variable will persist for the entire program run similar to global variables, but will be accessible only in the code block it is declared in. This is the same example, with only one change. `count` is now declared as a static variable inside `loop`.

    void inc();

    void loop()
    {
        static int count = 0;
        Serial.println(count);
        count++;

        inc();

        delay(500);
    }

This will not compile as the function `inc()` does not have access to `count`.

Global variables, however seemingly useful, come with some pitfalls. These can even cause damage when it comes to writing programs that can interact with the physical surroundings. This a very basic example of something that is quite likely to happen, as soon as programs start getting larger. A function may inadvertently change the state of a global variable.

    void setup()
    {
        Serial.begin(9600);
    }
    void another_function();
    int state=0;

    void loop()
    {
        //Keep toggling the state
        Serial.println(state);
        delay(250);
        state=state?0:1;

        //Some unrelated function call
        another_function();
    }

    void another_function()
    {
      //Inadvertently changes state
      state=1;

    }

Such cases are very hard to debug. *This* type of problem however, can easily be detected, by simply using a static variable.

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

    void loop()
    {
        static int state=0;

        //Keep toggling the state
        Serial.println(state);
        delay(250);
        state=state?0:1;

        //Some unrelated function call
        another_function();
    }

    void another_function()
    {
      //Results in a compile time error. Saves time.
      state=1;

    }

body:
From a functional perspective, both versions generate the same result, since in both cases the value of `count` is stored between the executions of the `loop()` (either because it is a global variable or because it is marked as `static` and therefore keeps its value).

So the decision which to choose come down to following arguments:

 1. Generally, in computer science, it is encouraged to keep your variables as local as possible in terms of **scope**. This usually results in much clearer code with less side-effects and reduces chances of someone else using that global variable screwing up your logic. E.g. in your first example, other logic areas might change the `count` value, whereas in the second, only that particular function `loop()` can do so.
 2. Global and static variables always occupy **memory**, where as locals only do when they are in scope. In your above examples that makes no difference (since in one you use a global, in the other a static variable), but in bigger and more complex programs it might and you could save memory using non-static locals.
*However*: If you have a variable in a logic area that is executed very often, consider making it either static or global, since
    otherwise you loose a tiny bit of performance each time that logic
    area is entered, since it takes a bit of time to allocate the memory
    for that new variable instance. You need to find a balance between memory load and performance.
 4. Other points such as better layout for **static analysis** or **optimization** by the compiler might also come into play.
 5. In some special scenarios, there might be issues with the unpredictable initialization order of static elements (not sure about that point, compare this [link][1] though).

Source: [Similar thread][2] on arduino.cc

  [1]: http://forum.arduino.cc/index.php?PHPSESSID=nt8h6685309s1vv0voea1rbkd5&topic=74180.msg559158#msg559158
  [2]: http://forum.arduino.cc/index.php?PHPSESSID=i4sdu9bn0f8u2jekn5tl5pbeo1&topic=74180.msg559208#msg559208

body:
Both variables are static - they persist for the entire execution session. The global is visible to any function if it declares - not defines - the global, or if the function follows the definition in the same compilation unit (file + includes).

Moving the definition of `count` to inside of a function both limits its scope of visibility to the nearest enclosing set of `{}`es, and gives it function invocation lifetime (it is created and destroyed as the function is entered and exited). Declaring it `static` as well gives it execution session lifetime it exists from the start to the end of the execution session, persisting across function invocations.

BTW: be cautious about using initialized statics within a function, as I have seen some versions of the gnu compiler get this wrong. An automatic variable with an initializer should be created and initialized on every function entry. A static with an initializer should only be initialized once, during the execution setup, before main() is given control (just as a global would be). I have had local statics get reinitialized on each function entry as though they were automatics, which is incorrect. Test your own compiler to be sure.


body:
I have 2 Lowpowerlab WaterMote's talking to each other using the 'out of the box' pre-installed [sketch][1] that just confirm they're talking to each other. I verified this by opening a COM connection and saw traffic of 'receiving packets...' That was just to show that they are functioning and talking to each other.

Now, using Arduino IDE on Mac OS X 1.9.x (Lion?) I have loaded the WaterMote sketch (found on [Github][2]) on the Moteino with the sensor (not the gateway) as it should be. The traffic looks like it's working, except the text being transmitted (number of Gallons) stays the same at 0.02 Gallons.

So... I want to debug the WaterMote sketch, *but* I do not see an option in my Arduino IDE on Mac OS X. Is there a way to debug sketches using Macs? Searching online shows various and preferred options, but mostly on Windows (of which I don't have any at home).

My current setup

 - Moteino Gateway (as out of the box) connected to a [Raspberry Pi][3] (with ssh enabled)
  - Connected via USB to the RasPi
 - Moteino with WaterMote sketch loaded
  - Connected via USB to the MacBook Pro
  - Arduino IDE running, but I see strange "[][][]" square output in the Serial connection.
  - I do not know what to make of this since that text is not in the WaterMote sketch.

Is there a way to debug sketches loaded on Arduino clones using Arduino IDE on Macs?

I found a debugging article:

 - [Visual Micro][4]

  [1]: http://www.arduino.cc/en/Tutorial/Sketch
  [2]: http://en.wikipedia.org/wiki/GitHub
  [3]: http://en.wikipedia.org/wiki/Raspberry_Pi
  [4]: http://www.instructables.com/id/Arduino-Debugging-Breakpoints-Tracepoints-and-E/

title: How to debug an Arduino sketch on a Mac?

Answers: 1

body:
> So... I want to debug the WaterMote sketch, but I do not see an option in my Arduino IDE on Mac OS X. Is there a way to debug sketches using Macs? Searching online shows various and preferred options, but mostly on Windows (of which I don't have any at home).

It's definitely possible to debug a sketch with OS X. But it's definitely an advanced AVR topic, and if you're not experienced enough with embedded programming you should first try to avoid it, except if it is really necessary.

Debugging a sketch for an [ATmega328][1] implies:

 - Running a flasher such as the AVR Dragon, the JTAG ICE 3, the STK500 or the AVR ONE; no cheap flasher implements the `DebugWire` protocol;
 - Setting up the debug fuse, which is an operation that can brick your [MCU][2].

If you're using an [ATmega32U4][3] (or alike), you won't be able to do it out of the box, as the 32U4 needs a [JTAG][4] connection for on-chip debugging.

Finally, once you got through that, you can bind a `gdb` to the AVR using [AVaRICE][5]. I'm not getting you through all that, because I really, really, strongly advise you not to do it until you're experienced enough to know what you're doing.

>    Moteino with WaterMote sketch loaded
>        connected via USB to the MacBook Pro
>        Arduino IDE running, but I see strange "[][][]" square output in the Serial connection.
>        I do not know what to make of this since that text is not in the WaterMote sketch.
> Is there a way to debug sketches loaded on Arduino clones using Arduino IDE on Macs?

It is very likely you did not setup the correct baudrate for the serial outputs. Arduino IDE defaults to 9600 bits/s connections, whereas the [WaterMote source code][6] defines a 115,200 bits/s connection. When you open the `Serial Monitor` change the setting at the right of the status bar.

And finally, be sure to uncomment the [`#define SERIAL_EN` line][7] to enable the serial communication and debug outputs.

  [1]: http://www.atmel.com/devices/atmega328.aspx
  [2]: http://en.wikipedia.org/wiki/Microcontroller
  [3]: http://www.atmel.com/devices/atmega32u4.aspx
  [4]: http://en.wikipedia.org/wiki/Joint_Test_Action_Group
  [5]: http://avarice.sf.net
  [6]: https://github.com/LowPowerLab/WaterMote/blob/master/WaterMote.ino#L31
  [7]: https://github.com/LowPowerLab/WaterMote/blob/master/WaterMote.ino#L30


body: I have been through http://arduino.cc/en/Hacking/LibraryTutorial but I can't do it. Whenever I create a new sketch and try to save it as `.cpp` or `.h` from the <kbd>Save As</kbd> button in the Arduino IDE, it gets saved as `_cpp` and `_h`. I am not able to create a library this way. How do I create a new library? What am I missing here?

title: Why are the files not being created correctly?

Answers: 1

body:
When you save a file using the Save As button from the Arduino IDE, it saves the current file as a sketch i.e. as an `.ino` file.

To create a `.cpp` and `.h` files for working on a new library, you need to create the files alongside a sketch. For this, you can use the Tab button on the top right (circled in red).

>![enter image description here][1]

Click on it, and select New Tab. You will get a bar at the bottom of the screen asking for a file name. Enter the name with extension (`test.cpp`) and press Enter.

>![enter image description here][2]

Your file has now been added to the current directory.

>![enter image description here][3]

Similarly, follow the same steps for creating the `.h` file.

Once your library is complete and ready to ship, you can move the `.cpp` and `.h` files to a separate directory and then add it under libraries.

  [1]: https://i.stack.imgur.com/lya7P.png
  [2]: https://i.stack.imgur.com/5cIWe.png
  [3]: https://i.stack.imgur.com/1Cp0V.png


body:
The Arduino IDE by default is oriented towards C++. The linker for example requires `.cpp` files and not `.c` files, otherwise it leads to errors during the linking process. See [name mangling][1] if you want to know more.

So, what are the tools that I need to setup a C environment? Can this be done from the Arduino IDE itself?

I work on a Linux system (Ubuntu 12.04).

  [1]: http://en.wikipedia.org/wiki/Name_mangling

title: What are the tools that I need to program the Arduino in C?

Answers: 4

body:
Well, if you want to do more advanced stuff with your AVRs, you should definitely leave the Arduino environment, and integrate your AVR development in your "usual" favorite development environment, whatever it is.

Then you've got two choices, either do 100% pure C with AVR libraries, for which you only need a simple makefile that calls avr-gcc with avr-libc libraries as include path. You can also use Atmel Studio that helps you a lot on that stuff. But if you do so, you're loosing the advantages of the libraries built for/by the arduino community – which, sadly, is not a huge loss for a strong majority of those.

Or you can work your code out as a 100% C external library, used from within the sketch, and included at linking time. Then you'll have all the advantages of working with any C++ library you'd like to have, but still doing the important code in pure C. Having only the `.ino` used to generate the main `.cpp` and any `.cpp` library you'd need. Though, for many basic features like writing on the serial port, you'll have to do it [the good old way][2] or by doing some weird encapsulation of `Serial.println()` call sent as a functor to the pure C parts.

In the [makefile][1] I've written (debian offers another one with the non-gui install of arduino), every `.c` file from declared libraries are detected and compiled with avr-gcc, every `.cpp` file is compiled with `avr-g++` and both gets linked when doing the `.elf`/`.hex` file.

[1]:https://github.com/guyzmo/Arduino-Tools/blob/master/Makefile

body:
Take a look at [ino][1] on linux and PCs and Mac.  It's available in the fedora repos, not sure about other distros; though, I'm sure everyone can install it from the [github project site][2], regardless of the distribution.  According to the website, you can also install it with python setup tools:

    pip install ino
or

        easy_install ino

*BTW: sorry for not including this "answer" in a comment due to reputation restrictions.*

Here's the description from the fedora repos; I think it's taken directly from the `ino` tool website:

>     Summary     : Command line toolkit for working with Arduino hardware
>     URL         : http://inotool.org/
>     License     : MIT
>     Description : Ino is a command line toolkit for working with Arduino hardware.
>                 :
>                 : It allows you to:
>                 : Quickly create new projects
>                 : Build a firmware from multiple source files and libraries
>                 : Upload the firmware to a device
>                 : Perform serial communication with a device (aka serial monitor)
>                 :
>                 : Ino may replace Arduino IDE UI if you prefer to work with command line and
>                 : an editor of your choice or if you want to integrate Arduino build process
>                 : to third party IDE.
>                 :
>                 : Ino is based on make to perform builds. However Makefiles are generated
>                 : automatically and you'll never see them if you don't want to.

  [1]: http://inotool.org
  [2]: http://github.com/amperka/ino.git

body:
> The linker for example requires .cpp files and not .c files, otherwise it leads to errors during the linking process

No, it doesn't.

---

> So, what are the tools that I need to setup a C environment?

Why do you want to?

---

**The answer**

Make a new tab in the IDE (top RH corner). Call it, for example, foo.c. That's your C file.

Put whatever C code you want into it. For example:

    #include <Arduino.h>
    void foo ()
    {
    PORTD = bit (1);
    }

Now in your "main" sketch call that function, eg.

    extern "C"
     {
     void foo ();
     }

    void setup ()
      {
      foo ();
      }  // end of setup

    void loop ()
      {
      }  // end of loop

Repeat as required for any C functions you care to write.

Of course, you can't use Serial (that's a C++ class) or Wire (that's a C++ class) or SPI (that's a C++ class), but if you want to work with C, you can certainly do that.

body:
You're already there with the Arduino IDE; C++ compilers understand plain C just fine, but may interpret C syntax slightly differently in some cases. I write most sketches in C, invoking C++ objects from libraries as necessary.

If you're to the point where you want finer grained control over which compiler, C or C++, gets used for a given module, then it's time to graduate to another environment. Eclipse is a very popular and flexible IDE for a large range of languages, compilers & cross-compilers, and provides a very flexible Arduino environment. Or your favorite shell, programming editor, Make, and the avr-gcc cross-compilation tool-set will give you the ultimate access to and control of every detail - perhaps more than you wanted - of the edit/compile/link/download/debug process.


body:
I am working on a UAV and we are currently exploring inertial measurement units or IMUs. The two options that we have come across are:

- Using an Arduino Uno and a 9 DOF IMU like [this one][1]
- Using an ArduIMU chip like [this one][2]

Ignoring the cost aspect and assuming the same microprocessor on board, what would be the pros and cons of either of these approaches?

Keep in mind that performance is very important for a UAV controller as ESCs require 60 Hz or higher refresh rates for stable flight.

  [1]: https://www.sparkfun.com/products/10724
  [2]: https://www.sparkfun.com/products/11055

title: Arduino + IMU vs ArduIMU

Answers: 1

body:
**Weight:** marginal as the difference between one board (with everything on it) and two boards (Uno plus DOF) may be - for model airplanes every bit counts.

**Size:** the traditional "Uno" is much larger than the ArduIMU integrated boards.

**Power:** the integrated board PROBABLY will use less and thus get away with a smaller (lighter) battery.