text:
Is there a way to have more than 14 Output pins on arduino?
Is it possible to have more than 14 output pins on the Arduino, I am working on a project in which I need to light up several LEDs individually. I only have an Arduino Uno, and I don't want to get a Mega.

In the spirit of expandability, is I2C even an option with Arduino?

@ChrisO What do you mean by I2C? Because from what I understand Shift registers would be considered I2C.

Oh make me answer my question then ;-)  Here's a wikipedia article on this bus standard.  And I just found some support from Wire lib for I2C, so you could connect an I2C chain to your Uno.

@JVarhol Not quite. I2C, aka TWI is a a 2-wire interface while SPI may be considered a 3-wire interface.

Ahh, Makes sense now THX

@JVarhol have you selected a solution for your project already? If yes, it would be useful to edit your question and accept the answer that matches (or is the nearest) your solution.

A common way to expand the set of available output pins on the Arduino is to use shift registers like the 74HC595 IC (link to datasheet).
You need 3 pins to control these chips:

Clock
Latch
Data

In a program, you pass on the data one bit at a time to the shift register using the shiftOut() command, like so:
shiftOut(dataPin, clockPin, data);

With that command, you set each of the 8 outputs on the 595 IC with the 8 bits in the data variable.
With one 595, you gain 5 pins (8 on the IC, but you spend 3 to talk to it). To get more outputs, you can daisy-chain a series of 595 together, by connecting its serial-out pin, to the data pin of the next one. You also must connect together the clock and latch pins of all of the 595 ICs.
The resulting circuit (using one 595) would look like this:

The figure above was taken from this codeproject.com webpage:

Arduino Platform - Working with Shift Registers

The latch pin is used to keep the 595 outputs steady while you are shifting out data into it, like so:
digitalWrite(latchPin, LOW);
shiftOut(dataPin, clockPin, data);
digitalWrite(latchPin, HIGH);

Thx, forgot to include how a shift register works. I had planned to, but I had to walk away from my comp and when I came back it had slipped my mind. :)

No problem, that's why we are a community. We complement each other's answers. But it's nice that you've added a few good tips in your answer, too, specially about the EZ-Expander shield. It allows those who cannot easily make their PCBs to expand the number of ports available to them.

Also it makes the programming easy, you do not have to shift the data in and Pulse the clock and then activate the Latch. I have known about the shield for quite awhile and I think it is perfect for beginners. Best thing is, is that because the code is opensource you can use the code even if you are not using the actually shield but have your own board, or are using a breadboard.

Don't forget that you can link them in line (theoretically) indefinitely, so 2 8-bit registers can become one 16-bit.

Thanks! Here is an archive link to the amazing codeproject description in case the link ever goes down https://archive.fo/1uvPE

There are two ways you can get more pins out of an arduino.
The first way is by using the Analog pins as digital output pins, which is really easy to do. All you need to do is refer to A0-A5 as pins 14,15,16,17,18,19. For example to write high to pin A0 just use digitalWrite(14, HIGH).
The other way to get more pins out of the Arduino is by using a Shift Register. To do this I recommend using the EZ-Expander Shield, which allows you to use digitalWrite([20-35], HIGH) when you import the EZ-Expander Library. This shield however only allows the pins to be used as outputs only and uses pins 8,12 and 13 to control the shift registers.
The great thing is, is that you can use both of the two methods above together, without any problems.

According to the Arduino reference, you can actually use the A0-A5 identifiers directly instead of using numbers 14-19. For example, digitalWrite(A0, HIGH).

@PeterR.Bloomfield Both are correct, however I recommend A0-A5 for simplicity and easy of reading. Not a big deal with a LED blinking but when you have large projects little habits add up.

Actually, whilst both will get the job done on UNO and compatible boards, digitalWrite(A0) is more correct than digitalWrite(14) since the former will always map to the correct physical (analog) pin. On a different board, pin 14 may in fact not be A0, eg pin 14 on the MEGA is Serial3 TX and will not influence the analog pin that you're after. ie, if using digitalWrite on an analog pin, use the A0-A5 reference.

I2C (Wire)
You can use the I2C protocol (Wire library) to connect to other devices such as port-expanders. For example, the MCP23017.
I used one of those chips to connect to an LCD board. The MCP23017 has 16 ports, which can be configured as inputs or outputs. As inputs they can raise interrupts if desired.
Example of connecting 13 of those 16 to the LCD:

Now we connect to the Arduino using only 2 wires (SDA/SCL) plus power and ground:

Some third-party manufacturers have made boards with 4 x MCP23017 on them, this gives you 64 inputs/outputs:

Multiplexers
You can use analog multiplexers like the 74HC4051 (8 ports) or the 74HC4067 (16 ports) to connect one pin to one of the 8/16 ports (but only one at a given time), like this:

These are bi-directional, so can be used as an input or output expander.

SPI with 74HC595
Using SPI you can send fast serial data to a shift register, such as the 74HC595. These can be daisy chained together. In this example I am controlling 32 LEDs with only 3 I/O pins (MOSI/MISO/SCK) plus power and ground.

I found inside a commercial LED sign that the 72 LEDs were driven by 74HC595 chips.

This had 9 chips driving the columns (9 x 8 = 72 LEDs) and one chip driving the rows, in a multiplexed configuration.

SPI with MAX7219
If you just want to drive LEDs you can usually multiplex them. The MAX7219 simplifies that by being designed to drive LED matrixes, for example 7-segment displays:

Or 64-LED matrixes:

In both cases these can be daisy-chained together, for example:

All those examples only use 3 pins of the Arduino (MOSI/MISO/SCK) plus power and ground.

SPI with MCP23S17
The 16-port port expander mentioned earlier (MCP23017) also comes in an SPI variant (MCP23S17), which does virtually identical things. It uses one more wire, but would be faster.

Other protocols
LED strips (like the NeoPixel ones) have their own protocols. There was a post on Youtube by Josh Levine where the author drove over 1000 pixels with a Duemilanove!

References

I2C and MCP23017
MCP23017 and graphical LCD
74HC4051 multiplexer / demultiplexer
SPI
Hacking a scrolling LED strip
Using a 74HC595 output shift register as a port-expander
Interfacing LED displays with the MAX7219 driver

You put a lot of work into this answer! Good job!

If you want to drive LEDs, then you can also use a MAX7219 that can drive 64 LEDs, without extra circuitry (no need for transistor to amplify signal).
Driving a MAX7219 requires only 3 output pins on Arduino.
Also, you can find a few Arduino libraries for it.
You can also chain several of them if you need to power more than 64 LEDs.
I have used it successfully for multiple 7-segment LED displays.
Downside: it is expensive (about $10).

I did forget about the MAX7219, Thanks for posting!

384 LEDs... whoah! Plus two pins for USB inference. Wonder what kind of annoying trinket you can create (with a sufficient power supply).

You can use Charlieplexing. With this technique you can directly drive n*(n-1) LED's from n pins. So with 3 pins you can drive 6 LED's, 4 pins - 12 LED's, 5 pins - 20 LED's and so on.
Exemple:
Six LED's on 3 Pins
PINS        LEDS
0 1 2   1 2 3 4 5 6
0 0 0   0 0 0 0 0 0
0 1 Z   1 0 0 0 0 0
1 0 Z   0 1 0 0 0 0
Z 0 1   0 0 1 0 0 0
Z 1 0   0 0 0 1 0 0
0 Z 1   0 0 0 0 1 0
1 Z 0   0 0 0 0 0 1
0 0 1   0 0 1 0 1 0
0 1 0   1 0 0 1 0 0
0 1 1   1 0 0 0 1 0
1 0 0   0 1 0 0 0 1
1 0 1   0 1 1 0 0 0
1 1 0   0 0 0 1 0 1
1 1 1   0 0 0 0 0 0

You can see a better tutorial here.

One thing to note is that this technique allows you to control more leds, but not simultaneously necessarily.

@kontur yes, you're right. But in terms of persistence of vision you can consider that they are. The question doesn't have such details.

Charlieplexing is not the ONLY way to multiplex LEDs without using shift registers.

@linhartr22 I've NEVER said that is the only way. Charlieplexing is just a common solution for this problem. And my answer was the 7th one. So other possibilities had already showed before.

@DanielGrillo I should have been more specific and explained how column and row multiplexing, which is typically used on LED cubes, can be done without shift register and without the limitations of Charlieplexing. A 4x4 row column matrix can individually control 16 leds with 8 I/O lines. A 4x4x4 cube can individually control 64 leds with 12 I/O lines (possible even on an Uno by using Analog A0-A5 as digital lines).

