text:
Why does opening the Tools menu take so long?
Every time I open the Tools menu, the IDE freezes for a few seconds. Why is that? It happens on both of my computers, and nothing I do makes a difference in how long it takes. I've tried restarting the IDE, unplugging my Uno, and many other things, but nothing helps.
I'm on windows, running IDE version 1.0.2.

Which OS are you running on?

@PeterR.Bloomfield Windows

This is one part of the IDE that I haven't seen as slow in either Mac or Windows version.

It's an RXTX issue. RXTX is the native serial library used to make the IDE talk to the boards.
On some Windows installation, with some Bluetooth things (both dongles or integrated), when enumerating serial devices, these dongles scan the air for remote serial devices. Hence, the IDE stays stuck, waiting for RXTX serial device enumeration to end. This issue has been acknowledged a lot of times, see for example #1375, #532, #200 and #143
As far as I understand, this issue does not affect linux or mac because of the different way the scan occurs. On linux it's a plain filtered file listing of /dev. Similarly it's on mac. On windows, it uses native API calls.
Some fixes are available in the 1.5 series but I suggest switching to the latest 1.5.6 release as RXTX was replaced by JSSC, a more modern and simpler library.

Could you elaborate? What is the issue? If it is known, then is there a bug report? Whats going wrong? Why is it happening only on Windows and not Linux/Mac?

@AsheeshR elaborated

FYI, in the past I have been successful, in using a different version of RXTX library file. basically copying it over from other sources. Where I do recommend going forward with 1.5.+. Being natively fixed.

FYI: latest nightly, soon to become 1.6.2, speeds up tools menu a lot

Frederico Fissore already pointed out that this delay is due to the serial libraries. From a functional perspective: The Arduino IDE tries to enumerate all available COM ports which simply takes some time.
Quote from the official troubleshooting guide:

Why does do the Arduino software and the Tools menu take a long time to open (on Windows)?
If the Arduino software takes a long time to start up and appears to freeze when you try to open the Tools menu, there by a conflict with another device on your system. The Arduino software, on startup and when you open the Tools menu, tries to get a list of all the COM ports on your computer. It's possible that a COM port created by one of the devices on your computer slows down this process. Take a look in the Device Manager. Try disabling the devices that provide COM ports (e.g. Bluetooth devices).

As sofware engineer I should add that it is a bug obviously. Devices should be enumerated in background, before any kind of menu is opened. To keep internal state correct, a system hook should be set. The problem is that software is written in Java, and such low-level programming in Java is very hard as it's positioned as cross-platform language and makes it hard to depend on system features. (This time it's a design problem.)

I was having the same problem under Windows 7 x64 and had already removed all com ports and unknown devices as suggested above. For me, the solution was to rename "ListComPorts.exe" in the hardware\tools subfolder to "ListComPorts.exe.xxx" - this prevents the Arduino IDE from using this file and appearently it reverts to using the internal COM port detection mechanism (using DEVICE_ARRIVAL/DEVICE_REMOVAL messages??) . The tool menu now opens immediately every time.

I had the same issue on my laptop (win 7, 64). Renaming file ListComPorts.exe to ListComPorts.exe.xxx as mentioned above worked. I also had to switch to a standard USB port (not 2.0) for sketch to load properly.

Welcome to Arduino Stack Exchange! As it stands, this answer does not help answer the question any more than the answers above. If you have more information about this particular way of fixing the tools menu bug, please edit your answer to add that information.


text:
How do I erase the memory of the Arduino Uno?
I'm just a tinkerer learning Arduino with my son and I was surprised that when I plugged the USB cord back in to the Arduino the program was still running and I thought to myself, "it's a good thing I didn't just blow anything up."
So, what's the normal way people call it a day with these things?  Do you usually load up the bare-bones do nothing sketch or just unplug everything?

What do you mean by "when I plugged the USB cord back in to the Arduino the program was still running", what behavior did you observe and what behavior did you expect? Was anything connected to the Arduino?

@jippie yeah, I had a bunch of LED's plugged in and they all lit up. For some reason I thought the programs were loaded into memory and would be gone on reboot, but since that doesn't exist....

The programs are loaded into flash memory, not RAM, so they are kept even after powerdown.

When booted, the Arduino will run whatever program was put on it last. Solution: Don't turn it on if you don't want it to run.
When out of the box, the Arduino usually runs the Blink program. So you can just load that and call it a day if you want to "reset" it.
Or have a loop program with a sleep command.
If you've been messing with the USB bootloader via the icsp pins, this isn't enough though, you'll need to reinstall the bootloader. But if you've been uploading programs via usb or directly using a programmer, there is no issue with uploading Blink or some other dummy program to reset it.