Shift registers have been mentioned in other answers, and they are definitely an excellent choice for many projects. They are cheap, simple, moderately fast, and can typically be chained together to add more outputs. However, they have the downside that they usually need exclusive use of several pins (between 2 and 4, depending on how you set them up).
An alternative is to use more advanced port expanders, such as the 16-bit MCP23017 and MCP23S17. These support I2C and SPI respectively, which means you can place them on a bus with several other devices (potentially of different types). Each device on the bus can be individually addressed, meaning you only need 2 or 3 pins to talk to all of them. The update speeds are typically extremely fast, so you're unlikely to experience significant latency (i.e. transmission delays) in an Arduino project.
At a low level, using I2C or SPI is substantially more complicated than a simple shift register. However, there is library code for Arduino to take care of that for you. See this question, for example: How do I use I2C devices with Arduino?

Wow, i never knew about those, thx, ill look into them!

Can you use I2C to control LEDs?

@ProQ You can't control standard LEDs directly using I2C. However, it is possible to get some LED products which have a built-in I2C driver. This is usually for products with lots of LEDs, such as strips or matrices.

In addition to Ricardo's answer, what Wikipedia states on shift registers:

One of the most common uses of a shift register is to convert between serial and parallel interfaces. [...] SIPO registers are commonly attached to the output of microprocessors when more General Purpose Input/Output pins are required than are available. This allows several binary devices to be controlled using only two or three pins, but slower than parallel I/O.

In the article Ricardo linked you can see the diagram of the shift register.

What happens here is that you put the data of the 8 pins in a sequence and for each clock tick the shift register will shift (move the binary data from each latch to the next one) until it "makes a circle" i.e. the first bit arrives to the last pin. Shift registers also have an input where you can turn on/off the shifting so the status can be kept after the data is shifted to the position. For a simple demonstration see the following animation.

Here the red light is the serial input and the green ones are showing the state of the latches in this simplified SIPO shift register. After the data shifted to place shifting can be turned off and you can read the pins. In this example I shifted out 10101011.
From these examples you can realize that serial transfer will be slower than parallel, because you have to wait for the shift register to shift the bits to their place. You will have to wait the same amount of clock tick as many bits you want to load. This is one of the many reasons why you can't chain them indefinitely, because loading would take forever.

+1 for the additional information AND for the pretty animated GIF and its didatic effect! Where did you find the GIF? Or did you make it?

@Ricardo I created the circuit with Digital Works, then print screen, edit, gif animator.

As you wrote already already, you can use all pins, including TX and RX as digital output. I did that a while ago for a demonstrator and recorded a video - 20 LEDS on 20 pins - of this rather nonsensical project.
As described by Peter R. Bloomfield here, you a have to disconnect TX and RX for upload. Moreover, you're out of pins to read sensors for possible interactivity and have to make sure that the total current limit isn't reached. Not to forget that you're limited to 5V leds if you drive them directly with your Arduino.
The use of shift registers in general and the 595, described by Ricardo is therefore highly recommended.

They are cheap!
It's rather easy to cascade them.
A lot of speed can be gained when you use hardware-SPI.

I used them a while ago when I realized the soldering and programming part of Kawaii me (text of the link is in German) of the upcycling artist Dominik Jais.
Here, just a bunch of 595 were used to drive a display of 8x11 leds. Since the leds were cut from a stripe of 12V SMD leds, an additional power supply and some UDN2803A Darlington arrays, hooked to the output pins of the shift registers, were necessary.
Other general methods would include the use of PCF8574(A) 8bit port expanders, which are controlled via the I2C bus.
Anyway, I'd give the 595 shift registers a try first.
If you need to control a couple of RGB leds, however, you might want to look for more specialized solutions. Some RGB leds come with their own WS2812. These fine pieces can be cascaded (1-Wire bus) and are addressed via their position in the chain.

I do not claim this method for my own, but I found this neat trick on the webpage MUX-DEMUX: CD4051 Parlor Tricks
Whatever method you choose to use to drive outputs or read inputs (shift registers, multiplexors or the straightforward direct use of the Arduino pins themselves) you can DOUBLE the number of outputs or inputs by a clever use of parallel circuit pairs (to form a dual input or output bank), employing diodes in opposing senses on each parallel branch, and switching the inputs/outputs to high and low.
To illustrate the method for outputs (LEDs in this case, note that the extra diodes are not required):

If you consider the pair of LEDs in this example to be a "bank", and
  you want to light LED_0, you need to set PIN 17 to HIGH, and PIN 18 to
  LOW. (The pin numbers are confusing, but they match the later example
  so bare with me). To light LED_1, you just reverse the PINS. The diode
  nature of LEDs keeps the current from flowing the opposite direction
  keeping the other one off.

To illustrate the method for inputs (CdSs in this case, note that the extra diodes are required):

This gets a little more complicated if you want to do an analog read
  on a CdS light sensor. First, you need to add a diode to each sensor
  to control the flow. Second, since you are reading values, you need to
  pull the inputs high or low to keep them from floating. Being a lazy
  person, I'm going to pull them high using the internal pull-up
  resistors. To read CdS_0, you set PIN 17 mode to OUTPUT and set it to
  LOW. This makes it the ground. Then you set PIN 18 mode to INPUT and
  set it to HIGH to engage the pull-up resistor. Now you are set to do a
  read on PIN 18 (a.k.a. analog pin 4). To access the other sensor, just
  switch the modes and outputs.

So, if you have a CD4051 8 port multiplexor, using 5 pins on the Arduino (instead of the usual 3), you can obtain 16 inputs or outputs, or a mix of the two.

Likewise, if you have a 4067 16 port multiplexor you can obtain 32 inputs or outputs, or a mix of the two.
An example sketch would be:
/*
 * Example of getting 16 i/o from 5 pins using a CD4051
 *
 * Based on tutorial and code by david c. and tomek n.* for k3 / malmö högskola
 * http://www.arduino.cc/playground/Learning/4051?action=sourceblock&ref=1
 */

int selPin[] = { 14, 15, 16 }; // select pins on 4051 (analog A0, A1, A2)
int commonPin[] = { 17, 18};   // common in/out pins (analog A3, A4)
int led[] = {LOW, LOW, LOW, LOW, LOW, LOW, LOW, LOW };  // stores eight LED states
int CdSVal[] = { 0, 0, 0, 0 }; // store last CdS readings
int cnt = 0;  // main loop counter
int persistDelay = 100; // LED ontime in microseconds

void setup(){
  Serial.begin(9600);  // serial comms for troubleshooting (always)
  for(int pin = 0; pin < 3; pin++){ // setup select pins
    pinMode(selPin[pin], OUTPUT);
  }
}

void loop(){
  flashLEDs();
  if (cnt == 0){
    for(int x; x < 8; x++){
      led[x] = random(2);
    }
  }
  cnt++;
  if (cnt > 100) { cnt = 0; }
}

void flashLEDs() {
  for(int pin = 0; pin < 2; pin++) {  // set common pins low
    pinMode(commonPin[pin], OUTPUT);
    digitalWrite(commonPin[pin], LOW);
  }
  for (int bank = 0; bank < 4; bank++) {
    for(int pin = 0; pin < 3; pin++) { // parse out select pin bits
      int signal = (bank >> pin) & 1;  // shift  & bitwise compare
      digitalWrite(selPin[pin], signal);
    }
    if (led[bank * 2]){        // first LED
      digitalWrite(commonPin[0], HIGH);  // turn common on
      delayMicroseconds(persistDelay);   // leave led lit
      digitalWrite(commonPin[0], LOW);   // turn common off
    }
    if (led[bank * 2 + 1]){     // repeat for second LED
      digitalWrite(commonPin[1], HIGH);
      delayMicroseconds(persistDelay);
      digitalWrite(commonPin[1], LOW);
    }
  }
}

Like I said in the first line, the full explanation can be found on MUX-DEMUX: CD4051 Parlor Tricks

If it's all about LEDs, what about WS2812B LED strips, or just the driver chips themselves? You can control a virtually unlimited number of LEDs using just one pin!
Although people are use to these in strips, they are available as standalone LEDs (known as neo pixels on Adafruit). Or if you're only driving a single colour, each WS2811 chip could control 3 LEDs by using each of the RGB outputs for a single LED each.
I recently just created created a project that uses 5 such LEDs: Door1 open/closed, Door2 open/closed, motor1 active, motor2 active and power. The "active" LEDs are dual purpose since I have red being the input from active motor and green being active flag inside the Arduino.
Point being, with 1 pin and the library installed, you can control any number of LEDs

For a class project I used a CD4024 and two Arduino pins to drive a 7-segment display.
There are some caveats to this approach. For example, to write a high value to the first output of a ripple counter only requires a reset and toggling the clock pin twice. But if you want to write high to all n pins requires toggling the clock pin 2n times, and during that time all the other pins are constantly toggling on and off.
If your application can deal with these limitations and you're short on pins, it's another option.
Bonus answer: there are a lot of examples of multiplexing inputs here, many of which also apply to multiplexing outputs.