is it possible to have it run a self-destructive program with nothing plugged in to the voltage terminals?

@PeterTurner when there's no power to it? No. But you can add a program that misuses the pins, and if you leave it on some damage can be called (not much unless the pins are connected)

If safety is a major concern, then you should almost always load a stop* sketch onto the board before calling it a day. This would be a good idea, for example, when your board is semi-permanently a part of a larger system. You could do so by:

Upload the Bare Minimum sketch found in File ->  Examples -> Basic in the arduino-ide
Upload a sketch with a large delay in loop.

#include <limits.h>

void setup()
{}

void loop()
{
  delay(ULONG_MAX);
}

Upload a sketch with a call to exit() from setup() (Thanks @Peter!)

void setup()
{
   exit(0);
}

void loop()
{}

*Stop is simply figurative. The board doesnt really stop running.

Could you get a similar (and more permanent) effect by calling exit() from within setup() or loop()?

@PeterR.Bloomfield Can't believe I forgot about that!

Why bother with either the exit or the delay? Just have void setup () { } void loop () { } - in any case internally the processor is just looping around "doing nothing useful".

The major thing that can go wrong is if you put your Arduino aside for a couple of weeks, forget what sketch (code) is loaded onto it, then get back to work on it, plug in hardware (like a switch, LED or motor) and have it unexpectedly light up / turn on, because the previous code addressed the pin it was connected to.

Solution 1. Load the new code first.
A simple and safe technique is to load the new code that you are working on today before you plug any hardware in. Now you know what the code does, what pins it uses, and you then plug the hardware in afterwards (preferably turning the Arduino off first by unplugging it).
Then when you reconnect power, it runs the sketch you uploaded, you have your hardware connected and all should be well.

Solution 2. Load a "do nothing" sketch.
You can upload this short sketch:
int main () { }

It "does nothing". All pins will remain as inputs, so you can safely then attach your hardware, and then start coding your new project.

Safety first
A good rule is to not plug or unplug hardware (eg. LEDs, switches, motors) with the power applied. If you get distracted and plug into the wrong socket on the board you might immediately damage either what you are connected, or the Arduino, or both.
With the power off, you can then do a last-minute check that everything is connected to the right place, you have your polarities correct, and so on.
Also make sure you don't have static electricity on your body, particularly if you are wearing a jumper or something fluffy, or are sitting on carpet.
Personally I always reach over and touch some metal part nearby to "ground" myself, before reaching for the Arduino. An example is the metal case of a PC, a headphone socket, or something like that.
If, after connecting power to the Arduino (eg. by the USB cable) you do not immediately see the power LED come on, disconnect the power immediately! You may have shorted something out, and the less time you do that for, the better.

In the Arduino IDE, go to examples, select Eeprom, select eeprom clear and then upload the sketch.
When it is the LED on pin 13 will turn on, you are done.
NB. This may take some time depending on the size of the EEPROM in the Arduino.

So what is the point? Running something that does not touch I/O (but clears the EEPROM at every power on)?

Have you actually tried this? Pin 13 does not appear to be set up as output (Arduino IDE 1.6.5)

My biggest concern when this happens is I've usually wired the Arduino for my new project and I'm plugging in the USB for the initial download of the new sketch. I worry, having no idea what the previous program is going to try, being connected to totally different hardware.
So far nothing bad has happened and I don't think I'll adopt burning BLINK each time I put one of my Arduinos back in the bin. It's probably just a matter of time though.

If the arduino board is connected to any other device then unplug everything and just connect the arduino with the computer using the usb cable and try to upload new sketch i hope it will help.

Welcome to Arduino SE! Is there any reason this answer is better than the other provided answers? Thanks!

source: Stack Exchange

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

sort: votes


text:
Can you fry an arduino with nothing plugged in to it?
I only get to work on my arduino every few weeks, so sometimes and get interrupted a lot by small children, so if I completely forget what is on the firmware, then I unplug the pins (because I haven't got anything soldered on there) should I be 100% certain I'm not going to fry my board?

There have been microcontrollers in the past that have functionality that allows you to create internals shorts or setup the clock in a way which means they are unrecoverable, but not recently

Although the controllers on an Arduino are pretty well protected, they can still be damaged by ESD (Electro Static Discharge). The same effect that makes a crispy sound when you pull off your woolen sweater in the winter, or after walking with rubber shoes on a carpet and you touch someone else or a metal and grounded object and you feel a pick. Static electricity can damage the controller. It may get completely broken, or it may function 'most of the time' or lifetime may be shortened.
An Arduino is also easily killed with an piezo gas lighter, just make the spark near the copper traces that feed directly in the controller. This is largely the same effect as above.
Again, the controllers themselves are pretty well protected, don't worry too much about them. But with kids running around (on their rubber shoes) better make sure they don't accidentally draw a spark from their little finger to your Arduino. The protective metallic bag is best, but putting it away in a cupboard or box should do the trick equally well.
As a general rule of thumb, the faster the electronics, the more sensitive it is for ESD. A Due is probably more sensitive than a UNO or a MEGA. But with normal, avoiding static electricity, use you should be OK.

An Arduino is also easily killed with an piezo gas lighter, just make the spark near the copper traces that feed directly in the controller This one is funny: why would someone want to do that? Is that a real-life experience of yours?

@jfpoilpret I don't know it is a fun experiment (for cheap chips that you don't need anyway). You never know with kids. But is was mostly to illustrate what is going on.

Arduinos are far from bulletproof but with nothing connected (apart from a power source of course) I doubt it will come to harm. If in doubt, upload Blink to it.
There are rugged Arduino-compatibles. One of them has a rather obvious name

What would that obvious name be? Ruggedduino? ;) You probably should put that in your answer because it could be called BulletProofDuino and that last sentence would still be applicable.

@AnnonomusPerson: I try to limit the amount of advertising I subject you folk to. (Especially(?) as I don't have any affiliation with the company concerned)

It seems though if a user wants one that you should tell them about it. You can just say I've heard of _____. Not to mention, you're not really affiliated with Arduino, either. :)

@AnnonomusPerson: Answer updated to be less coy.

It's generally a good idea not to try to take input from a pin configured as pinMode(OUTPUT) and vice versa. In addition, I prefer not to take input from tristated pins. Both of these cases are harmless, but it's good practice not to do so, especially since they can cause issues when coupled with some hardware.
In general, Arduinos are protected from software issues. You can't burnout an Arduino with just faulty software.
There are, however, many ways to fry an Arduino via hardware.

100% certain? No. 99.9999[Repeating]%? Yes
Here's a couple problems you could run into:

Using pins 0 and 1 when connected to USB (wouldn't damage it, the USB chip if on a board with a separate USB chip would probably ignore the "corrupted" data.)
You never mentioned your board. If it's a Uno and you modified your USB firmware, there might be some issues reflashing your board if you forget that you flashed it with a keyboard firmware. It won't damage it, but you may think it's bricked if you forget to reflash it.
If you only disconnect a couple pins and leave others in, it may give wierd results and fry the Arduino or whatever is partially attached
If you make any physical modifications to the board

The second to last one is the one you really have to worry about. I have seen previous discussions about destroying a board with a sketch, but nothing has been suggested.
Lastly, there a chance you can damage it with setting the fuses on the chip(s) on the board.

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


text:
How can I transmit data to/from arduino from up to ~750 ft away?
I am working on a design project for school (non-capstone non-electrical engineering project) where we are building a system to remotely control a winch on a boat that will lower an independently operating meter to specified depths using a pressure transducer (controlled from the shore).
My current idea is to have an arduino collecting data from the pressure transducer while being connected to the winch (adjusting it up/down as needed, based on the desired inputted depth). The arduino would then be connected to the a Raspberry Pi B via USB. The Raspberry Pi would then communicate via wifi USB adapter to a router @ 2.5 GHz 802.11n on the shore, which would then communicate with the laptop on the shore. The important thing is that the laptop on the shore will be recording data as well as changing the input depth for the arduino.
Arduino <==> Raspberry Pi <==> Router <==> Laptop on shore
I saw [this information][2] talking about connecting to an arduino via wifi, but I was unable to determine the potential range.
A related project using a boat that uses the Xbee shield.
Once concern is that we will not be able to specifically point any antenna on the boat back to shore, so we are looking for a non-direction-oriented solution.
I was wondering what potential ways I could communicate back to the shore to control the winch depth (output display on shore showing depth, then being able to change the depth from shore). Furthermore, I was wondering if my setup would be feasible and what your suggestions might be.
Thanks!

The previous thread was located at this link: http://%20https://arduino.stackexchange.com/questions/432/how-can-i-connect-to-an-arduino-using-wifi

Although your project includes an Arduino, your question does not look like an Arduino-related question, since you describe WIFI plugged into your Raspberry Pi. If you had the intent to use a Yun for instance, then your question would make more sense on arduino.SE

@jfpoilpret I believe he's looking for a way to accomplish this without the Pi. He mentions it because that's how the linked related project accomplishes it

Oops thanks @JohnB my mistake, I misread this part. Then the question seems OK for arduino.SE. However the use of 'would' or 'will' throughout the question makes me think that there is nothing at all currently. I think the OP should edit his question to make it clearer what is looking for: Arduino WIFI (including the distance issue), or something else including Raspberry Pi

Note that a directional antenna on either end will dramatically improve the range. A directional antenna could therefore be pointed at the boat from shore..

@jfpoilpret, you are correct that I currently do not have anything at this time. I am in the process of ordering parts for a design project in school.
I am looking for a solution in general and had planned to use the arduino for its analog inputs/outputs because it is what we have learned to use in class -- I do not have an extensive background in circuitry nor coding (beyond VBA for spreadsheets), so I am not entirely sure which direction to take with this problem.

@JohnB is correct that I would prefer to approach this without a pi, but it is a solution I came up with.

@jlbnjmn I didn't realize it could come from one source - I don't have a background in networking.
Would something along these lines be sufficient for improving the range work?

Google for '433MHz transceiver'

There are a number of considerations that need to be made when considering any wireless communication solution over long distances and over water.
WiFi is capable of working over long distances especially with higher power cards (1W ones are now readily available) and directional antenna (anything from 3dBi to 30dBi of gain). There are advantages and disadvantages to using WiFi like this for your purposes:

WiFi uses 2.4GHz which is attenuated by the presence of water and water vapour. If you are close to the surface of the water surface, this can cause variable range with weather conditions increasing humidity and spray - even slight choppiness can massively increase the humidity close to the surface.
WiFi is a fairly heavyweight protocol that has several layers that need setting up each time a connection is made. This takes time and means marginal connections will have zero throughput as they will never get setup.
WiFi is intended to have high throughput (>1MBps) and doesn't degrade gracefully below this point. There isn't often a need to shift data this fast on an Arduino project. Speed and range are a trade-off.
Directional antenna on boats can be hard work. The more gain an antenna has, the more directional it is, which in turn means you need to aim it better. Even mild rocking can make this difficult to impossible. It depends if you are on a smooth pond or the sea really.

If you do want to go with WiFi, Ubiquiti make some neat products like the Nanostation that allow long range connections to be set-up over long ranges.
Personally I would stay away from 2.4GHz near water, and go with one of the other ISM bands. Depending on your location, this could mean 315MHz 433MHz, 868MHz, or 915MHz. It depends which region of the world you are in which ones you are allowed to use.
These lower frequencies are suited to longer ranges and penetrating object and water. There are a lot of different solutions in this space, all of which have ups and downs.
The Hope RFM12B is a very popular small RF board that has several easy to use libraries available - I use Jeelib personally. These are just capable of the 750ft range you require. They are available in all most ISM bands, and personally I have found the 868MHz best outdoors, whilst the 434MHz is better indoors.
The newer Hope RFM69W is a similar board but with more functionality and more power. It has 13dBm (20mW) of power vs 0dBm (1mW) of power on the RFM12B. I have been seeing an increase in range of ~50-100% with these boards.
The RFM69HW is a high power version has 20dBm (100mW) of power. I haven't range tested this, but would expect up to 3-4 times the range of an RFM12B.
Ciseco, a UK company, also make a series of boards that use CC1110 chips as transceivers. These are in an XBee like form. One of their boards, the ARF, has a power amplifier. These have 26dBm output power (400mW) and in a brief test in a built up area, I have seen a range of about 2km.
It's important to note that these are transceivers so that they can send and receive, which means you can acknowledge if packets have been received.
There are boards like the nRF2401L which use 2.4GHz, but use a much lighter weight protocol than WiFi so work better on marginal ranges. They are dirt cheap (~£2). They have the same disadvantage of water impacting range.
I don't like Xbee at all. The boards are overpriced and I find the range isn't great even with the higher powered modules.
You could also "roll your own" and use simple 434/868/915MHz on-off-keyed (OOK) transmitter/receivers. Protocol design isn't easy though, and you lose a lot of hidden functionality that the more advanced boards have.

Thanks for the reply, @Cybergibbons. What would be a relatively easy system to implement? I am not extremely experienced on the software side, but I am willing to put forth the effort to learn, given it doesn't take too much effort -- I have a decent workload this semester.
I am overloaded with options  from you (for which I am grateful), so please give me your expert advice! This is a project that I am hoping to do a good job on while hoping to finish up within a semester.

I would use RFM69HW modules with Jeelib. There is an active and helpful Jeelib forum, they are very widely used. I am going to range test these this week.


text:
How do I burn the bootloader?
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?)