Using a 7-stage counter to drive a 7-segments display seems a suboptimal approach, for the reasons you've yourself indicated.

With a bit of work (installing a different bootloader) an additional seven I/O lines are available on an Uno, on the ICSP1 and JP2 headers.  The replacement bootloader is called HoodLoader2.  It allows you to install sketches on both the Atmega328 and Atmega16U2 on an Uno.  Dealing with multiple processors would be the main complication from using this method.
On an Uno, the ICSP1 and JP2 headers connect to pins PB1...PB7 of the Atmega16U2.  In addition the Atmega16U2 has about 9 I/O pins with no connection to the circuit board.  A person working under a microscope might be able to attach wires to a total of 18 I/O pins on the 16U2, while leaving three other I/O pins attached to their ordinary connections.
HoodLoader2 also works on Mega boards.

There is a wealth of good answers here, but if you costed your time you'd find it cheaper to buy a Mega.
My 3/2-d worth.


text:
What are the steps involved in porting an Arduino library?
I want to use the Adafruit CC3000 and its Arduino libraries on another platform. In this case it's the Arduino pin compatible PSOC4 Pioneer Kit. This is an ARM Cortex M0 based platform.
My question is: How would I go about porting a library like this? What are the steps, key files etc?
One obvious issue is that PSOC Creator does not readily support C++.
One positive might be that the Arduino Due board is based on the Atmel SAM3X8E ARM Cortex-M3 CPU.
NOTE: If you think this question is off topic; please head over to this question on Arduino Meta to voice your opinion on whether questions on Arduino Compatible devices are appropriate for this list.

Are you asking how to port a Lib written in C++ to C?

Not really. Because I've seen that limited C++ support can be made to work in PSOC Creator. It's more the process of library porting I'm interested in. Particularly to an ARM Cortex based Arduino Compatible device.

ahh, Okay well then I am not quite sure how to do that, I thought you just wanted the library in C instead of C++

I did essentially the same thing with getting the Adafruit ST7735 library working in chipKIT. I started a support thread here which can lead you through my process.
I tackled it the same way I do general programming:
1-» Copy over Libraries, get it so your compiler can actually SEE them.
2-» Start trying to compile and then triage errors from the "top level" down:
3-» Look for stlib functions you recognize as should be working and fix those.
4-» Look for AVR specific code and comment those out. I normally also add my initials and a comment: ckck - bitbanging SPI, so I can search for these later.
Repeat 3 and 4 until it works or you quit. :)
Reach out to the forums for your target; they might have been there done that -- or like in my case, you introduce them to something that they want, so they dive in and help.

source: Stack Exchange

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

sort: votes


text:
Internet connectivity for the Arduino Due using AtmelStudio?
What hardware and software solutions work and what are the tradeoffs for connecting an Arduino Due to the internet?  I gather the ethernet hardware is much cheaper than WiFi hardware (€29 versus €69).  In either case (wired or wireless), what software stacks and drivers work under AtmelStudio?

Greatt question

Atmel studio uses c++ right? Porting the Ethernet library cant be that hard.

Hoping so @TheDoctor.  I see an Ethernet PHY component and driver in the ASF Wizard but no TCP/IP pieces.  In answer to your question, yes, I see C++ hints everywhere but I've only used C so far.

@BobStein-VisiBone - That PHY component requires a specific external ethernet PHY (A DM9161A). It will not work with the arduino ethernet board/shield, which uses a Wiznet W5100 PHY/coprocessor).

Well, your best bet is to import the arduino libraries in your Atmel Studio project. Then you'll be able to use existing code to connect to the "traditional" Ethernet Shield using SPI.
Though, the Sam 3X features an hardware ethernet that is not wired, unlike the MBed LPC1768… Sadly that's the ethernet PHY component you saw, but won't be able to actually use…

You could always buy a Taijiuino Due, which is a 3rd party due clone that is code-compatible, but has the ethernet IO lines broken out.

You mean the Visual Micro plugin for Atmel Studio?  And with that make a TCP/IP server with the EthernetServer class?

I guess so, though I've not tried that. You may also include the sources or add headers + libraries as dependencies in your project (which is what I do)

What .c .cpp .h files do you use @zmo?  What kind of TCP/IP features do you have, or are they merely Ethernet?

This solution means I'd give up ASF (Atmel Studio Framework) correct?

Er… what are you actually asking? are you asking about the SAM3X Ethernet features, or using an ethernet shield on the Due? Anyway, that does not mean you have to give up ASF, just to complete it with parts of the Arduino framework.

Your answer says "import the arduino libraries".  Is that possible in a project that includes ASF?  I've only managed to be able to use one or the other, by New | Project or New | Arduino Project.  If it isn't too noob a question, can you walk me through the exact steps how to import the arduino libraries in a project that uses ASF?

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