It is pretty easy to burn bootloader to arduino provided you follow right steps. This video might help you: YouTube - How To Burn Bootloader Onto ATMEGA328P-AU(SMD) | Homemade ARDUINO MINI

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:

Obtain an AVR ISP, USBtinyISP, ParallelProgrammer, or similar; or use another Arduino board. This will be your ISP.
Unless otherwise instructed, connect the ISP to the ICSP pins on your board.
Power your board with either a USB cable or an external power supply.
Open up the Arduino IDE.
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.
Select the appropriate programmer at Tools ► Programmer ►.
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

The AVRISP is pretty much EOL (end-of-life) at this point. At minimum, you want a AVRISPmk2. There are also lots of other, fancier tools (AVR One! for example). You should probably just say {line 1} or other dedicated ISP programmer.

On boards like the Arduino Yun, each time you "upload via wifi", you're burning the bootloader merged with your sketch. This thanks to the fact that the Linux CPU is connected to the AVR MCU through SPI, so that you can mimic an ISP with software.

@FedericoFissore - is that why it take so long?

Yes, that and the fact that GPIO bitbanging is slower. There is an ongoing effort to speed it up.

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.

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
Code can be downloaded from Github: nickgammon/arduino_sketches

Do you have to select the type of chip your are burning to (Tools->Board..)? What board do I select when I am burning the bootloader to stand alone chip?

You select the type of board you are using to burn the bootloader in the IDE. The bootloader sketch auto-detects the target board type.

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


text:
How do I debug on-chip with Arduino?
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?

Could you elaborate on what you are trying to accomplish? Its not clear from the question that what exactly do you want to debug.

@AsheeshR The only thing that is possible to debug on Arduino is source code. There's a set of tools called "debuggers", which employ breakpoints, step-by-step evaluation etc. I don't understand your question.

@jippie You're wrong about that. DebugWire yes, but JTAG No. The ATMega168/368 has no JTAG support whatsoever. If you do a quick search of the datasheet you will not find any reference to JTAG

@Madivad Is it possible to make another Arduino into USB to DebugWire connector?

@polkovnikov.ph I have never used DebugWire, so I don't know the first thing about it. I just did a quick google search, and there is stuff out there, so have a look at that. I have only ever used the JTAG pre Arduino days (ATMega128).

DebugWire is an Atmel proprietary protocol, not much information available about it.

I would say you don't. The closest to debugging I've seem is having the Arduino listen to serial and perform commands (like e.g. variable dumping) on request.

It seems there is possibility for interactive debugging with this tool: http://www.visualmicro.com/post/2012/05/05/Debug-Arduino-Overview.aspx it is not free but it is quite cheap. I haven't used it myself so I don't want to provide an answer for it.

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

Is there an AVR Dragon clone with open-source firmware?

Any links to those online guides?

There are MKII clones which will do debugwire with this chip, but I'm not aware of their open source hardware or software status, and am having trouble finding a good example easily. Here's one guide for using AVR Studio 6 with arduino projects: http://www.engblaze.com/tutorial-using-atmel-studio-6-with-arduino-projects/

Doesn't this require  removing a capacitor?

@PeterMortensen I don't know, you'd have to examine the arduino uno schematic and the debugwire requirements along with your debugger's documentation. It may be worth asking a new question to get or share details of a specific setup.

This might not be right for you, but the Visual Micro plugin for Atmel Studio and Visual Studio has a USB debugger which only uses Arduino code.
In the background the debugger uses Serial which might affect some time-sensitive applications.

Will this really work on Arduino Uno?


text:
Arduino as USB HID
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?

I may be wrong, but this is not really about Arduino. Its about Window's side device driver development.

First answer in google : http://mitchtech.net/arduino-usb-hid-keyboard/ ... but you did not specify which Arduino. On a Leonardo it's builtin, and the appropriate driver already exists (see http://arduino.cc/en/Reference/MouseKeyboard).

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 as the components aren't as readily available and cheap in my area as in most places.

@AsheeshR Well, now you've added more information to back up your claim, but it's just a link. So why didn't you post a more ellaborate version of that comment as an answer (not to be considered a link answer) and wait for the upvotes? That would have been much more constructive than voting for closing it.

@AsheeshR This issue is on meta now: http://meta.arduino.stackexchange.com/q/102/46

Well, that's definitely possible, as the Arduino Uno features an Atmega16u2 as USB driver chip, the user can use either DFU or ICSP flashing to push on the device a firmware close to the leonardo's which will make the Arduino behave as a HID keyboard. There's no windows development involved, no driver to be built as USB/HID devices are recognized per default. i.e. that question should be reopened.

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

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 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 or an
atmel programmer 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 to save your device, though it's often less trouble to just take a new chip.

Thanks for all the useful info, we ended up achieving this.

Well, the proper way to brick an AVR is with over current / over voltage. Then it will be toasted...