text:
Washable, Wearable Tech with Arduino
Question: How does one prepare clothing with embedded electronics for washing?
Background: There are several Arduino boards/clones that are designed for "wearable tech."  (For example, the Lilypad.)  Wearable tech with LED light patterns, microphones, GPS, or other circuitry is an interesting concept, but water and electricity tend not to mix.
To prepare wearable tech for washing, I would assume people make large circuitry removable.  Yet, inevitably, some electronics will be more-or-less permanently affixed to the cloth.  What, if anything, can be done to these electronics (e.g. sewn-in Arduino Lilypad) to make them washing-machine (preferred--hand wash could be done, but it's so much easier to machine wash) safe?

I would use some sort of epoxy and cover up the exposed circuitry. The major concern would be where the wires connect to the board as flex over time can weaken it.
Some options include:

3M™ Scotchcast™ Wet-Niche Potting Kit
Hysol

US1150™—For electronics, telecommunications, and automotive
  components. Provides environmental hazard protection.
US1152™—For electronic assemblies. Provides environmental hazard protection.

  Heat might play a factor if you cover up the boards in epoxy but you shouldn't be producing that much heat in a wearable device anyway, right?

I would make it so the Board has velcro on it so that it can be un attached from the clothing, and then have all the wires have snap terminals that wires from the Arduino connect to. This way you un snap all the wires and remove the arduino. As far as components, I would cover them in an epoxy to protect them.

I've purchased the "correct" snaps for wearable electronic connections, and I've also bought cheap shiny silver colored snaps from the fabric store. Both work just fine with conductive thread. It's a lot less particular than it seems like it should be.

How does one prepare clothing with embedded electronics for washing?

Remove the battery(ies) and other power supplies, and set them far away from the water. Buzzers and speakers also.
Gently wash clothing (including the Lilypad, LEDs, resistors, capacitors, integrated circuits, accelerometers, magnetometers, Bluetooth modules, GPS modules, etc.) by hand with a mild detergent.
Drip dry, or manually dry with a hair-dryer.

See:

"LilyPad ... They're even washable!"
"accelerometer shirt ... is washable."
"Are LEDs and Resistors Washable?" (Yes!)
"Remove After Washing" on Piezo Buzzer


text:
Is my ATmega broken, and would replacing it with another break that one, too?
I was communicating between my computer and my Arduino Uno R3 through Bluetooth using this Bluetooth module. The connector I use has a red wire where it connects to GND, and a black wire where it connects to +5V.

                ↓        ↓  to Uno ↓       ↓
               +5V      GND       pin 0  pin 1

I forgot this one time when I connected the Bluetooth module to the Uno, so the polarity was reversed. This fried the Bluetooth module.
After getting a new module, I discovered that the Uno was apparently fried too. Plugging a USB cable into the Uno made the little green integrated LED turn on, but that was all that happened; none of the pins put out any electricity. When I tried to upload a program, it gave the infamous avrdude: stk500_getsync(): not in sync: resp=0x00 error. I could upload programs to my other Uno fine, and I could not upload to the broken Uno on my other computer.
Two of the Arduino experts I know told me that the ATmega328 chip might be the only broken part. Is this likely to be the case? I have an Uno R2 with a working ATmega328. Would temporarily replacing the R3's ATmega with that R2's ATmega have a change of damaging anything?

Generally the black wire is ground and the red wire is +5v

@TheDoctor I know. The connector I used looked sort of like this. When I connected it to the Bluetooth module, the pins on the bluetooth and the wires on the connector were ordered in such a way that the connector's red wire represented the bluetooth's ground.

looks like youre having the same problem as discussed here: http://arduino.stackexchange.com/questions/17/some-dude-named-avr-wont-let-me-upload-my-program-aka-avrdude-stk500-getsync

@TheDoctor Not exactly. That problem is a symptom of this problem.

Another possibility is that the bootloader got erased by the accident. Since you have another Uno, you could try using the ArduinoISP sketch on your working Uno to try reprogramming your non-working Uno.

Besides breaking a pin while removing the IC from its socket, or static electricity during manipulation, I don't see what could fry the ATmega.
However, it is possible that the R2 ATmega has a different bootloader and that may be an issue.
If I was you I would just remove the ATmega from the R3 board and test it on a breadboard (don't need a lot of components to do that); at least that could tell you if it is fried or if it is the R3 board that is fried...

Although bootloaders may be different, they don't rely on board revision. I know there was a switch of bootloaders in the past because the new one was smaller and therefore left more flash for the program. The board release is mainly different for couple signals being routed to extra pins on the headers.


text:
What are the AREF, IOREF, and the unlabeled pin next to IOREF on the Uno R3?
There are some pins on the Arduino which I haven't been able to find out anything about:

IOREF
AREF
An unlabeled one next to IOREF

What are they?

AREF:
This is the voltage reference analog-to-digital converter (ADC). It can be used instead of the standard 5V reference for the top end of the analog spectrum – for example, if you wanted to use the ADC to monitor a signal that had a 0-1.5 volt range you could get the full scale of the ADC by connect AREF to a 1.5V signal. DO NOT CONNECT A SIGNAL OUTSIDE THE 0V TO 5V RANGE!
Note that in order for this to work, you must run analogReference(EXTERNAL); before using analogRead(). Also:

After changing the analog reference, the first few readings from analogRead() may not be accurate.

Fore more information, see AnalogReference.
IOREF:
This is a voltage corresponding to the i/o of that board, for example an Uno would supply 5v to this pin, but a Due would supply 3.3v. Sending a signal to this pin does nothing.
Unlabeled pin:
This pin is unused, but is there to ensure compatibility with future products. It is not connected to anything on any R3 boards I have seen.

I agree with possibly using this pin directly from the 5V pin.  My Nano boards do not measure the same on the ADCs as the UNO boards.  It is somewhere below 5V that I get the 1023 reading.  I assumed they were already referenced to 5V but apparently that was wrong.  Thank you for the tip.

Concerning the AREF pin, you have to remember that the Arduino comes with a 10bit ADC (Analog-Digital-Converter), which converts incoming voltages between 0V and 5V to integer values between 0 and 1023. This results in a resolution of roughly 4.8 mV.
If a sensor only delivers a lower maximum voltage, it is resonable to apply this voltage to the AREF pin, just in order to obtain a higher resolution.

analogReference();

I agree with possibly using this pin directly from the 5V pin.  My Nano boards do not measure the same on the ADCs as the UNO boards.  It is somewhere below 5V that I get the 1023 reading.  I assumed they were already referenced to 5V but apparently that was wrong.  Thank you for the tip.  Upvote.


text:
What is the difference between the revisions of the Arduino Uno board?
There are three different revisions of the Arduino Uno. What changed in each revision?

UPDATE: I was given an UNO by my son which has A6 and A7 wired out to J2 pins 9 and 1. The normal size of J2 is 8 pins while this version has J2 and J3 combined as a single component. My best guess is that he bought this off an official Arduino site since that would be his philosophy plus the board says it is made in Italy. I took a photo but my wifi is not letting my cell phone connect to upload the photo right now. >:(

Here is a summary from the official site:

Revision 2 of the Uno board has a resistor pulling the 8U2 HWB line to
ground, making it easier to put into DFU mode.
Revision 3 of the board has the following new features:

1.0 pinout: added SDA and SCL pins that are near to the AREF pin and two other new pins placed near to the RESET pin, the IOREF that
allow the shields to adapt to the voltage provided from the board. In
future, shields will be compatible with both the board that uses the
AVR, which operates with 5V and with the Arduino Due that operates
with 3.3V. The second one is a not connected pin, that is reserved for
future purposes.
Stronger RESET circuit.
Atmega 16U2 replace the 8U2.

A more detailed list of changes can be found here.
R2:

The rotation of the ATMEGA8U2 (the little chip near the USB port) was changed by 45 degrees.

Four solder pads (JP2) were added, connecting to pins PB4 to PB7 of the USB ATMEGA."

Instead of R1's solder pads, R2 adds header pins to the USB ATMEGA ICSP.

An LED connected to pin 13 was added. It turns on when pin 13 is HIGH, off when LOW.

The main microchip was changed from an ATmega168 to an ATmega328.

A resistor was added between the DTR (HWB) line and the ATMEGA PD7 pin.

R3:

The rotation of the ATMEGA8U2 was changed back by 45 degrees.
The ATMEGA8U2 was changed to an ATMEGA16U2.
A diode was added, wired from +5vdc to the reset pin, cathode to +5vdc.

The 8 pin connector that contains Arduino pins 8 was changed to 13, GND and AREF for a 10 pin connector. The extra 2 pins are connected to AD4/SDA and AD5/SCL. Also, the 6 pin connector that has the reset pin connected to it changed to an 8 pin connector. One of the new pins on this header is the IOREF pin that allows shields connected to the board to adapt to the voltage of the board. The second pin is not connected and reserved for future use.

User Side Changes

Both revision 2 and 3 boards add four solder pads (JP2) connecting to pins PB4 to PB7 of the USB ATMEGA.
Revision 2 and 3 boards are both supplied with header pins in the USB ATMEGA ICSP header rather than just solder pads in the Arduino Uno.
The revision 3 board changes the 8 pin connector that contains Arduino pins 8 to 13, GND and AREF for a 10 pin connector. The extra 2 pins are connected to AD4/SDA and AD5/SCL. These are the two analog input pins that can be used for I2C.
Revision 3 boards change the 6 pin connector that has the reset pin connected to it to an 8 pin connector. One of the new pins on this header is the IOREF pin that allows shields connected to the board to adapt to the voltage of the board. The second pin is reserved for future use.

Electronics Based Changes

The Arduino Uno and Arduino Uno revision 2 both have an ATMEGA8U2 USB microcontroller on board – this is upgraded to an ATMEGA16U2 on the revision 3 board.
Revision 3 adds a diode across the USB ATMEGA reset pin pull-up resistor.
Both revision 2 and 3 boards add a 1k pull-down resistor to the DTR (HWB) line coming from the USB ATMEGA microcontroller – from the PD7 pin.
The Arduino Uno and Arduino Uno revision 2 both have a LED and resistor connected in series on Arduino pin 13. The revision 3 board buffers this LED/resistor through a unity gain op-amp. This is the spare op-amp that was unused on previous boards.

Sources:

http://startingelectronics.com/articles/arduino/uno-r3-r2-differences/


text:
How can I communicate from Arduino to MATLAB
I want to use sensors on an Arduino to control values in a MATLAB program. What are my options for communicating?
I've used Processing to receive data sent via the serial cable, and that strategy has worked pretty well. Is there something similar I can do using MATLAB? I'm somewhat new to MATLAB, so gentle guidance would be great.
I'm not really looking for something like the ArduinoIO package -- I want to have separate computation executing on the Arduino and occasionally informing my MATLAB program (which will occasionally poll the serial line, I suppose).

Do you need help writing the code for the Arduino, or help writing MATLAB code to read data input from the serial stream?

This question appears to be off-topic because it is about programming in Matlab.

The serial port is your best bet.  I would define a simple message format bases on your needs.  If you only are doing simple stuff like valve on/off: I would define a start byte followed by a fixed number of data bytes.  If you want to get more complicated send a length byte first, followed by that many data bytes.  Please remember: don't send serial bytes nonstop, always have a few breaks (sleep cycles) in the data which allows the serial chips to clock recover.

MATLAB Support Package for Arduino (aka ArduinoIO Package) allows you to do it fairly easily.

Sample usage:
%-- connect to the board
a = arduino('COM9')
%-- specify pin mode
a.pinMode(4,'input');
a.pinMode(13,'output');
%-- digital i/o
a.digitalRead(4) % read pin 4
a.digitalWrite(13,0) % write 0 to pin 13
%-- analog i/o
a.analogRead(5) % read analog pin 5
a.analogWrite(9, 155) % write 155 to analog pin 9

If I understand ArduinoIO correctly, all the computation is initiated on the Matlab side and the Arduino just becomes a sensor extension.  That isn't what I want.  I want to have a program on the Arduino (doing it's own computation) that occasionally communicates with Matlab.

The MATLAB side simply provides you with the functions to communicate with the Arduino. It's up to you how/when you want the two to communicate. The Arduino can write to the serial port and this allows you to read from it.

I don't know a whole lot about MATLAB, but I found some tutorials about reading and writing from the serial port:
s = serial('COM1');
fopen(s)
fprintf(s, 'Your serial data goes here')
out = fscanf(s)

out is now your received data, and you can do whatever you want with it.
To close:
fclose(s)
delete(s)
clear s

It is from Writing and Reading Data (MATLAB/ Data and File Management/ Serial Port Devices).
From your question I assume you know about the Arduino side of things (using Serial).

I've established a connection, sending numbers. By just changing Serial.write to Serial.print and fread to fscanf you can send/receive clear ASCII text instead of binary data.
Both matlab and arduino code can be found at this question:
https://stackoverflow.com/questions/24368670/matlab-plot-serial-data-continously

clc
clear all
global value
global value1
global val5
global val6
global val7
global val8
global val9
a=arduino('COM4');
   value = zeros();
   value1 = zeros();
   val5 = zeros();
   val6 = zeros();
   val7 = zeros();
  val8 = zeros();
  val9 = zeros();
for i=1:1000
val1(i)=analogRead(a,0)/2; %incomming
val2(i)=analogRead(a,1)/2; %heater
val3(i)=analogRead(a,2)/2;   %heat sink
val4(i)=analogRead(a,5)/2; %atmsphr
val8(i)=analogRead(a,6)/2; %pressure
val9(i)=analogRead(a,7)/2; %pressure
val(i)=analogRead(a,0)/2;
value(i)= (val1(i)+val4(i)+val3(i))/3;
value1(i) =(val8(i)-val9(i)); %pressure
val5(i)=analogRead(a,0)/2 %incoming
val6(i)=analogRead(a,4)/2 %outgoing
val7(i) = value(i)-val6(i)
    plot(value, 'r');
    title('heat sink temprature');
hold on

plot(val5, 'k');

title('incoming air temprature');
plot(val6, 'g');

title('outgoing air temprature');

 plot(val4, 'k');
 title('atmospheric temperature');

plot(val7,  'c');
title('change in temprature');

pause(6)

figure
plot(value1,  'r');
title('change in pressure');

pause(6)

end

Providing a code-answer without an explanation on what it does it's not a valid answer here on StackExchange. Can you edit your post providing some informations?


text:
Programming options other than C++
Can I program my Arduino using any programming language other than C++? If so, which programming languages? What software would I need for compiling and loading my code onto the Arduino?

Related: http://arduino.stackexchange.com/questions/105/programming-an-arduino-using-python-rather-than-c-c

Unfortunately, this is an effective duplicate of an non-Arduino.SE question: see here  I think the question I linked should be moved here after beta ends, but not just yet.

@anorton That question is asking about alternative IDEs. This question is not a duplicate because it talks about alternative programming languages.

@user2202326 Sorry... I seemed to recall more people responding with different languages than IDEs on that thread, but, apparently, I was wrong.  Carry on.

You could look into Netduino if you are familiar with C# (Visual Studio is the way to go, but there are other ways to compile C# code). I don't know what board you have and if it is compatible though. http://netduino.com/

Some commonly known ones:

Ada
Basic
Forth, alt, alt
Java
Pascal
Python
C (mac) and C (Windows)

In theory you should be able to extend avr-gcc to support other languages, though this is no small undertaking. I should also caveat that support for languages other than C typically comes with some fairly weighty restrictions on language components -- for instance, even with C++ it's discouraged to be instantiating new objects as malloc and free are extremely expensive in both memory space and cycles.
Besides using Google, the following references are applicable Click Here.

In theory, any compiler which outputs AVR assembly could be used (modulo limitations on code size, ram usage etc).
AVR backends exist for both LLVM and  GCC -- so in theory, with some effort, most languages which are supported by LLVM and GCC's front-ends could be compiled to AVR. A big question will be library support, etc.
Never the less, here's a couple of odd choices for the spirit of the question, rather than its letter [1].

AMForth, a forth dialect can be flashed onto an Arduino.
AVR-Ada: Ada for AVR micro-controllers.
BASIC: Bring back the Goto!

Oh, and you could write raw AVR Assembly!
[1]- I Haven't tried these though!

There are also some people working on Javascript node.js based systems. One that is already publicly available is Espruino and another is Tessel which launches in spring 2014.

I'm surprised that nobody has mentioned AVR Assembly!
Assembly is not often thought to be the most interesting, or even an easy method of programming, but it's nonetheless, 100% possible with all AVR based arduino. SAM boards will likely not work with this flavor, but it's still possible to use assembly in their programming.
All Arduino boards (as of posting) support assembly programming via Atmel Studio, The SDK made for Atmel based chips.
Assembly is naitively supported by all Atmel devices, and requires no boot loader in order to work, so all programs are inherently real-time.

Note that assembly is also supported by the gcc toolchain, which is included in the Arduino IDE install.

@EdgarBonet Correct, which is why the __asm__("Assembly code here") works to add in-line assembly to any sketch. For most programs, this is a bad idea, however, as it's difficult to achieve platform independence with this method.

Because avr-g++ should support all standard C / C++ constructs it is possible to code inline assembly. More info on this arduino.cc forum thread

Inline assembly isn't part of the C/C++ standards, but gcc and the microsoft c compiler support it, although incompatibly.

true, and so do the avr_gcc.

Nothing beats writing executable code in hex anyway.

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


text:
Code for one-time execution in Arduino
Question: Where do I put code if I want it to execute only once per Arduino startup?
Background: I tend to use my Arduino to perform tasks that should be executed once per power cycle.  (For example, my robot should only drive forward once every time I turn it on--more than that, and it might fall off the table.)
The standard Arduino IDE "template" consists of a loop() and a setup() function.  The setup code is run once per power cycle, and the loop is re-started every time it finishes.
I see two approaches to code "1 time tasks:"
Method 1: "Loop once"
void setup() {
  //do setup stuff
}

void loop() {
  //do task

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

Method 2: "Setup only"
void setup() {
  //do setup stuff

  //do task
}

void loop() {
  //do nothing
}

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

Some use of the exit command is discussed in http://arduino.stackexchange.com/questions/188/what-happens-when-i-call-exit-from-my-program

I'm kind of confused by your question. You ask where you want to put once-per-startup setup functions, and then discuss the setup function. That's what the setup function is for.
As such, one-time setup functionality goes in the setup function.
FWIW, if you look in the file that calls the setup and loop functions:
#include <Arduino.h>

int main(void)
{
    init();

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

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

For all intents and purposes, the two options are completely identical. Either way, you get a empty busy-wait loop. Frankly, I'd expect the two different options to probably emit the same machine code anyways, so the whole thing is a non-issue.
Note:
if (serialEventRun) serialEventRun(); appears to be a facility to allow you to attach a function that is called upon reception of serial data, but if you do not define a function void serialEvent(){} in your code, it will compile out completely and not be present in the produced machine code.

It feels weird to accept an answer that isn't (yet) the highest-voted.  But, seeing the main() function definition was really helpful to my question.  (And, you do indicate a consensus with the group with using setup instead of loop).  Thank you for your help.

@anorton - When in doubt, look under the covers. I find the arduino platform convenient for prototyping, but it's largely just boilerplate code. Understanding what it's doing can be tremendously helpful in deciding how to architect something.

I usually go with Method 2, but end up doing this:
void setup() {
  //do setup stuff

  //do task
  init(); //Do start-up initialization steps
}

void init() {
  // do tasks on startup
}

void loop() {
  //do looping code
}

With the above setup it allows my code to be even more organized.

the best answer so far +1, thanks dude you saved me!

I would strongly prefer Method 2. If you ever plan to add code to handle input, output, etc,  it's easy with Method 2 -- just fill in loop(), but requires reworking/refactoring in Method 1.

There is no time limit on the setup function. I prefer method 2 because the loop can be filled with whatever you need to later.

Definitely go with method two. That's what the setup function is there for. It's much easier to read as well. Anything in the loop() implies it will be run in a loop.

As most other answers, I would go for method 2.
But I would try to avoid the call, by Arduino library, to an an empty loop() that makes the Atmel consume "a lot" of current for nothing.
Edit:
As some comments pointed out though, using delay() in loop() will change nothing to power consumption.
Hence, if you would like to reduce power consumption once your setup() has run, you will have to play with Atmel sleep modes.
You can take a look at this article that shows how to deal with sleep modes from your Arduino sketches; it does more than just putting the Atmel to sleep but it is a good (and simple) read if you want to play with sleep modes.


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

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

Before you do anything to your board, as with most electronics, turn them off before you start tinkering with them. Do this as well when you are setting up wire and adding components, you don't want to accidentally short anything. With Arduinos it is like any other electronics device, keep away from water, protect it from falling/hard collisions, make sure you have been grounded before touching components or wires, etc.
Try not to let the magic smoke out

One quick tip that I saw someone mention before: don't turn on your Arduino when it's resting on a conductive surface: the soldered pieces on the back of the circuit board could short out. ;)

@anorton Actually one of the first things I do with an Arduino is attaching some stick-on feet or couple screw feet under them to protect my desk from being scratched and prevent the Arduino from touching anything metal on my desk. Apart from being safe, it also looks good.

First step is read the manual!

If the board is mounted on a metal frame, perhaps on a robot, and you're drilling new holes into the frame, then make sure the board and all electronics are covered with a cloth, to prevent getting metal chips in places they should never go.

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

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

For keeping people safe:

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

Know where the fire extinguisher is. Wow... I don't know that I would go that far.

Depends what you're doing @AnnonomusPerson.  If you're just writing code to blink an LED, and you're powering off of USB, a fire is unlikely.  Working with soldering irons, rechargeable batteries, or high-current bench supplies makes fire a real danger.

@AnonymousPenguin "Knowing where the fire extinguisher is" is pretty recommended even if you don't work with Arduinos.

One of the most common bad things I have seen is connecting LEDs directly to addition pins without a current limiting resistor.
Basically, in electronics there are a few main sources of problems. Too much current, too much voltage, overheating, and physical damage.
Too much current usually comes from shorting things, too much voltage(or reversed polarity) usually comes from not paying attention to what is being connected, overheating comes from too much current or not using a heatsink when you should be.
Basically, just think before you connect things and you'll be fine. Learn some basic circuit theory if you haven't already, get in the habit of knowing the ratings of the parts you want to use, and double check stuff before turning it on.
I like this list here of things not to do: http://ruggedcircuits.com/html/ancp01.html


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

I would suggest that the title and question is either changed to be "Arduino Uno", or the tag "uno" is removed and the question made more generic.

See also https://arduino.stackexchange.com/a/13293/39212 for several more checks.

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

Plug the board into a USB port on your computer and check that the green LED power indicator on the board illuminates. Standard Arduino boards (Uno, Duemilanove, and Mega) have a green LED power indicator located near the reset switch.
An orange LED near the center of the board (labeled “Pin 13 LED” in the image below) should flash on and off when the board is powered up (boards come from the factory preloaded with software to flash the LED as a simple check that the board is working).

If the power LED does not illuminate when the board is connected to your computer, the board is probably not receiving power.
The flashing LED (connected to digital output pin 13) is being controlled by code running on the board (new boards are preloaded with the Blink example sketch). If the pin 13 LED is flashing, the sketch is running correctly, which means the chip on the board is working. If the green power LED is on but the pin 13 LED is not flashing, it could be that the factory code is not on the chip. If you are not using a standard board, it may not have a built-in LED on pin 13, so check the documentation for details of your board.
Online guides for getting started with Arduino are available at for Windows,  for Mac OS X, and for Linux.

Note: This will work only if the USB port or the FTDI chip have not been burnt. The Atmega chip could be functioning correctly even if these two components are not.

+1 Right on, Hardik! Funny thing is that just yesterday someone asked a question about a problem with their Arduino and I wanted to point it to your answer. Now we can do it properly.

@Ricardo : Bingo :P

If you reset the board (with the button), the bootloader usually flashes the pin 13 LED

My first board was a Duemilanove and came with a dead FTDI chip. Was very frustrating until I got a working replacement board.

Supposed one owns a USB programmer, there's another way to inspect the Arduino.
Connect the programmer to the ICSP pins of the Arduino and call avrdude with the right parameters to read the fuses of your Arduino.
avrdude -c programmer-id -p partno -P port

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

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

The UNO board responds with the correct signature and is ready for some action :)
How to connect?
My USB programmer came with a 6-wire ribbon cable with 2x3 female connectors on both sides. As usual, the wire for pin 1 is marked red. Due to a notch in at the 2x3 male connector of the programmer, the cable only fits here in one direction.
If you look at the Arduino UNO, the ICSP header is to the right of the reset button.
The pinout is as follows.

MISO  1    2 VCC
SCK   3    4 MOSI
RESET 5    6 GND

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

This won't test the USB->Serial interface however.

@Cybergibbons Absolutely true! But even with a fried USB, there might still be a chance to flash the Arduino using the programmer then ;)

+1 Good to know! Will put my 3 dead ATmegas through this test. Do you know how to check the fuses using an Arduino UNO as a programmer, with the ArduinoISP sketch loaded?

If you have another, working, Uno, and both have socketed microcontroller chips, you could use the known board to program a test sketch onto the unknown board's chip, put it back on the unknown board, and run it.
I like the following (pseudo-coded) test sketch for quick-checking my hand-built boards; it's just as handy for testing an unknown factory-built one. It's not an exhaustive test, it just checks for basic digital I/O, serial I/O, and shorts or opens:
forever,
  for each digital I/O pin:
    write high;
    delay 100ms;
    write low;
  end;

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

A test LED - an LED with its resistor soldered to it - connected between any I/O and ground should blink every 2 seconds. If it doesn't, that pin may have failed or have a bad connection.
Two test LEDs connected to numerically adjacent pins (they may not be physically next to one another) should blink in sequence. If they blink together, it indicates a short, probably a solder bridge, between them.
The terminal should say "Hello World!" every two seconds. If not, that pin or the FTDI cable or on-board USB/Serial chip may have failed.
Type something on the keyboard and it should be repeated back to the serial terminal (if the previous test passed). If not, again that pin or the FTDI cable or on-board USB/Serial chip may have failed.


text:
Connecting breakout board to Arduino with UART
I'm using a DigiX (Arduino Due based 3.3V) board to connect to a GPRS/GSM SIM908 breakout board. The SIM908 EVB board has the following pins on its RS232:
I've got all three UART TX lines hooked up to the RX Lines (and RX to TX) on my Arduino but the board keeps resetting, which I would guess is some sort of voltage issue (I turned the board off immediately). However there are three MAX3232s on the underside of the board, which I thought would have made it so I could just connect the lines directly to the Arduino. Does anyone know why this might be happening or how to properly connect these two devices?
Additional info:
Pinout of the DigiX.
Schematic of the DigiX.
(The below links are in Chinese):
Here is a SIM908 Hardware guide.
The full schematic of the breakout board.

Both the DigiX and the SIM908 are natively 3.3V boards. They should be able to connect to each other directly.
For some reason, the SIM908 breakout seems to only offer RS232 level serial outputs for the GPRS and GPS. On U3 (the SIM908 module itself) Pins 68/71 offer 3.3V levels for the GPRS (GPRS-TXD and GPRS-RXD) and 15/16 offer 3.3V levels for the GPS (GPS-TXD and GPS-RXD).
These are converted to RS232 levels by the MAX3232 and presented on J3 and J13. I can't see any point where the 3.3V signals are presented on a connector.
You could either:

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

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

Thanks for the answer. I dont want to modify the SIM908 board so I'm going to go with building or buying a level converter. I'm assuming I can go with 3x something like these http://www.ebay.com/itm/5-x-Mini-RS232-to-TTL-Converter-Adapter-Module-Board-MAX3232CSE-3-5V-120kbps-/330611479927 Or even building my own http://sodoityourself.com/max232-serial-level-converter/ just without the actual serial port? Will I need to have one of these for each RX and RX line (so 6 total)?

Both of those solutions would work. They are bi-directional and have two TX/RX pairs each, so you would only need 2 boards (1.5, sort of).


text:
How do I use I2C devices with Arduino?
I have a few useful I2C components, such as a 16-bit port expander (MCP23017), which I'd like to use in various projects.
What do I need to do to make these work with Arduino? Will it work with any Arduino, or do I need a specific board or shield?

Arduino have the Wire Library that communicate with I2C.

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

Board   I2C / TWI pins

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

You can take a look at , this examples.
Like @TheDoctor said:

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

Don't forget pullup resistors on the I2C lines

To expand on that, the i2c data lines both need resistors to 5v. This keeps them from drifting if they are disabled. Andy resistor value should work, but it is recommended to use one between 10k ohm and 47k ohm

It should be said that if you use 5V pullups on the Arduino due (which was named in the answer) you have damaged the board.
The Arduino Due uses 3.3V logic and it does NOT need 5V pullups, also SDA and SCL are already pulled up internally by the board.

Additional shields are not needed.
You only need the Wire library and a couple of wires to connect the device to SDA and SCL.
The position of these pins is different on the various Arduinos, please have a look here.

For future readers: use the Adafruit_MCP23017 library.


text:
Why can't I declare a class in another tab in Arduino IDE?
I wanted to move some of my code out into a second tab in the Arduino IDE, to keep things better organised. At first, I only tried moving a function, and it seemed to work fine. I could call the function from the setup() function in my main tab, and there were no problems compiling or uploading.
However, I tried putting a whole class into the second tab, and suddenly it didn't work any more. For example:
Tab 1:

TestClass obj;

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

void loop()
{
    //...
}

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

When I tried to compile this, it gave me the following errors:
tab1:1: error: 'TestClass' does not name a type
tab1.ino: In function 'void setup()':
tab1:5: error: 'obj' was not declared in this scope

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

Is this the entirety of the code? What are the file names? Are there no preprocessor directives like #include?

Yes, that's the entirety of the code. The tabs are named tab1 and tab2 respectively. The names were set using the IDE, so the underlying files are both .ino.

I am starting to hate the jiggery pokery the Arduino IDE does. What it adds in ease of use over AVR it takes away in breaking things like this.

It is not possible to declare and use classes declared in one .pde file in another .pde file from within the Arduino IDE.
One workaround is to make the second file into a C++ source file (.cpp) and then add a #include "<filename>" directive in the beginning of the first file.

This code compiles correctly:
Tab 1:
#include "test.cpp"

TestClass obj;

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

void loop()
{
    //...
}

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

Thanks for the workaround. It works for the basic example, but unfortunately it doesn't work if I add any Arduino-specific calls in the .cpp file. For example, if TestClass::init() tries to call pinMode(), the compiler complains that pinMode was not declared in this scope. Is there a way to access the Arduino functions in my class?

@PeterR.Bloomfield Add a #include <Arduino.h> to the top of the .cpp file.

I think it's not good to teach others to include source files (#include "test.cpp"). It works, but may brake the understanding of the linking process. Only header files should be included.

I agree with @Mars - a better solution is to put the class declaration in a .h file, and the definition (implementation) in a .cpp file. So you have two extra files in the project. This is actually the normal way of handling classes.

The way the Arduino IDE works is that it compiles your code (the code you write in the IDE) as the "main" code. Then it pulls code from all of the libraries you have imported and compiles that along with the main code. To do what you are suggesting would require you to create a library for Arduino.
Here is some more information on Arduino libraries:
http://arduino.cc/en/Guide/Libraries
And here is some on how to create a library:
http://arduino.cc/en/Hacking/LibraryTutorial //this one is the easiest to understand imo
http://playground.arduino.cc/Code/Library
http://www.divilabs.com/2013/03/write-your-own-arduino-library.html#
Here is an example library I wrote https://github.com/jamolnng/Arduino/tree/master/libraries/ShiftRegister as you can see there is no problem with calling Arduino functions from the .cpp file (I know, I've tested the library)

It’s also possible to just create .h and .cpp files in your main project, without having to create a separate library.


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

And yes, usually the Nano is hanging in free space by its wires (yes I know, quick and dirty, should be using something cleaner, even for prototypes).  So I'm hoping for the best of both worlds, sturdy "enough" to stay attached, yet possible to remove and switch around.  Having no luck finding such advice on the internet, perhaps searching for the wrong terms.
EDIT:  I neglected one important point, each wire is attached individually just like the SparkFun wires with the female header as mentioned in @TheDoctor's answer below.

Not sure exactly what you're looking for.  Dupont connector, maybe?

What about a breadboard? They're useful so the wires are a little more secure.

Don't forget about soldering. It is a time proven semipermanent to permanent way of attaching wires.

You are trying to do something in a harder and less effective manner than you could be. Yes, there are ways of doing what you want. No, it is almost certain that not using a breadboard makes sense. There may be constraints which make various solutions unsuitable but, if so, you should include them in your question.

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

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

The row of female headers, shown in the second link, is the way to go, since the individual wires have a tendency to pop out every now and then, whereas the entire row is much more secure.

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

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

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

From Gravitech's webpage for the Nano:

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

If you have a Nano in such a dangling state, then you are using the wrong sort of Arduino board for the wrong purpose.
Obviously a Nano will work just fine when loose on a surface, i.e. not plugged into a breadboard, but that is not what it was intended for, and maybe you should employ an UNO in its place.
However, if you have to use your Nano without a breadboard, then in addition to the wire wrapping, wires with female DuPont connectors, or female header strips, you could just solder wires to the holes in the nano board, if you do not already have header pins already soldered in to them.

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

Ooh! that's pretty.


text:
How do I print multiple variables in a string?
Say I have some variables that I want to print out to the terminal, what's the easiest way to print them in a string?
Currently I do something like this:
Serial.print("Var 1:");Serial.println(var1);
Serial.print(" Var 2:");Serial.println(var2);
Serial.print(" Var 3:");Serial.println(var3);

Is there a better way to do this?

An idea, but I don't know if it would work, is some modification of this... Again, I don't know if this is supported on Arduino: http://stackoverflow.com/questions/804288/creating-c-formatted-strings-not-printing-them

ardprintf is a function that I hacked together which simulates printf over the serial connection. This function (given at the bottom) can be pasted in the beginning of the files where the function is needed. It should not create any conflicts.
It can be called similar to printf. See it in action in this example:

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

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

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

  delay(5000);

}

The output as expected is:
test 2 123456789 g test 2.30

The function prototype is:
int ardprintf(char *, ...);

It returns the number of arguments detected in the function call.
This is the function definition:
#ifndef ARDPRINTF
#define ARDPRINTF
#define ARDBUFFER 16
#include <stdarg.h>
#include <Arduino.h>

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

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

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

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

Now, available on Github gists.

Nice idea, although I felt it could be more minimalist, so I rewrote this version to one without buffering. Anyone interested can check out the gist: https://gist.github.com/EleotleCram/eb586037e2976a8d9884

I wouldn't normally put two answers to a question, but I only just found this today, where you can use printf without any buffer.
// Function that printf and related will use to print
int serial_putchar(char c, FILE* f) {
    if (c == '\n') serial_putchar('\r', f);
    return Serial.write(c) == 1? 0 : 1;
}

FILE serial_stdout;

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

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

    printf("My favorite number is %6d!\n", 12);
}

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

This still has the floating point limitation.
I thought I would do a little testing on this, and it works quite well. I added a better test to the loop with formatted output.

Oh man, that's cool. printf is a whole lot safer than sprintf. It gives you format strings for free, which is great. Cool trick. Thanks. (Voted)

One question: In your serial_putchar function, why not make the return statement return !Serial.write(c);? Isn't that cleaner than a trinary operator for inverting the sense of a boolean return value?