But then, it's not called bricking, but frying it, or as you say toasting it. Put 15amps through the MCU, and I bet you'll see it jump through the room ;-)

How to release a specific key? I want to emulate a key HOLD then release. And also in the link, the character goes to array [2] while here goes to [1]. Why?

well, as shown in my example, you do it in two steps, first you press the key, then there's the delay, then you release it. Well, then you'd need to lecture yourself on how hardware keyboard implementation works, it's kind of not natural, and each value of the array have a meaning. Pardon me for not having a link to share atm, but whenever you find something searching the web, please post a new comment ☺

Just to be clear. This ability depends on the Atmega16u2, so e.g. this is not possible with Arduino nano?

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

Welcome to Arduino SE! Can you add a little bit about how to use your library? Thanks!

Read the readme and try the examples? Its all there, no need to dupe everything here. Everything on Github is up to date :)

Sorry dude, it looks like a cool library, but your documentation is crazy lacking.  There's no real installation instructions as far as I can tell, and entire topics in your wiki just say "TODO" (specifically the gamepad topic is completely empty like this). :-/

Actually there is a need to present a basic description here: answers are required to be meaningful even without the external link, which could die.  And this one is not.


text:
Combining Strings into a datestamp
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?

How many problems can you detect here: "char dateName[13] = {String(now.day()) + "-" + String(now.month()) + "-" + String(now.year()) + ".csv"};"?

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

The SD card doesn't get files saved onto it when using this.

Can you check if it works when you write the filename manually? E.g.: dataFile = SD.open("test.csv", FILE_WRITE);

@SquarePie I tested the filename code just now, and it works as expected. I suspect the problem must be somewhere else in your code (or possibly the hardware).

@SquarePie I suggest you create a new question for this more specific SD write issue; it seems to me (but it's you to decide) that the current question has been correctly answered.

Is this based on the SDFat library?
Then you have to live with short 8.3 filenames for the moment.

It looks like this applies to the core SD library too. I hadn't noticed that. Well spotted.

In your second case, you need to break the initialization into two lines and use toCharArray() as shown:
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.

The SD card doesn't get files saved onto it when using this.

@SquarePie That's odd. Maybe there is something wrong  elsewhere, in the code, or in the hardware?

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

char str[16] = {0};

filename.toCharArray(str, 16);

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

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

Add some explanation to your code only solution.

Well:
  char buffer[15];
  snprintf(buffer, sizeof(buffer), "%02d-%02d-%04d.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.


text:
Best way to determine if a 5 gallon water jug is getting empty
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?

I believe water absorbs infrared light, so you could experiment with an infrared LED / phototransistor. There are special components too and possibly break outs. I believe it is how rain sensors work in a car.

A pressure sensitive base (i.e. springs and a switch) might be something to consider as well. The accuracy may not be excellent, but as long as you accounted for that in your tolerances it could work.

You might be able to use the difference in specific heat at a point on the bottle with and without water to the level of that point. A resister dissipating a level of energy detectable to the touch that is in thermal contact with a temperature sensor and all of that in thermal contact with the appropriate point on the bottle.

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

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

It's basically using the tare weight of the empty water container (or nearly empty, anyway) to trigger the alarm.
I would suggest that the hoses from the espresso machine plus a minimum safe amount of water be in the bottle when getting the baseline sensor measurement.

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

Interesting. This would require modifying the espresso maker somewhat to implement, correct? Would a fuse be an acceptable method?

I think you want a "liquid level switch", 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.

Yeah, that needs to be in the water, which is what I don't want.

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.

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?

Would work if all shots were equal, and then only if water was only used to make shots (not steam milk or clean glasses, or make americanos)

An espresso shot or even an Americano would seem a fixed amount (digital in this context), but yeah, steaming milk and cleaning in particular could vary (analog in this context). jlbnjmn's suggestion of essentially weighing the jug periodically is looking good, unless you can find a jippe suggested sensor that would maybe shine through the bottle near the bottom and then have some sort of reading change when it was no longer shining through water.

Nah, they are only semi-fixed per bean, and only assuming you don't change your recipe. The amount needed for a shot of espresso is not known beforehand as it can change per bean, per mood, per desired output weight or volume.

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.

Again, I dont want it in the water.

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 -- 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) -- 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.
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"
"Laser Timing Gate"
"Arduino Laser Tripwire"
"Arduino Forum: laser detection"
"Arduino security with frickin’ laser"
"Arduino self-calibrating laser trip wire"
"The Arduino Controlled Laser Security System"
"Raspberry Pi & Arduino: laser pointer communication"
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!)

Im definitely going to try this one, because I feel like it'll be a solution where I can change the bottle out without removing any sensor gear.  The laser and the sensor just need to be mounted bear the bottle, not actually on it.

you can use a metal detector like setup using the fact that electronic permittivity 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

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.


text:
Make an Arduino board act as both a usb storage device and a keyboard?
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!

http://www.atmel.com/Images/doc7631.pdf http://www.atmel.com/Images/doc8446.pdf

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)
USB mass storage is another game all together. The Brondani EasyUSB 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.

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, it'll just require more effort than you'd normally put into an arduino project.

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.


text:
sprintf() to assemble String and float pieces locks up
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%%20%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%%20Arduino&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.

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.

Well spotted. I was surprised to see that the Arduino's String class actually supports c_str() now. I'm fairly sure it didn't support it in the past, and it doesn't seem to be documented.

Yep, that seems to have cleared it up

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


text:
Sensor for underground water tank level
In a similar way to the question  "best way to determine if a 5 gallon water jug is getting empty", 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?

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:

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.
This would work, but corrosion is going to be an issue. Resolution limited by how many contacts you have.
Interesting idea, but would likely require a lot of DSP work. Not a tried and tested method.
An ultrasonic sensor would be my preferred method. Non-contact, high resolution, range of 2m is easy. Tried and tested system.
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:

A pressure sensor at the bottom of the tank. This is often used on ships, works well but needs immersion which can be avoided.
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 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.

I would concur with the ultrasonic sensor.  Stick a length of PVC down the dipstick hole into the tank so the pipe fills from the bottom.  Drop a ping pong ball or a float down the pipe so it rides up and down inside the pipe.  Aim an ultrasonic sensor down the pipe and read the distance to the ball/float.

I've had no issues using the bare sensor onto water with a 5cm length of pipe over the end to reduce spurious reflections, but I do like the ping pong ball idea.

@Mike Good idea but I don't know if most ultrasonic sensors would reach deep enough for a 3,000 gallon tank. Also, a sensor might be too wide to fit in a pipe that holds a ping-pong ball...

Question states range would need to be about 2m, Parallax Ping does 3m.

cybergibbons - nice list of for/against reasons, I agree with you that ultrasonic looks the simplest and most standard.  I'll leave the question open for a few more days for other suggestions before accepting an answer.  @mikeY - nice idea, simpler to mount, but the existing hole (through concrete) that the dipstick uses is (as Annonomus Person suggests) too narrow for a sensor (it's about 1/2", 12mm diameter).  Looking at the dipstick, the depth might be nearer to 3m than 2m, but that's still enough (as it's never empty).

http://playground.arduino.cc/Main/Waterlevel
The above link had a nice approach.

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.

Please update your answer with some detail in case the link gets changed or removed.

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, or at least base your own project on it.
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.

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.

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

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.

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?

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!

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.

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


text:
Is it better to use #define or const int for constants?
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 #defines for constants. There are a number of reasons for this:

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

You can check this question 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.

a good optimizer will render it moot

Really? I don't see how a compiler is going to resolve things like type safety, not being able to use the to define array length and so on.

I agree.  Plus, if you look at my answer below, I demonstrate that  there are circumstances when you don't really know which type to use, so #define is the obvious choice.   My example is in naming Analog pins - like A5.  There is no appropriate type for it that could be used as a const so the only choice is to use a #define and let the compiler substitute it as text input before interpreting the meaning.

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.