That's a good point and I like it. The code wasn't mine and I pasted it as I found it.

Thanks for the serial_putchar function. It works a treat. :-) Can you fix the floating point limitation?

I only use this for debugging but:
int a = 10;
int b = 20;
Serial.println("a = " + String(a) + " and b = " + String(b));

what is String$?

LMFTFM (Let me fix that for me).

This is probably not better, just different.
You can use the String object for output. These objects allow concatenation and support automatic typecasting.
Serial.begin(9600);
String label = "Var";
const byte nValues = 3;
int var[nValues] = {36, 72, 49};

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

Obviously it's important to be careful of memory limits. Lots of concatenations and other string operations in one place can use a surprising amount of space.

@PeterR.Bloomfield Absolutely true! That's the reason why I mentioned that this variant isn't better ;)

I usually used Tabs to make things line up better in the Serial. Having things line up like I do allow the arduino to fire as fast as possible while being able to notice certain changes in the variables.
Try something like this:
Serial.println("Var 1:\tVar 2tVar 3:");
Serial.print("\t");
Serial.print(var1);
Serial.print("\t");
Serial.print(var2);
Serial.print("\t");
Serial.print(var3);
Serial.println();

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

Honestly, I do the same ("\t" and "\n") and normally avoid the code-bloating String object bells and whistles.

@KlausWarzecha, I rarely give the variable name as they're in nice columns. Also make it easier to see random print outs that don't match this syntax

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

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

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

....

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

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

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

The above solution from Iain increases code size.

I like this method and I use it a lot. I'm giving you a plus 1.

I usually (painfully) stick with multiple lines of Serial.print but when it becomes convoluted I go back to sprintf. It's annoying in that you have to have an available buffer for it.
Usage is as simple (??) as:
char buffer[35]; // you have to be aware of how long your data can be
                 // not forgetting unprintable and null term chars
sprintf(buffer,"var1:%i\tvar2:%i\tvar3:%i",var1,var2,var3);
Serial.println(buffer);

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

sprintf is a horrible abomination. Not type safe, easy to overrun your buffers, etc, etc. It's a tool from the 1960s. That said, I use it too, but it is not for the faint of heart....

To avoid overrun, use snprintf... BTW most of the moder IDEs (NOT the Arduino IDE) will check the string format against the provided variable types, and will throw a warning.

The usage will depend of the data type of your variables.
If they are int, it would be %d or %i
If they are string, it would be %s
Wrapper for printf
You can change the limit based on your requirements
#include <stdarg.h>
void p(char *fmt, ... ){
    char buf[128]; // resulting string limited to 128 chars
    va_list args;
    va_start (args, fmt );
    vsnprintf(buf, 128, fmt, args);
    va_end (args);
    Serial.print(buf); // Output result to Serial
}

Source: https://playground.arduino.cc/Main/Printf
Usage examples:
p("Var 1:%s\nVar 2:%s\nVar 3:%s\n", var1, var2, var3); // strings
p("Var 1:%d\nVar 2:%d\nVar 3:%d\n", var1, var2, var3); // numbers

ESP8266
Its built-in in Serial class of the framework. No need for additional library or function.
// strings
Serial.printf("Var 1:%s\nVar 2:%s\nVar 3:%s\n", var1, var2, var3);
// numbers
Serial.printf("Var 1:%d\nVar 2:%d\nVar 3:%d\n", var1, var2, var3);