You raise some excellent points (especially about the array limits -- I hadn't realised the standard compiler with Arduino IDE supported that yet). It's not quite correct to say that a compile-time constant uses no storage though, because its value still has to occur in code (i.e. program memory rather than SRAM) anywhere that it's used. That means it impacts available Flash for any type that takes up more space than a pointer.

"so in fact several of the objections against it that have been alluded to in the original question" - why are they not valid in the original question, as it is stated these are constraints of C?

@Cybergibbons Arduino is based on C++, so it's not clear to me why C only constraints would be pertinent (unless your code for some reason needs to be compatible with C as well).

@PeterR.Bloomfield, my point about constants not requiring extra storage was confined to const int. For more complex types, you're right that storage may be allocated, but even so, you're unlikely to be worse off than with a #define.

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 is as follows:
dataType variableName[] PROGMEM = {dataInt0, dataInt1, dataInt3...};

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

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

In the same circumstances, a const will not use more RAM than a #define. And for the analog pins, I would define them as const uint8_t, although const int would make no difference.

You wrote “a const doesn't actually use more RAM [...] until it is actually used”. You missed my point: most of the time, a const does not use RAM, even when it is used. Then, “this is a multipass compiler”. Most importantly, it is an optimizing compiler. Whenever possible, constants get optimized into immediate operands.

You can't set array sizes using const int.

You can with constexpr int:
constexpr auto size{ 15 };
int array[size]{};

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

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(learncpp):

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


text:
How to switch an external circuit with Arduino?
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?

Can you describe your circuit a little more? Did you put the transistor between the 24v supply and the LEDs? Also, are you using the same Ground for the Arduino and the external circuit?

I put the transistor between 24v supply and LEDs and I tried using the ground of 24v supply only and also using both the ground

A diagram or photo would be most helpful. I find words can miss out vital detail.

@Cybergibbons http://meta.arduino.stackexchange.com/questions/12/how-do-i-describe-or-draw-my-circuit-in-such-a-way-that-everybody-understands-wh

Thanks guys for the many advices. In the next days I'm going to completely rebuild this project, following jippie diagram, to avoid messing things. I'll let you know

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

simulate this circuit – Schematic created using CircuitLab
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.

Note the transistor part number is just the standard partnumber from CircuitLab. I forgot to remove it and can't edit circuit any more.

From the comments, it sounds like Alessandro actually has the transistor on the other side of the LEDs.

@PeterR.Bloomfield one more reason to upvote http://meta.arduino.stackexchange.com/questions/12/how-do-i-describe-or-draw-my-circuit-in-such-a-way-that-everybody-understands-wh because that is not how I initially understood it. My transistor is "between 24v supply and LEDs" too ... it can be uderstood both ways. Apart from that this is the de-facto standard to solve the problem, unless ...

@jipple which transistor would you recommend for switching between a 5v and a 24v circuit?

I see you made a proper question on the stack from it, so I'll take it that you'll get some good answers there @Martin


text:
Is it better to use c_str or toCharArray?
When reading/trying a recent answer, 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(). 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?

Because new Arduino users don't want to branch out

Re "that method is not mentioned in the official Arduino documentation": It is available now: c_str()

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 trying to make a real and smart use of the C++ abilities in the embedded world.


text:
Arduino Yun external antenna
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.

If you can confirm that you've figured it out, could you add your solution as an answer? That will make it a bit easier for future visitors to find. Thanks!

Pat, were you ever able to confirm if the /1532 part works?

@Brodie I haven't purchased it yet, however this project has gained steam this week, so it might be ordered soon. Looking back at it again, I think it's the right connector, but can't confirm first-hand (yet)

the Arduino YUN wifi antenna onboard is an "SWF£ female connector type; not an IPX ;-)

I think what @Gianni72 said is correct.  This Digikey presentation has a nice animation showing how an RF Switch Connector works.  This type of operation would make sense on the Yùn, since it would automatically (mechanically) switch the signal route from the internal antenna to the external one.

There's a discussion on the Arduino Forum about this:
Mystery component on Yun board?
From what I read it's only for testing purposes.

the connector is a MM8430-2610 (see this). 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

I don't think I would call it testing purposes if the Arduino uses the "probe" as an external antenna. That seems like normal expected behavior for a device to turn off the internal antenna in favor of an external antenna. The PDF you linked may be onto something though with the validation of the MCX connector, and not the IPX connector I bought (pictured above).

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.

Did your cable look like mine in the photo? I think I may have bought a female cable (and the board connector is female) so I would have needed a male cable (I think).

@pat - Yep. you have the right cable. They don't look like they should fit, but they do

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

Thanks. That's the cable I have [.../852], and it doesn't work either. I think that's a female connector because of the way it looks. I think I need to purchase this male connector. http://www.adafruit.com/products/1532 - I haven't tried it yet though

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.

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


text:
What design patterns can I use to handle user input and display updating?
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!).

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

This is a great answer by the way. Exactly the kind of answer the site needs.

For program control, I made something of a menu handling framework for one of my projects and shared the source on Github. 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.
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.

I like the way you've done that - it's understandable, clean, and very small in size. I had been looking at using a library (MenuBackend) but it is hard to understand for new programmers (using callbacks) and can't sit in PROGMEM.

I find debounce often isn't required, but some switches seem to be much noisier than others. The upright, edge mounted PCB tactile switches seem the worst by far, maybe because instead of pressing, users often lever these forwards. Debouncing is so easy that I nearly always do it now.

Sorry for all the questions - why a TFT? I'm currently working with a 128x64 LCD which has a lot of benefits (mainly being physically large). Also cheap.

@Cybergibbons ah, didn't see any mention of a display. The one I like is a ready made shield, cheap enough, and you can do things with colors. Here's a build report of my most recent project: http://forums.adafruit.com/viewtopic.php?f=22&t=44710&p=223543#p223543

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.

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