More details about formatting tips on the printf format reference page : http://www.cplusplus.com/reference/cstdio/printf/
\n is the escape sequence for the line feed.

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

Source: http://en.cppreference.com/w/cpp/language/escape
[EDIT]
- As @Juraj mentioned, it's not available on most of the AVR modules. So I added ESP8266 mention and a printf wrapper for common AVR modules

this is not true. there is no Serial class. printf would be in Print class, but it is not in the most used AVR package

@Juraj you are right, I've only tested it on ESP8266 which have it (link) and thought it was from arduino core. Will update my answer accordingly

for the p function I would add one more downvote if it was possible.

this is an old question and I can\t judge the old answers because I don't know what was available in 2014. but now there are libraries for wrapping a Print stream in a Print stream with printf implementation.

Using Streaming.h, in place of
Serial.print("Var 1:");Serial.println(var1);
Serial.print(" Var 2:");Serial.println(var2);
Serial.print(" Var 3:");Serial.println(var3);

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

The definition of << in Streaming.h in effect translates that into a series of ordinary Serial.print() calls.  That is, << is syntactic sugar, implemented without increasing code size.
If you don't have Streaming.h installed, get Streaming5.zip from arduiniana.org.  Unzip it in your libraries directory, for example in ~/sketchbook/libraries.  Add the line #include <Streaming.h> within sketches where you use << as a stream operator.
Base-conversion specifiers _HEX, _DEC, _OCT, and _BIN are provided, as well as a _FLOAT function (with number of decimal places) and endl.  For example, to print latitude and longitude values in a form like "Your coordinates are -23.123, 135.4567” one could write:
Serial << "Your coordinates are " << _FLOAT(latitude,3) << ", " << _FLOAT(longitude,4) << endl;

This could also be written as
Serial << F("Your coordinates are ") << _FLOAT(latitude,3) << ", " << _FLOAT(longitude,4) << endl;

which would keep the longer string in PROGMEM instead of bringing it into RAM.
Note, Streaming.h  doesn't build any strings as such; it just delivers the text of its <<-arguments to a stream.  A PString class at arduiniana can build strings from stream inputs, if strings instead of streamed output are desired or needed.

From http://playground.arduino.cc/Main/Printf
I observed this is working fine on my mega2560
That's all it just worked, no need for vsnprintf_P or PROGMEM ...
#include "Arduino.h"
void local_printf(const char *format, ...)
{
static char line[80];
va_list args;
va_start(args, format);
int len = vsnprintf(line, sizeof(line), format, args);
va_end(args);
for (char *p = &line[0]; *p; p++) {
    if (*p == '\n') {
        Serial.write('\r');
    }
    Serial.write(*p);
}
if (len >= sizeof(line))
    Serial.write('$');
}

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

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

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

Why would anyone want to do this instead of just using printf() itself?

I've been using PrintEx for years, and it works great.  See enter link description here

I also have been using PrintEX for years and I agree is almost bulletproof.  However, you should know that the Teensy 3.x/4.x MCU's from Paul Stoffregen' store (https://www.pjrc.com/store/teensy32.html) have Serial.printf built into their TeensyDuino package.  Teensy 3.2s are as cheap as, or cheaper than  Arduino's and run MUCH faster as well.  I have dozens of these MCU programmed into various projects around the house and have had very few problems with them.

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


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

http://electronics.stackexchange.com/questions/28211/backup-avr-with-avrdude but as others say, this only spits out .hex files, not the originating C source.

Cross site dupe: http://reverseengineering.stackexchange.com/q/125/189

It should be possible as long as the security bit isn't set. This question was asked on EE a while back.
Is it possible to extract code from an arduino board?
But you won't get the Arduino code you wrote back. The code is compiled into assembly and you'll have to convert that back to C yourself.

Reading back the raw hex:  http://forum.arduino.cc/index.php?topic=6150.0  and Automatic Disassembly:  http://forum.arduino.cc/index.php/topic,46843.0.html

This answer doesn't directly answer the question, but still will result in the same end result.
The Arduino IDE uses temporary directories to store build files, including the original sketch as well as the HEX and intermediate files.
On a Mac, these are in /var/folders by default, and on a Windows machine they are in …\Local Settings\Temp\ (which depending on the version of Windows could be in several places).
I've found that especially in Windows, these build files don't get deleted when you close the sketch or IDE, so they may exist on your machine for far longer than you would think.
Also, by default, Crashplan, Backblaze and Time Machine back-up these locations, so even if they have been deleted, they may still be in a backup.
The advantage here is that you will recover C code rather than ASM.

This is the best solution IMHO. Very creative, too...

You may find this in /tmp/ directories on Linux (and even Mac). c.f. https://www.arduino.cc/en/Hacking/BuildProcess

Comment echo from the accepted answer:  Reading back the raw hex:  http://forum.arduino.cc/index.php?topic=6150.0  and Automatic Disassembly:  http://forum.arduino.cc/index.php/topic,46843.0.html

I assumed you checked the trash. I use Linux mint and my last program was here: "/tmp/arduino_build_699749/preproc/ctags_target_for_gcc_minus_e.cpp" That was the original source file I compiled a few days back. Note I have not compiled anything since. I found the original /tmp/arduino_build_699749/sketch/myfile.ino.ccp. This probably will not help you but it probably help others. Remember go after it before compiling anything else.

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

There are no disassemblers for arduino, because it is not a MCU type. There are multiple ATmega disassemblers (google atmega disassembler).

If you have the arduino envitonment, you already have avr-objdump as it comes with avr-gcc.

Reading back the raw hex:  http://forum.arduino.cc/index.php?topic=6150.0  and Automatic Disassembly:  http://forum.arduino.cc/index.php/topic,46843.0.html

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

Unless your objective is to simply copy the identical code to another device, the simple answer is: no
As has been pointed out in other answers, you can turn the hex code on the device back into assembler code.
For example (once you have copied the code from the device back onto your disk):
avr-objdump -j .sec1 -d -m avr5 yourFileHere.hex

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

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

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

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

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

Upload:
Use w (write) instead of r (read) for the -U option.
More details at manual - avrdude Option-Descriptions.

Example:
Download UNO v3 (ATmega328) flash ROM (bootloader) given port /dev/ttyACM0 as Intel HEX:
avrdude -c arduino -P /dev/ttyACM0 -b 115200 -p m328p -U flash:r:SaveFlash.hex:i

If used directly from from the arduino IDE archive also add:
-C path-to/arduino-V/hardware/tools/avr/etc/avrdude.conf

Another approach might be to treat the program onboard the Arduino as a black-box exercise. That is, run the program and take careful notes of what happens (via Serial Monitor or whatever). If, in fact there is any output that you can observe, make it a task to create your own new code to emulate what the program DOES. This won't be productive unless the original programmer liberally included Serial.print() statements throughout the code, something I STRONGLY RECOMMEND as a programming habit to develop. Doing so, facilitates just the exercise I am suggesting. (Ask me why I developed that habit for everything I have coded for the past 30 years.)
Unfortunately, most people sprinkle a few comments here and there, which is helpful 5 years later if you have the source code. Personally, I comment EVERY LINE of source code. But comments in the source don't help later in this sort of situation, as the compiler doesn't put them in the machine code it generates. (Perhaps that might be a valuable option for the compiler. Yes, it takes bytes, but how valuable might it be years later for an important project?)
My two cents worth, which probably is worth the price the reader of this post paid to see it!


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

If budget wasn't an issue you can use bluetooth or xbee chips. They're not too bad, but will run a total of ~$60 as you'll need 2.

@Steven10172 Bluetooth devices are handy, but it seems like the OP wants a cheap solution without shields (low profile maybe?)

Make sure to connect the grounds if your medium of transfer is electricity!!!

Related: Sending minimal data between two Arduinos far away from each other

For long distance wired communication, look at RS-485.

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

You can use the MAX485 chip. It's pretty easy to work with but there's a good library as well:
https://github.com/Protoneer/RS485-Arduino-Library

Couldn't he just strip the wires in RS-485 or similar and just use that for serial to save money? 9600 baud doesn't run nearly as fast as 2 MBPS. Is there something special about the protocol/voltages/etc. that makes it suitable for long distances? It might save some money...

It's a differential signal sent over a twisted pair. Reduces noise. http://en.wikipedia.org/wiki/Differential_signaling

This page is an excellent resource on RS485 with Arduino http://www.gammon.com.au/forum/?id=11428

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

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

Between more than 2 devices

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

There are other methods available, but these listed only require a minimum of external hardware.
For distance ratings, see http://forum.arduino.cc/index.php?topic=82937.0 and http://www.tldp.org/HOWTO/Remote-Serial-Console-HOWTO/serial-distance.html
These data rates are directly controlled in Serial and can be tweaked in many others.

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

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

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

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