text:
Arduino Time Clock Accuracy
I'm currently trying to create an Arduino time clock by using the PJRC Time library (http://www.pjrc.com/teensy/td_libs_Time.html). I know that since most of the Arduino boards are running with a 16MHz clock and a single resonator, the time can become "out-of-sync" after a certain period of time.
However, I was wondering if anyone has an idea about the accuracy of the Time library when used on the Arduino DUE with a 84MHz clock. I've been testing it out and so far, the clock has been kept in sync for a few hours. Thanks!

The limitations of accuracy of the library depend on accuracy of the crystal. Let's say you have a crystal that is off by .5 second every hour, great for short term, but if you expand that over a year it is over 1 hour off by that time. If you want something to keep an accurate time over a long period I suggest a real time clock (they still have inaccuracies), a GPS module, or an internet connect to sync with.

@jamolnng Thanks for your answer. Do you know the accuracy of the crystal on the Arduino DUE or where I could go about finding it?

The best accuracy you are going to get is 84MHz, when they make, or cook, the crystal they can only make it to a certain degree accurate, also the environment of the crystal (temperature, humidity, etc.) play a role in the accuracy of it.

@jamolnng So can I expect a higher accuracy with the 84MHz crystal rather than the 16MHz crystal on most other Arduinos?

Not necessarily because if the 84MHz and the 16MHz both have the same amount of inaccuracy per clock cycle then the 16MHz clock would have a smaller inaccuracy at the end because it did less cycles. The frequency of the crystal is more for how fast the processor is

"The best accuracy you are going to get is 84MHz" - that doesn't make much sense to me!

He was looking for the exact frequency of the clock crystal including its defects. Appears it is to late to edit...

The Due has an RTC but no pins to add an external battery to keep it running.

The limitations of accuracy of the library depend on accuracy of the crystal. When they make, or cook, the crystal they can only make it to a certain degree accurate, also the environment of the crystal (temperature, humidity, etc.) play a role in the accuracy of it. Let's say you have a crystal that is off by .5 second every hour, great for short term, but if you expand that over a year it is over 1 hour off by that time. If you want something to keep an accurate time over a long period I suggest a real time clock (they still have inaccuracies), a GPS module, or an internet connect to sync with.
For further information look at the wikipedia article on quartz crystals
The use of a 84MHz crystal versus a 16MHz crystal will not necessarily improve the accuracy of the Arduino clock since the frequency of the crystal is more an indicator of processor speed than accuracy. The accuracy of the Arduino clock is primarily dependent on the accuracy of the crystal oscillator.
EDIT: I am no expert on crystal oscillators so if you see anything wrong here please let me know

Re-visiting an old question... as I found a very informative blog post
that sheds new light into it. But let me first provide some context
before giving the link.
When assessing the quality of a time base, be it a crystal, a ceramic
resonator or a lab-grade frequency standard, there are two notions that
should be distinguished:

accuracy: how close is the frequency of the time base to its
nominal value
stability: how much does that frequency drift over time

Accuracy is important if you want your clock to give correct time “out
of the box”. However, if you are willing to spend some time calibrating
your clock, then you do not really care because you are going to
calibrate out any inaccuracy you measure. jfpoilpret's answer provides
an example of a “manual” calibration protocol, which is by necessity
quite lengthy. If you can borrow a GPS module with a 1PPS output, the
calibration could be done in a few seconds.
Stability is a more serious issue. If the frequency of the time base
drifts randomly, this will defeat your calibration efforts. Essentially,
the calibration will tell you how fast or slow your clock is running
right now, but it will not allow you to predict how fast or slow it
will run in the future.
Here is the promised link: Arduino clock frequency
accuracy, by Joris van Rantwijk.
What Joris did is measure the accuracy and stability of an Arduino Pro
Mini (clocked off a ceramic resonator) and an old Duemilianove (quartz
crystal). From my perspective, the main takeaways are:

both clocks are grossly inaccurate, thus both would need user
calibration in order to be used as timepieces
the quartz crystal of the Duemilianove has decent stability, better
than 1.5e-8 at 6 h averaging time
the stability of the Pro Mini’s ceramic resonator is pathetic, more
than two orders of magnitude worse than the crystal, which makes it
essentially useless as a time piece

Here is his Allan deviation plot, which measures clock instability
as a function of observation time:

(source: jorisvr.nl)
Although this study has some limitations (only two boards were tested,
and the observation time is too short), it is well thought and very
informative. I encourage you to read it in whole.

Quartz crystals’ frequency changes slightly with temperature. If you can control the temperature it helps keep the frequency stable.

The best way to know the accuracy of the resonator of your board is to measure it yourself.
To do so, you can use the Arduino millis() function of your board and write a small sketch that will:

enable you to set the beginning time for measuring time drift (eg with a simple push button); you will trigger the button based on an accurate time base.
then repeatedly call millis() until at least 120h ("arduino hours", that would be around 5 days) have elapsed
display a signal when those 120h have elapsed (your sketch should probably "warn" you before the exact time has been reached so you get ready for measure)
when the 120h have elapsed, check your reference time based (used in step 1.) and check how much time have elapsed (should be 120h +/- epsilon)
once you know the drift of your clock, and provided your board will run in the same environental conditions (temperature mainly) of your measure, you can use it in your sketches to adjust the millis() value every hour or so.

Of course, this approach is far from perfect as it requires human intervention and thus will create additional time drifts during measurements, that's why you need to measure your clock time drifts over a long period.
An improved approach would be to connect a high accuracy RTC clock (the accuracy must be chosen based on the accuracy you need for your application) to your board and adapt the sketch so that it automatically calculates the drift. Once you got the time drift you can do the same as step 5 above in your sketches, and disconnect the RTC clock from your board.
Important points:

measure the time drift on the board that will need clock adjustment later on (if you have several boards, you must measure one drift per board)
ensure the stability of the environment in which your board will be used

Finally, if you really need high accuracy, then definitely connect an external clock source (e.g. RTC clock, GPS, NTP) to your board and use it as a SyncProvider for the PJRC library.

Your average system clock crystal will be off by several tens ppm (parts per million. They are great for stable and accurate timing of signals, but dramatic for keeping accurate time. Without special provisions the system crystal may be off by several seconds per day.
The solution is to use a proper Real Time Clock, driven by what is commonly known as a 32768Hz watch crystal. These crystals are easily a factor 10 better in accuracy. You can either set up your own oscillator that interrupts the main processor and keep count in your Arduino sketch or you find a RTC breakout board.
Two random examples that pop up in Google with search terms "RTC breakout":

http://www.cutedigi.com/breakout-board/ds1302-rtc-breakout.html
https://www.sparkfun.com/products/10160


text:
Are there any signal smoothing libraries for Arduino?
I am working on a mobile robot controlled via a wireless 2.4 GHz link.The receiver is connected to the Arduino Uno which serves onboard as the main controller. The most critical (and main) input channel coming from the receiver produces a very noisy signal, which leads to lots of minor changes in the output of the actuators, even though these are not needed.

                    Plot of the input of the Arduino in a 30 second interval.
I am looking for libraries that can perform efficient smoothing. Are there any signal smoothing libraries available for the Arduino (Uno)?

Don't know if you can find this kind of libraries but I'm afraid these might need to much CPU power for an Arduino. I'd rather go with an electronic solution (low-pass filter) if possible.

I am with  jfpoilpret on this. I think you need an electronic solution. I would try a stabilization capacitor, (simple low pass filter). I assume you are using an adc channel, so you should put a cap from this channel to ground. Start with values around 100pf, and work up from there.

Microsmooth is a lighweight signal smoothing library currently being developed by me.
It is still being worked on and the aim is to make it lightweight in terms of memory and fast. The library provides multiple filters for smoothing:

Simple Moving Average
Exponential Moving Average
Cumulative Moving Average
Savitzky Golay Filter
Ramer Douglas Pecker Algorithm
Kalmogorov Zurbenko Filter

To use the library, download and add it to the source directory. Also, add the following line to your source file:
#include "microsmooth.h"

Hi, I'm having trouble using your library. You wouldn't use "Import Library..." to import your library right? I tried just copying the source into my .ino folder, but I'm getting errors about missing automicrosmooth.h, Serial not being defined, and missing ';'. Is this library still working? Thanks

@waspinator Sorry about that. Fixed the errors. Thanks for the feedback!

I think I see a lot of single-sample noise spikes in your noisy signal.
The median filter does better at getting rid of single-sample noise spikes than any linear filter.
(It is better than any low pass filter, moving average, weighted moving average, etc. in terms of its response time and its ability to ignore such single-sample noise spike outliers).
There are, in fact, many signal-smoothing libraries for the Arduino, many of which include a median filter.
signal-smoothing libraries at arduino.cc:

Paul Badger: smooth digital low-pass filter
Paul Badger: digitalSmooth digital low-pass filter with outlier rejection
David A. Mellis and Tom Igoe: Smoothing tutorial
Majenki: Average Library

signal-smoothing libraries at github:

AsheeshR / Microsmooth
jeroendoggen: Arduino-signal-filtering-library
karlward: Arduino data filtering library
sebnil: FIR-filter-Arduino-Library
daPhoosa: MedianFilter
arc12: A Collection of Digital Signal Filters (intended for use with Arduino)
sebnil: Selfbalancing robot in Arduino. Implemented with PID controllers, FIR filters, complementary filter.

Would something like this work in your robot?
(The median-of-3 requires very little CPU power, and hence fast):
/*
median_filter.ino
2014-03-25: started by David Cary
*/

int median_of_3( int a, int b, int c ){
    int the_max = max( max( a, b ), c );
    int the_min = min( min( a, b ), c );
    // unnecessarily clever code
    int the_median = the_max ^ the_min ^ a ^ b ^ c;
    return( the_median );
}

int newest = 0;
int recent = 0;
int oldest = 0;

void setup()
{
    Serial.begin(9600);
    // read first value, initialize with it.
    oldest = random(200);
    recent = oldest;
    newest = recent;
    Serial.println("median filter example: ");
}

void loop()
{
    // drop oldest value and shift in latest value
    oldest = recent;
    recent = newest;
    newest = random(200);

    Serial.print("new value: ");
    Serial.print(newest, DEC);

    int median = median_of_3( oldest, recent, newest );

    Serial.print("smoothed value: ");
    Serial.print(median, DEC);
    Serial.println("");

    delay(5000);
}

Have you tried a low pass filter? I found an example here an another one here.
Both of these libraries have a list of data being read from the analog sensor of your choice which is averaged. Every new sensor value is added to the list, and the last one is thrown out, like this:
List: 3 4 3 3 4 3 5 3 2 3 4 3
new reading added. old one thrown out
      /--                     /--
List: 5 3 4 3 3 4 3 5 3 2 3 4
list averaged

Pretty much what a simple FIR filter does with all tap values set to 1. Fiddling with the taps values can improve the signal further, but requires higher math.

Note: The second link computes the cumulative moving average which is not a practical choice for actuator control, especially one which may involve frequent start and stops. The smoothed signal will always trail the peak value of the actual signal by quite a margin.

You could filter this digitally using a low pass filter:
int valueFilt = (1-0.99)*value + 0.99*valueFilt;

Change the 0.99 to change the cut off frequency (closer to 1.0 is lower frequency). The actual expression for that value is exp(-2*pi*f/fs) where f is the cutoff frequency you want and fs is the frequency the data is sampled at.
Another type of "digital filter" is an event filter. It works well on data that has outliers; e.g. 9,9,8,10,9,25,9 . An event filter returns the most frequent value. Statistically this is the mode.
Statistical averages such as Mean, Mode etc.. can be calculated using the Arduino Average Library.
An example taken from the Arduino Library page referred to :
#include <Average.h>
#define CNT 600
int d[CNT];

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

void loop()
{
  int i;

  for(i=0; i<CNT; i++)
  {
    d[i] = random(500);
  }

  Serial.print("Mean: ");
  Serial.print(mean(d,CNT),DEC);
  Serial.print(" Mode: ");
  Serial.print(mode(d,CNT),DEC);
  Serial.print(" Max: ");
  Serial.print(maximum(d,CNT),DEC);
  Serial.print(" Min: ");
  Serial.print(minimum(d,CNT),DEC);
  Serial.print(" Standard deviation: ");
  Serial.print(stddev(d,CNT),4);
  Serial.println("");
  Serial.println("");

  delay(5000);
}

Note that this will be very slow, since it's doing lots of implicit casts to float and back.

Check out the Arduino Smooth library. It uses absolutely no arrays, no looping over past values, it's fast with constant compute time, and the objects take up 8 bytes regardless of the sample window size.

It would be worth mentioning that this library, like some of the others already cited, implements an exponentially-weighted moving average. The fact that it works in constant-time and constant-size is nothing special: this is how this type of filter is always implemented. There are good use cases for an exponentially-weighted moving average, but the spiky noise of the original question is not one of them: this would be better served by a moving median.

source: Stack Exchange

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

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

sort: votes


text:
Infrared TV Remote to Arduino
On the hardware side of things, what is involved in making the Arduino receive signals from a TV Remote? What kind of infrared receiver is needed? Do TV remotes use some kind of channels, encoding, or encryption requiring special receivers or else additional programming work to decrypt the signals?

I would checkout http://www.righto.com/2009/08/multi-protocol-infrared-remote-library.html it explains locations to look to understand some of the protocols required to communicate with specific brands.

The most common (not sure what others are used) carrier frequency is 38khz. You need an IR receiver tuned to that frequency to get the signal from the remove. See this page for way more information.
There is no encryption or special receivers needed as long as the carrier frequencies match.
That's really all the hardware you need. On the software side of things, you read this signal and decode it. There's a neat little library for doing exactly that. It's called Arduino IRemote.
It even has an example sketch which tells you just what the decoded value is of whatever button you pressed so you can use that in your other programs.

Responding to TV remotes is surprisingly simple, because they typically all work on exactly the same principle, with no concept of channels or encryption.
What you need is an IR receiver module, which you can buy fairly cheaply from many electronics suppliers. Anything intended to work with remote controls should be suitable. The important part is that it will work with ~38 kHz signals.
It will typically be a 3 pin component. Many are able to operate at 5 volts, which means you can usually connect the IR module's voltage and ground pins directly to the Arduino's power supply. The data (or signal) pin can typically be connected straight to any GPIO pin. Always check the component's data sheet though. It will often recommend using some additional components (e.g. resistor and capacitor) to smooth out power fluctuations. That shouldn't be necessary for a small project though.
When an IR signal is detected, the module will usually output a series of pulses on the data pin. These will be digital pulses, so there's no need to use an analog-to-digital converter. What matters is typically either the length of each pulse (Pulse Width Modulation), or the length of the gap between consecutive pulses (Pulse Distance Modulation).
The timings of the pulses/gaps will be very fast; usually in the region of 400 to 2000 microseconds. That means it's probably too fast to try to detect them using repeated calls to digitalRead(). Instead, there is a core Arduino function called pulseIn(). When it's called, it will wait for a pulse to arrive on the specified GPIO pin. It will then return the approximate length of the pulse. You can detect high pulses for PWM, or low pulses for PDM.
Precise timing values will vary considerably, so you can ignore small variations. The key is to categorise each pulse as short or long, corresponding to a binary 0 or 1. A good starting point is to consider anything below 1000 usec as short, and everything else as long. Check what timings you actually receive though, and adjust that value accordingly.
Call pulseIn() repeatedly, storing each result. Keep going until no more pulses arrive (you will need to give it a timeout after which it gives up waiting, e.g. 10,000 usec or more).
Your TV remote will output a unique sequence of short/long pulses for each button, typically 32 bits or less (possibly with extra pulses at the beginning/end). All you need to do is figure out which sequence corresponds to each button. You could store that information in a lookup table, and respond accordingly when a sequence is recognised.

A simple IR diode like this can receive raw IR data. There are several chips which are designed to decode these signals, such as this one.
  ----------------
Ir Diode ------------------------------- Ir Decoder

To be more accurate, the TSOP382 is a bit more than just an IR diode; it includes additional electronics (pre-amp). Using a real simple IR receiver diode typically is not enough to just get commands from a TV remote.

The very nice thing about the TSOP382 and like others IC's, is that it has AGC amplifiers built in. Which accommodate a large dynamic change in amplitude, related to distances. Hence it works close and far away. DIY with discrete components gets messy(poor cost vs benefit ratio), as the IR energy drops very fast with distance.

I used TSOP1738 which is easily available at cheap price and I recorded values from more than 10 remotes and it worked very well.
Here is a file which contain recorded values of a Videocon DTH setup box's remote

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


text:
How do I write an Arduino sketch and an Android application to talk to each other over a standard USB cable?
How do I write an Arduino sketch and an Android application to talk to each other over a standard USB cable?

You can use one of the many usb interfaces

Android devices usually don't have a USB host: they expect to be connected to some smarter device like your computer. Same goes with Arduino.
For this reason Arduino made the Mega ADK (that means Accessory Development Kit).
Mega ADK and Due act as USB hosts and can be connected directly to your Android phone. If you already have a board, another option is to get a USB host shield to add USB host capababilities.
Your sketch will tell the phone what kind of accessory application it is and your phone will download the appropriate application from the store.
There is a book about connecting Arduino to Android.

There are converters from mini USB to USB-A host.

@anorton Yes: those are OTG cables... see my post.

The premise of this answer was outdated years before it was posted - most contemporary android devices were intended to have USB host support, though there are cases where some quirk of the design leaves it broken.

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

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

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

Note that standard Android USB host mode does not support flash drives with any operating system functionality (though a few vendor builds do) - rather, it exposes a fairly raw USB host API to application code.

The USB protocol requires one end to be a "host" and the other end to be a "peripheral", and it doesn't work if the devices at both ends of the cable are "peripherals".
Alas, most Arduinos and many early Android devices are "peripherals", so connecting such devices with a standard USB cable doesn't work.
Some modern Android devices support "OTG", so in theory one could make the Android end of the cable the "host". Has anyone gotten this to work?
Another approach is to somehow make the Arduino end of the cable the "host", and the Android end of the cable the "peripheral".
That's the approach taken by

Microbridge (a) (b)
The IOIO board (a) (b)
The Android Accessory Development Kit (ADK) (a) (b) (c)

(The Amarino (a) and Cellbots (a) (b) take yet another completely different approach).

Processing is a great place to get started with device to device communication.
The interface and language are very similar to Arduino and there are many examples to get you started.
http://playground.arduino.cc/Interfacing/Processing

Does that run on Android?

@AnnonomusPerson Yes, processing for android

@Faux_Clef Hmm didn't know that. I still don't know if it's the best for Android, that link that you posted didn't seem like it was very stable... I know that processing has USB support but I don't know if you can do that on Android...

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


text:
Serial data showing up weird
I have a simple sketch that prints out "Hello World" to the serial, but I'm getting a bunch of gibberish instead.
void setup() {
    Serial.begin(9600);
}

void loop() {
    Serial.println("Hello World");
    delay(1000);
}

Why isn't it printing "Hello World" like the code says?

Have you checked if initialization of serial port is proper and matches with PC serial terminal ?  The setup() should have something like Serial.begin(9600);

@Rajendra that line is in the code example I gave. Besides, I'm not actually having the problem. It's a common issue for beginners and I answered the question below.

The board and terminal are probably not using the same baud rate. Check the bottom right corner of the Arduino Serial Terminal and make sure it is set to 9600.
Serial Data
Serial communication works by sending the entire data stream one bit at a time. This is in contrast to the standard parallel port which sends one byte at a time. Both devices need to know at what speed the data is being sent. Furthermore, both devices need to be operating at the same speed. This is called the baud rate.
Baud Rate
Baud really just means pulses per second. In the context of serial communication, it means how many bits are transmitted per second. One of the most common values is 9600, but there are other common ones which are factors or multiples of 9600. It doesn't really matter, though, as long as both devices operate at the same speed.
If I'm sending you messages faster than you are getting them, you lose data. If I am sending you messages slower than you are receiving them, you get nonsense mixed in with what I sent you.
Data, Parity, Stop bits
If you look at the documentation for begin(), you'll see it can take two parameters:
Serial.begin(speed)
Serial.begin(speed, config)

Hopefully you understand speed now, it is the bits per second at which the Arduino will communicate.
The second parameter, config, lets you configure some other things about the serial data transmission. These are the Data, Parity, and Stop bits. You'll see on the page it has values like 5N1, 6N1 and SERIAL_8N1 (the default)
The first number represents how many data bits. The second character tells you what kind of parity bit there is. E for even parity, O for odd parity, or N for no parity. The third number tells you how many stop bits.
So really, with 8N1, we have 10 bits being sent for each 8 bits of "your" data. 1 start bit, 8 data bits, and 1 stop bit.
Anyway, both sides need to agree on this information as well as the speed. The Arduino Serial Terminal doesn't give you the option of changing these settings, but others do, so you'll need to be sure all of these configuration settings are the same.
More info on wiki: Asynchronous serial communication

Sachleen's answer (above) says:
The board and terminal are probably not using the same baud rate.
Check the bottom right corner of the Arduino Serial Terminal
and make sure it is set to 9600.

If this number is 9600, and you still get garbled data, check the output you obtained when uploading the code. It should read something like:
Sketch uses 2754 bytes (8%) of program storage space. Maximum is 30720 bytes.
Global variables use 195 bytes (9%) of dynamic memory, leaving 1853 bytes for local variables. Maximum is 2048 bytes.
C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avrdude -CC:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf -v -patmega328p -carduino -PCOM5 -b57600 -D -Uflash:w:C:\Users\Owner\AppData\Local\Temp\arduino_build_457862/LockCode.ino.hex:i

avrdude: Version 6.3, compiled on Jan 17 2017 at 12:00:53
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "C:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf"

         Using Port                    : COM5
         Using Programmer              : arduino
         Overriding Baud Rate          : 57600

This bottom line (of what I have posted) says what your device's default baudrate is. For me, I changed Serial.begin(9600); --> Serial.begin(57600); and checked that the bottom right corner of my Arduino Serial Terminal read 57600.
After I ran this, and it worked, I was able to switch back to 9600 and get non-garbled data. Arduino seems to be finicky...

I spent half an hour trying to solve that, and it was my Arduino Pro Mini that is 3.3V and I had selected 5V in the Arduino IDE (on PC).   Serial print never works like that even with same baud rate defined.
Select the correct board in the Arduino IDE.
To be clear, the correct processor (voltage/clock speed) under the Tools tab has to be selected.


text:
Using the Waspmote Sensor Board
Spanish company Libelium makes this pretty impressive sensor board:
http://www.libelium.com/products/waspmote/sensors/
for their Waspmote series of boards.  These are not meant for Arduino compatibility, but they are not only interesting for combining so many sensors, the availability of calibrated sensor sets makes it even more unique.
So here is the challenge: can we reasonably leverage these from an Uno or a Mega?

Look at some of their docs: http://www.libelium.com/development/waspmote/examples/ga-11-co-sensor-on-socket4-reading/ seems like they have a very similar platform to Arduino.

Their forums suggest making the connection is not trivial, but may be possible:  http://www.libelium.com/forum/viewtopic.php?f=15&t=8811

They talk about XBee and WiFi connections in one of the datasheets and there is an API later in the PDF docs... Yet I read that it might be hard... (Direct quote from 0xF2's comment) Compatibility between Arduino and Waspmote's sensor boards is not direct, since the connectors' pinout do not correspond, you'd have to wire the connections using the documentation. Anyway, I'm afraid the Libelium's sales policy implies a minimum first order including five Waspmotes, five batteries and one Gateway. | @sachleen Maybe it is powered by Arduino with a few libraries...

Too long for a comment...
Look at some of their docs for examples. seems like they have a very similar platform to Arduino.

Their forums suggest making the connection is not trivial, but may be
  possible: http://www.libelium.com/forum/viewtopic.php?f=15&t=8811

All that's saying is you can't simply plug in a sensor into your Arduino like a shield, because it's not a shield. You'd have to hook up the connections to the right pins and then use their libraries and code to communicate with it.
That involves reading their documentation and code to figure out what pins it uses to communicate with what. You may have to modify the code slightly to work with Arduino (mainly changing pin numbers).
All in all, I wouldn't invest my time or effort into it. Don't lock yourself into a product that isn't intended to be used the way you're using it. You'll get no support from the company and there's no guarantee future versions of their product will work. Or things like this (from the forum link):

Anyway, I'm afraid the Libelium's sales policy implies a minimum first
  order including five Waspmotes, five batteries and one Gateway.

Simply not worth the effort. You'd be much better off making your own sensor board to fit your requirements.

Now you can purchase single boards through MicroConrollerShop.com
http://microcontrollershop.com/product_info.php?cPath=297_566&products_id=6773


text:
When should I use a transistor, mosfet, and when should I use a relay?
I am used to relays some, and they are useful, especially for large loads like a incandescent light bulb or other 120V AC device. However, it seems like overkill to use a relay for a bunch of LEDs linked together (parallel) that use 60 mA (too much for the Arduino). Also, it wouldn't work if you wanted to turn it on/off frequently or do PWM. I've heard some about transistors and MOSFETS and know a little about them. When should I use each one and how do I know what type to get? Also, it seems like relays can be more expensive than transistors/MOSFETS.
Edit: How can I use these with my Arduino?

This question appears to be off-topic because it is about electrical engineering in general, not arduino specific. It belongs here https://electronics.stackexchange.com/

@jamolnng I disagree. If a new user posts something like this, they generally don't know how to use any of these. EE generally requires a fair amount of knowledge about the subject before posting. This does bring up an issue though of "should we migrate and close it just because there is overlap?"

True. We really need a defined set rules on what is acceptable, which is what this beta should help us decide. Also you are right about EE because a post like this would most likely get buried there. I keep my opinion that it should be migrated and closed because it doesn't really deal with arduino specifically, but you have a valid argument for keeping it open.

@jamolnng I respect your argument too and I see both sides: I just posted this question to bring up this argument because it hasn't really been answered in meta and I thought it would be a good example to actually post a question so we can see how it plays out.

Related meta discussion.

One could also add optocouplers to this list.

Simplest design requirement I can think of at the moment is: If you want to control mains power, you never use a transistor-only based solution.

@AsheeshR I agree, I would've unaccepted it earlier if it hadn't been so heavily voted to put on hold. I cast the final vote. This was more of a "test" to see if we would get good enough answers but the two there clearly show that this would be fit for EE.

Transistors (such as Bipolar Junction Transistors (BJT)) are solid state switchers, that is, they don't have any moving parts. Metal-Oxide-Semiconductor Field-Effect Transistors (MOSFET) are also transistors, but are voltage controlled, whereas classical BJTs are current-controlled. Relays are more expensive, but they have moving parts.
BJTs and MOSFETs produce a lot of heat (with high currents). They both have three pins (usually) called the base, collector and emitter (in the case of BJT) or gate, source, drain (in the case of MOSFET). More info here
Relays use a magnet to control the position of a metal switch. They generally take more power than an Arduino pin can deliver, and therefore they are often controlled by a transistor. Relays can usually switch more current than either a transistor or a MOSFET.
There are also Solid State Relays (SSR), which have a triac (a device similar to a transistor) in them. These can't switch as much as a normal relay, but they generally have better ratings than MOSFETs and BJT. example

One comment: MOSFETs have very low internal resistance, and so when fully switched on do not generate a lot of heat. They can handle quite a bit of current without needing a heat-sink.

Big differences between relays and transistors are:

relays are all-or-nothing (like switches) whereas transistors can transmit more or less current through the collector based on the current present on their base.
relays provide isolation between the command circuit (the one with the electromagnet) and the controlled circuit (the one on the switch side of the relay)

If you want to play with arduino, you definitely need to know about transistors; using relays is more akin to special applications.


text:
What will happen when I use an invalid pin number?

Related to:
  What happens if there is a runtime error?

This question is similar to the one above, however this is an alternate situation:
int pin = 999;
pinMode(pin, OUTPUT);
digitalWrite(pin, HIGH);

What would happen in this instance? The compiler might catch it but if you used a random number would the IDE catch it?

The compiler will not detect any error and the code will compile and execute. Hence, to see what happens we need to explore the behind-the-scenes magic. For a summary, skip to end.

The second line in your code is where the magic will happen and thats where we need to focus.
pinMode(pin, OUTPUT);

The portion of pinMode relevant to this discussion is:
void pinMode(uint8_t pin, uint8_t mode)
{

    uint8_t bit = digitalPinToBitMask(pin); //The first instance where pin is used
    uint8_t port = digitalPinToPort(pin);

    if (port == NOT_A_PIN) return;

//Do something
}

(The complete implementation can be found in wiring_digital.c)
So, here, digitalPinToBitMask seems to be using pin to compute an intermediate bit. Exploring further, digitalPinToBitMask is a macro defined in Arduino.h whose definition is this one-liner:
#define digitalPinToBitMask(P) ( pgm_read_byte( digital_pin_to_bit_mask_PGM + (P) ) )

This weird looking one liner does a very simple task. It indexes the Pth element in the array digital_pin_to_bit_mask_PGM and returns it. This array digital_pin_to_bit_mask_PGM is defined in pins_arduino.h or the pin map for the specific board being used.
const uint8_t PROGMEM digital_pin_to_bit_mask_PGM[] = {
    _BV(0), /* 0, port D */
    _BV(1),
    _BV(2),
    _BV(3),
    _BV(4),
    _BV(5),
    _BV(6),
    _BV(7),
...
};

This array has 20 elements in total, so we are out of luck. 999 will index a memory location in the flash memory outside of this array, thereby leading to unpredictable behavior. Or will it?
We still have another line of defense against runtime anarchy. Its the next line of the function pinMode:
uint8_t port = digitalPinToPort(pin);

digitalPinToPort takes us along a similar path. It is defined as a macro along with digitalPinToBitMask. Its definition is:
#define digitalPinToPort(P) ( pgm_read_byte( digital_pin_to_port_PGM + (P) ) )

Now, we index the Pth element of digital_pin_to_port_PGM which is an array defined in the pin map:
const uint8_t PROGMEM digital_pin_to_port_PGM[] = {
    PD, /* 0 */
    PD,
    ....
    PC,
    PC,
};

This array contains 20 elements, so 999 is again out of range. Again, this command reads and returns a value from flash memory of whose value we cannot be certain. This will again lead to unpredictable behavior from here on.
There is still one last line of defense. That is the if check in pinMode on the return value of digitalPinToPort:
if (port == NOT_A_PIN) return;

NOT_A_PIN is defined as 0 in Arduino.h. So, if the returned byte from digitalPinToPort happens to be zero, then pinMode will silently fail and return.
In any case, pinMode cannot save us from anarchy. 999 is destined to result in doom.

TL;DR, the code will execute and the result of this will be unpredictable. Most likely, no pin will be set to OUTPUT, and digitalWrite will fail. If you happen to have exceptionally bad luck, then a random pin may get set to OUTPUT, and digitalWrite may set it to HIGH.

It's interesting there is no bounds checking. digitalWrite is so slow and bulky anyway, it wouldn't be awkward to put in either compile time or run time checks.

If all arduino pins are in a contiguous range, than couldn't they replace the port==not a pin check with a pin>BOARD_MAX_PIN check, where board max pin is defined in some header file based on some ifdef that detects the board?

You are forgetting that 999 cannot be represented in a uint8_t so it would first be converted to 231 by the code calling pinMode.  The end result is the same: pinMode and digitalWrite will have unpredictable behavior and could clobber random parts of memory if you call them with a bad pin argument.

In the standard libraries, there are macros designed for converting pins to ports, which are used in assembly. Here they are for the Uno from Arduino 1.0.5:
#define digitalPinToPCICR(p)    (((p) >= 0 && (p) <= 21) ? (&PCICR) : ((uint8_t *)0))
#define digitalPinToPCICRbit(p) (((p) <= 7) ? 2 : (((p) <= 13) ? 0 : 1))
#define digitalPinToPCMSK(p)    (((p) <= 7) ? (&PCMSK2) : (((p) <= 13) ? (&PCMSK0) : (((p) <= 21) ? (&PCMSK1) : ((uint8_t *)0))))
#define digitalPinToPCMSKbit(p) (((p) <= 7) ? (p) : (((p) <= 13) ? ((p) - 8) : ((p) - 14)))

There are more, but I won't show them here.
I believe your program would subtract 14 from 999, which would still be too big for the brogram. It would then try to point to the 985th element of the digital_pn_to_bit_mask_PGM array, which only contains 20 elements. This would most likely end up screwing the Arduino by pointing to a random spot in progmem.


text:
How can I get a unique ID for all my Arduino boards?
Once you have uploaded a sketch to one of your Arduino boards, it is hard to know exactly what source code led to that sketch.
Indeed, you may change the source code of your sketch on your PC without updating it (in binary format) to your board.
I had the idea of setting up a kind of "sketch repository" that would be populated as soon as I upload a sketch to one of my boards. Then I could retrieve, later on, the source code for a sketch running on any of my boards.
For such a repository, I would first need to have an "index" that would enable me to know which board the sketch source code is linked to.
Typically, such an index should be unique for every single arduino board.
Hence my question: how can I get a unique ID for an Arduino board?
Edit:
This is my current list of boards (the miniumum list to be supported by a single unique ID approach):

UNO R3
Mega 2560
Yun
Arduino Robot (that must be 2 Leonardo equivalent boards)

In the future, I may also build my own boards (Uno equivalent but barebones, without FTDI), hence if an approach also supports these that would be better.

@jfpoilpret...just saw this post while perusing the site..did you find a solution, or best case scenario on how to implement this?

There are a number of techniques you could use here to get a unique ID.

FTDI chips have a unique serial number programmed onto them. This can only be accessed from the PC side of the connection as far as I am aware.
Some of the chips with built in USB (e.g. ATmega8U2/16U2/32U2) have a unique ID in the signature data, normally used for USB. Can easily be accessed from both sides of the connection. This includes the ATmega16U2 that is used as the USB->Serial bridge Arduino Uno R3.
Some of the chips with built in USB but no unique ID in the signature will still have a unique ID programmed into the USB stack (e.g. LUFA) used for the bootloader or DFU (Device Firmware Upgrade).
There are many chips with globally unique serial IDs in them e.g. the Microchip 11AA02E48, all of the Dallas 1-Wire sensors (including the common DS18B20 temperature sensor), and other serial EEPROMS. I've used these in production hardware that must have a unique MAC address.
You could modify the standard Optiboot bootloader (or whichever boat loader you use) so that it can hold and respond with a unique ID.

The problem with these is that there is no option except 5 that will work across all boards.
If your solution is going to be a generic one, I would suggest that using a USB ID is not the way forwards. I have ~30 Arduino-based boards, and only 5 of them have built in USB hardware. All the rest of them need an external FTDI cable to be programmed. This means they would all have the same ID.

What do you do with 30 boards?

Mainly for wireless sensor networks. I only have a few real Arduinos - a Duemilanova, a Seeeduino Mega and an Uno. All the others are Teensy, Jeenodes, WiNodes, Nanodes and RFus.

+1 for a thorough list of possible options, thanks! I'd rather avoid 4. as I don't want to add specific hardware to all my boards. 5. looks dangerous (easy to upload the same modified bootloader to 2 different boards) and cumbersome (need to have different bootloaders source code to upload for every board). So far, USB ID and FTDI seem quite good solutions, but do they work with all my current board?

Does Arduino have globally unique serial IDs ? How to read it ?

The chip doesn't have any sort of unique ID as far as I know.... but you could program one into the EEPROM of your boards.
EEPROM documetnation
You would write to a specific address and then future sketches can read the ID and do whatever with it.

You may also be able to see a unqiue ID or address on the host side. I don't know enough about USB devices to tell you more, but the chip handling USB communication might have a unique ID you could use. Your Arduino code would not be able to use this, though.
Alternatively, just use a label maker and put a label on each board.

As far as the unique aspect of the question, a GUID could solve that (within some tiny margin of error).

I had originally thought of using the EEPROM for that; but that requires additional work for every board  get: create a new unique ID, then write it to the EEPROM. Also, there may be incompatibilities with libraries used by my sketches (that may write to the same EEPROM address). Finally in my context, I would need to read the ID from my PC, which is more difficult. The USB unique ID seems more interesting to me.

As per my answer, if you want this to be a generic solution (for most people, and a wide range of boards), relying on the USB ID means that people using FTDI cables on boards without a USB->Serial bridge would not be able to use you system.

Some boards, when connected to a computer, publish their serial number. My Arduino Uno R3 says
[16818.451423] usb 3-2: SerialNumber: 85235353137351E02242

Though I'm not sure how unique it is.

Do all Arduino boards have such a number? It would be nice to have the list of boards that have one (or not).

Looking at mines, 32u4 based ones don't, 328 and SAM3X8E ones do have it

To the best of my knowledge the USB chips all come with a unique serial number, at least for the FTDI chips. On Linux you can easily assign unique device names from that, check my website.
Other than that, what you are describing is pretty much a simple form of version control. Make sure your source files have version numbers. To identify your Arduino, you can make it Serial.Print(); name and version of the code during setup();.

Yes version control is more or less what I want to achieve; but setting a version in code and changing it every time the code changes is not an option (too easy to forget). I currently use github for my sketches, but I'd like to easily find out what version of what sketch is currently running on one board.

There is a macro for compilation date and time __DATE__ and __TIME__. So at least you can automatically store that info in your .hex file @jfpoilpret

Good point, I hadn't thought about these macros for versioning.

I doubt that the USB interface on the Uno gives you a unique serial number. Any number would be part of the code uploaded to the chip which would therefore be the same amongst multiple Unos.
One approach is the DS2401 "Silicon Serial Number" chip which uses the One-wire interface. That would only require one free pin, and some code (the code would be the problem, possibly).
The least intrusive method, and probably the most reliable, would be to simply read back the code and sum-check it. That is exactly what I do with my chip signature detector. However that only detects (as currently written) the bootloader signature. A fairly minor change and it could MD5-sum the entire sketch code.
Example output:
Signature detector.
Written by Nick Gammon.
Signature = 1E  95  0F
Fuses
Low = FF High = D6 Ext = FF Lock = CF

Processor = ATmega328P
Flash memory size = 32768
Bootloader in use: Yes
EEPROM preserved through erase: Yes
Watchdog timer always on: No
Bootloader is 512 bytes starting at 7E00

Bootloader:

7E00: 02 01 02 03 0405 06 07 08 09 0A 0B 0C 0D 0E 0F
7E10: 02 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F
7E20: 02 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F
7E30: 02 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F
...
7FB0: 02 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F
7FC0: 02 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F
7FD0: 02 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F
7FE0: 02 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F
7FF0: 02 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F

MD5 sum of bootloader = 56 72 75 2D 5D B5 0D BA 25 10 DF BE 87 D2 A1 27

That MD5 sum (last line) is effectively the signature of that particular bootloader. In fact the most recent version looks them up in a table:
MD5 sum of bootloader = FB F4 9B 7B 59 73 7F 65 E8 D0 F8 A5 08 12 E7 9F
Bootloader name: optiboot_atmega328

So what you could do is, when uploading a sketch, generate a MD5 sum of the hex code. There are fairly simple ways of doing that. Then you could do a "git tag" operation on your source code, and then (using some automated or manual process) remember that a particular MD5 sum of hex code represents the sketch code at a particular moment.
Some sort of database like:
Chip: Uno
MD5 sum: D8 8C 70 6D FE 1F DC 38 82 1E CE AE 23 B2 E6 E7
Sketch: My_robot_sketch_42.ino
Git tag: version666

Now to locate the source from the board, you establish the MD5 sum of the code (by reading it back from the board) and then look it up in your database.

I connected a one wire temp sensor that each come with an unique I'd.  All the sketches read the I'd on boot and wrote the address on every serial connection. I made a shield with all the hardware I needed so if I needed to upgrade from Uno to Mega the device kept its unique I'd.

There is tiny library for reading and writing your custom hardware ID to EEPROM. You can use it to avoid pushing wrong sketch to your Arduino or to identify device for other purposes.
https://github.com/skoumalcz/arduino-id-guard
Disclaimer: I'm author of the library :-)

#include <avr/boot.h>
#ifdef __AVR_ATmega2560__  /// check if a MEGA2560 is in use
#define USEMEGA_ID         ///
void setup()
{
#ifdef __AVR_ATmega2560__
  cli();
  int data3, data4;
  data3 = boot_signature_byte_get(0x04) * 256;
  data4 = boot_signature_byte_get(0x01);
  sei();
  MegaID = data3 + data4;
#endif
Serial.begin(115200);
  Serial.print("MegaID             \t: "); Serial.println(MegaID);
}

// This will show you a 3 digit MegaID
// You can now create different setups for different MEGA2560  with the same source code

The number returned by this code seems to be based both on the device signature (which is the same for all ATmega2560 devices) and the factory-stored oscillator calibration byte (which can vary between boards). It is not guaranteed to be unique. I wonder what is the typical spread of the calibration bytes: this conditions the likelihood of ID collisions.

correct!There only 3 numbers. so they are 999 possibilities. this is not much or secure, but practical, when you have only a few boards an like to have different setups with the same code.


text:
How can I create multiple running threads?
Is there a way I can have multiple parts of the program running together without doing multiple things in the same code block?
One thread waiting for an external device while also blinking a LED in another thread.

You should probably first ask yourself if you really need threads. Timers may be OK for your needs already and they are natively supported on Arduino.

You may want to check out the Uzebox too.  It's a two chip homebrew video game console.  So while it isn't exactly an Arduino, the entire system is built on interrupts.  So audio, video, controls, etc. are all interrupt driven while the main program doesn't have to worry about any of it.  May be good reference.

Use the Arduino library NonBlockingSequence. You can define more than one sequence. Each sequence can describe a specific thread.

There is no multi-process, nor multi-threading, support on the Arduino. You can do something close to multiple threads with some software though.
You want to look at Protothreads:

Protothreads are extremely lightweight stackless threads designed for
  severely memory constrained systems, such as small embedded systems or
  wireless sensor network nodes. Protothreads provide linear code
  execution for event-driven systems implemented in C. Protothreads can
  be used with or without an underlying operating system to provide
  blocking event-handlers. Protothreads provide sequential flow of
  control without complex state machines or full multi-threading.

Of course, there is an Arduino example here with example code. This SO question might be useful, too.
ArduinoThread is a good one too.

Note that the Arduino DUE has an exception to this, with multiple control loops: https://www.arduino.cc/en/Tutorial/MultipleBlinks

AVR based Arduino's do not support (hardware) threading, I am unfamiliar with the ARM based Arduino's. One way around this limitation is the use of interrupts, especially timed interrupts. You can program a timer to interrupt the main routine every so many microseconds, to run a specific other routine.
https://www.arduino.cc/reference/en/language/functions/interrupts/interrupts/

It is possible to do software side multi-threading on the Uno. Hardware level threading is not supported.
To achieve multithreading, it will require the implementation of a basic scheduler and maintaining a process or task list to track the different tasks that need to be run.
The structure of a very simple non-preemptive scheduler would be like:
//Pseudocode
void loop()
{

for(i=o; i<n; i++)
run(tasklist[i] for timelimit):

}

Here, tasklist can be an array of function pointers.
tasklist [] = {function1, function2, function3, ...}

With each function of the form:
int function1(long time_available)
{
   top:
   //Do short task
   if (run_time<time_available)
   goto top;
}

Each function can perform a separate task such as function1 performing LED manipulations, and function2 doing float calculations. It will be the responsibility of each task(function) to adhere to the time allocated to it.
Hopefully, this should be enough to get you started.

I am not sure I would talk about "threads" when using a non preemptive scheduler. By the way, such a scheduler already exists as an arduino library: http://arduino.cc/en/Reference/Scheduler

@jfpoilpret - Cooperative multithreading is a real thing.

Yes you're right! My mistake; it had been so long ago I had not faced cooperative multithreading that in my mind, multithreading had to be preemptive.

As per the description of your requirements:

one thread waiting for an external device
one thread blinking a LED

It seems you could use one Arduino interrupt for the first "thread" (I would rather call it "task" in fact).
Arduino interrupts can call one function (your code) based on an external event (voltage level or level change on a digital input pin), that will trigger your function immediately.
However, one important point to keep in mind with interrupts is that the called function should be as fast as possible (typically, there should be no delay() call or any other API that would depend on delay()).
If you have a long task to activate upon external event trigger, then you could potentially use a cooperative scheduler and add a new task to it from your interrupt function.
A second important point about interrupts is that their number is limited (e.g. only 2 on UNO). So if you start tohave more external events, you would need to implement some kind of multiplexing all inputs into one, and have your interrupt function determine what multiplexed inut was the actual trigger.

A simple solution is to use a Scheduler. There are several implementations. This describes shortly one that is available for AVR and SAM based boards. Basically a single call will start a task; "sketch within a sketch".
#include <Scheduler.h>
....
void setup()
{
  ...
  Scheduler.start(taskSetup, taskLoop);
}

Scheduler.start() will add a new task that will run the taskSetup once and then repeatedly call taskLoop just as the Arduino sketch works. The task has its own stack. The size of the stack is an optional parameter. Default stack size is 128 bytes.
To allow context switching the tasks need to call yield() or delay(). There is also a support macro for waiting for a condition.
await(Serial.available());

The macro is syntactic sugar for the following:
while (!(Serial.available())) yield();

Await can also be used to synchronize tasks. Below is an example snippet:
volatile int taskEvent = 0;
#define signal(evt) do { await(taskEvent == 0); taskEvent = evt; } while (0)
...
void taskLoop()
{
  await(taskEvent);
  switch (taskEvent) {
  case 1:
  ...
  }
  taskEvent = 0;
}
...
void loop()
{
  ...
  signal(1);
}

For further details see the examples. There are examples from multiple LED blink to debounce button and a simple shell with non-blocking command line read. Templates and namespaces can be used to help structure and reduce the source code. Below sketch shows how to use template functions for multi-blink. It is sufficient with 64 bytes for the stack.
#include <Scheduler.h>

template<int pin> void setupBlink()
{
  pinMode(pin, OUTPUT);
}

template<int pin, unsigned int ms> void loopBlink()
{
  digitalWrite(pin, HIGH);
  delay(ms);
  digitalWrite(pin, LOW);
  delay(ms);
}

void setup()
{
  Scheduler.start(setupBlink<11>, loopBlink<11,500>, 64);
  Scheduler.start(setupBlink<12>, loopBlink<12,250>, 64);
  Scheduler.start(setupBlink<13>, loopBlink<13,1000>, 64);
}

void loop()
{
  yield();
}

There is also a benchmark to give some idea of the performance, i.e. time to start task, context switch, etc.
Last, there are a few support classes for task level synchronization and communication; Queue and Semaphore.

I also came to this topic while implementing a matrix LED display.
In one word, you may build a polling scheduler by using millis() function and timer interrupt in Arduino.
I suggest the following articles from Bill Earl:
https://learn.adafruit.com/multi-tasking-the-arduino-part-1/overview
https://learn.adafruit.com/multi-tasking-the-arduino-part-2/overview
https://learn.adafruit.com/multi-tasking-the-arduino-part-3/overview

From a previous incantation of this forum, the following question/answer was moved to Electrical Engineering.  It has sample arduino code to blink an LED using a timer interrupt while using the main loop to do serial IO.
https://electronics.stackexchange.com/questions/67089/how-can-i-control-things-without-using-delay/67091#67091
Repost:
Interrupts are a common way to get things done while something else is going on.  In the example below, the LED is blinking without using delay().  Whenever Timer1 fires, the interrupt service routine (ISR) isrBlinker() is called.  It switches the LED on/off.
To show that other things can simultaneously happen, loop() repeatedly writes foo/bar to the serial port independent of the LED blinking.
#include "TimerOne.h"

int led = 13;

void isrBlinker()
{
  static bool on = false;
  digitalWrite( led, on ? HIGH : LOW );
  on = !on;
}

void setup() {
  Serial.begin(9600);
  Serial.flush();
  Serial.println("Serial initialized");

  pinMode(led, OUTPUT);

  // initialize the ISR blinker
  Timer1.initialize(1000000);
  Timer1.attachInterrupt( isrBlinker );
}

void loop() {
  Serial.println("foo");
  delay(1000);
  Serial.println("bar");
  delay(1000);
}

This is a very simple demo.  ISRs can be much more complex and can be triggered by timers and external events (pins).  Many of the common libraries are implemented using ISRs.

You could also give my ThreadHandler library a try
https://bitbucket.org/adamb3_14/threadhandler/src/master/
It uses an interrupting scheduler to allow context switching without relaying on yield() or delay().
I created the library because I needed three threads and I needed two of them to run at a precise time no matter what the others were doing. The first thread handled serial communication. The second was running a Kalman filter using float matrix multiplication with the Eigen library. And the third was a fast current control loop thread which had to be able to interrupt the matrix calculations.
How it works
Each cyclic thread has a priority and a period. If a thread, with higher priority than the current executing thread, reaches its next execution time the scheduler will pause the current thread and switch to the higher priority one. Once the high priority thread completes its execution the scheduler switches back to the previous thread.
Scheduling rules
The scheduling scheme of the ThreadHandler library is as follows:

Highest priority first.
If the priority is the same then the thread with the earliest deadline is executed first.
If two threads have the same deadline then the first created thread will execute first.
A thread can only be interrupted by threads with higher priority.
Once a thread is executing it will block execution for all threads with lower priority until the run function returns.
The loop function has priority -128 compared to ThreadHandler threads.

How to use
Threads can be created via c++ inheritance
class MyThread : public Thread
{
public:
    MyThread() : Thread(priority, period, offset){}

    virtual ~MyThread(){}

    virtual void run()
    {
        //code to run
    }
};

MyThread* threadObj = new MyThread();

Or via createThread and a lambda function
Thread* myThread = createThread(priority, period, offset,
    []()
    {
        //code to run
    });

Thread objects automatically connect to the ThreadHandler when they are created.
To start execution of created thread objects call:
ThreadHandler::getInstance()->enableThreadExecution();

And here is yet another microprocessor cooperative multitasking library – PQRST: a Priority Queue for Running Simple Tasks.

Home page
Class-level documentation
Repository, with downloads and issues list

In this model, a thread is implemented as a subclass of a Task, which is scheduled for some future time (and possibly rescheduled at regular intervals, if, as is common, it subclasses LoopTask instead).  The run() method of the object is called when the task becomes due.  The run() method does some due work, and then returns (this is the cooperative bit); it'll typically maintain some sort of state machine to manage its actions on successive invocations (a trivial example is the light_on_p_ variable in the example below).  It requires a slight rethinking of how you organise your code, but has proven very flexible and robust in fairly intensive use.
It's agnostic about the time units, so it is as happy running in units of millis() as micros(), or any other tick that is convenient.
Here is the ‘blink’ program implemented using this library.  This shows only a single task running: other tasks would typically be created, and started within setup().
#include "pqrst.h"

class BlinkTask : public LoopTask {
private:
    int my_pin_;
    bool light_on_p_;
public:
    BlinkTask(int pin, ms_t cadence);
    void run(ms_t) override;
};

BlinkTask::BlinkTask(int pin, ms_t cadence)
    : LoopTask(cadence),
      my_pin_(pin),
      light_on_p_(false)
{
    // empty
}
void BlinkTask::run(ms_t t)
{
    // toggle the LED state every time we are called
    light_on_p_ = !light_on_p_;
    digitalWrite(my_pin_, light_on_p_);
}

// flash the built-in LED at a 500ms cadence
BlinkTask flasher(LED_BUILTIN, 500);

void setup()
{
    pinMode(LED_BUILTIN, OUTPUT);
    flasher.start(2000);  // start after 2000ms (=2s)
}

void loop()
{
    Queue.run_ready(millis());
}

These are “run-to-completion” tasks, right?

@EdgarBonet I'm not sure quite what you mean. After the run() method is called, it is not interrupted, so it has the responsibility to finish reasonably promptly. Typically, however, it'll do its work then reschedule itself (possibly automatically, in the case of a subclass of LoopTask) for some future time.  A common pattern is for the task to maintain some internal state machine (a trivial example is the light_on_p_ state above) so that it behaves suitably when it is next due.

So yes, those are run-to-completion (RtC) tasks: no task can run before the current one completes its execution by returning from run(). This is in contrast with cooperative threads, that can yield the CPU by, e.g., calling yield() or delay(). Or preemptive threads, that can be scheduled-out at any time. I feel the distinction is important, as I have seen that many people who come around here searching for threads do so because they prefer writing blocking code rather than state machines. Blocking real threads that yield the CPU is fine. Blocking RtC tasks is not.

@EdgarBonet It's a useful distinction, yes. I would regard both this style, and yield-style threads, as simply different styles of cooperative thread, as opposed to preemptive threads, but it's true that they require a different approach to coding them.  It would be interesting to see a thoughtful and in-depth comparison of the various approaches mentioned here; one nice library not mentioned above is protothreads. I find things to criticise in both, but also to praise. I (of course) prefer my approach, because it seems most explicit and needs no extra stacks.

(correction: protothreads was mentioned, in @sachleen's answer)


text:
Serial sensors and the Yun
I am involved in a project that is going to measure PH and chlorine in a swimming pool.  The plan is to use a Arduino Yun. The sensors we are going to use are connected using serial.  Since we may be using multiple sensors, is there any difference in reliability, latency, known issues (bugs) of using software serial versus pin0 and pin1? Is it any way to avoid software serial pitfalls (if there are any)?

The Yun is a bit different to other Arduinos. The main microcontroller is a ATmega32U4 with a build in USB interface. This is used for the connection to the PC so the single USART is not used for this purpose.
However, the single USART is used for connecting to the built in wireless processor. This means that you can't use the wireless and hardware serial at the same time. I presume you are using the Yun for wireless, so disabling this is not desirable.
SoftwareSerial is relatively good, but does consume a lot of cycles. You can only listen on a single port at a time. It is possible to use pin change interrupts to listen for activity on multiple ports and switch to the one required, but this requires that the other end can wait for a response.
SoftwareSerial will tie up the microcontroller whilst sending, which can lead to problems when supporting low baud rates. Conversely, because it is CPU heavy, it can also have problems with high baud rates. There is a window, between 9600 and 38400 baud, where it seems to work best.
There is another software serial version called AltSoftSerial. This works faster than SoftwareSerial and can transmit and receive at the same time.
You can use the USART, SoftwareSerial and AltSoftSerial all at the same time. Be warned that because all three of these use interrupts and some use timers, you are highly likely to end up with complex, hard to debug interactions.
Note than in older versions of Arduino (pre v1), SoftwareSerial was very, very poor. It was replaced entirely with "NewSoftSerial".
Sensors are often have very basic USART hardware with limited buffer sizes, and drop data when they aren't serviced in a timely manner.
I am not a massive fan of the Yun. It isn't popular, the wireless is still relatively hard to use (compared to the TI CC3000), and the wireless interface uses valuable pins. Personally, if I was to work on a project that required multiple serial interfaces, I would either

Use a board with multiple USART, such as a ATmega1280 (2 USARTs) or ATmega2560 (4 USARTs) and a CC3000 (SPI connected) wireless board.
Use SPI/I2C->USART bridges. This allows a single SPI/I2C port to control multiple USARTs. Sparkfun sell one, there are many others available.

Be cautious of falling into the trap of using hardware because it is what you have available.

I don't have any experience with the Yun so I can't comment on that specifically, but the only problem you'll encounter with using SoftwareSerial is that you can only communicate with one device at a time.
This means you'll have to make a call to listen()
sensor1.listen()

before communicating with sensor1. Then when you want to communicate with another sensor, you have to do the same.

I didn't check the circuit diagrams, but on most AVR based Arduino's pins 0 and 1 are used to program the device. By reusing the pins, you may run into problems when trying to program the Arduino from IDE. It is easily solved by detaching the hardware from those pins, but you have to reattach them to test the sketch. I personally try to avoid using those to pins, just for ease of development.


text:
What's the difference between a clone and a counterfeit Arduino?
I've been hearing a lot about clones and counterfeits. What are the differences between the two?

Price is the main difference.

and quality is another issue

The difference is simple:
Clones don't say "Arduino," where counterfeits do
If I were to create 200 boards all labeled "Arduino UNO R3," it would be a counterfeit. If I were to call them "Happyduino," it would be a clone.

Note: You can still write Happyduino (Arduino Compatible) on your product. Here's a quote from the Arduino FAQ section

Not okay:

Arduino Xxxxxx
Xxxxxx Arduino
Arduino Compatible Xxxxxx - use "Xxxxxx (Arduino-Compatible)" instead

Okay:

Xxxxxx for Arduino - products that work with official Arduino boards    (e.g. shields or kits)
Xxxxxx (Arduino-Compatible) - variations and clones which are    software and hardware compatible

Note that while we don't attempt to restrict uses of the "duino"
  suffix, its use causes the Italians on the team to cringe (apparently
  it sounds terrible); you might want to avoid it. (It's also
  trademarked by a Hungarian company.)

I have a "Arduino" lying in front of me and it definitely a cheap clone. Nothing hints that it is not the original thing other than visual aspects as layout/color/silk screen font/... (and the brand name in a tiny print in a corner of the PCB)

I understand the "Happy" part, but I guess I miss the point you're trying to make.

@jippie what he's saying is, you can use the "duino" in your naming structure without trademark/copyright issues, so Happyduino is ok, but the word Arduino itself is not, except as detailed with "for Arduino" or "Arduino compatible"

I guess one key point is that if they say "Arduino" very directly in the name, they are giving the impression to the customer that it was actually made by Arduino, with the quality assurance that that would imply.  But if you stick the word "Arduino" off in a phrase AFTER the title, or if they only use the "duino" suffix,  then it is clear to the customer that this is made by a third company that is only promising that it will work compatibly with the original Arduinos.  Makes me glad- I am about to buy a few inexpensive chinese MEGAs and they are honest about it, so no guilt for me.

A clone is an exact or almost exact replica of an original Arduino board, with a different branding.
A derivative is a board based or inspired by Arduino boards, with some specific addition or modification (different layouts, built-in sensors...)
A counterfeit is a clone of an Arduino board, with the same branding of an Arduino board.
More info on an article on the Arduino blog.

So is there a difference in the functionality?

A counterfeit will strive to give the very same functionality. As for clones and derivatives, I think it depends on manufacturer's choice.

Quality of the passive components (such as reset buttons that stick), poor/cold soldering that fails, misaligned connectors, etc are the hallmarks of counterfeits.


text:
How high of a baud rate can I go (without errors)?
The standard is 9600 baud. That's just the standard. Using a Arduino Uno SMD R2, what is the highest practical baud rate I can achieve?
Bonus points for the audacious: how would you go about creating an error checking mechanism and then increasing the baud rate ridiculous high to get high transfer rates?

It's worth noting that Arduino boards that use FTDI USB-serial ICs can go REALLY fast. The common FT232 can go 3 Megabaud (that's 3,000,000 baud) without issues. The use of a ATmega16U2 is the limiting factor.

My clone Arduino Nano that I got from eBay maxed out at 1,099,999. Seriously. It did. Once it reached 1,100,000, the output was garbled. laqq`na`fca`fga`fga`bcngaah````iin`ha`a`a`bga`fga`bcqpahhqfq```fh`oopa`bca`fca. It uses a CH340 chip for USB comms.

There are several factors here:

How high of a baud-rate can the ATmega328P MCU achieve?
How high of a baud-rate can the USB-Serial interface achieve?
What is the oscillator frequency on the ATmega328P?
What is the oscillator frequency on the USB-serial interface (if it has one)?
How tolerant is the USB-serial interface of baud-rate mismatch?

All of these factors are relevant to determining the maximum achieveable baud rate. The ATmega328P uses a hardware divisor from it's clock-rate to generate the base-clock for the serial interface. If there is no integer ratio from the main clock to the bit-time of the desired baud rate, the MCU will not be able to exactly produce the desired rate. This can lead to potential issues, as some devices are much more sensitive to baud-rate mismatch then others.
FTDI-based interfaces are quite tolerant of baud-rate mismatch, up to several percent error. However, I have worked with specialized embedded GPS modules that were unable to handle even a 0.5% baud rate error.
General serial interfaces are tolerant of ~5% baud-rate error. However, since each end can be off, a more common spec is +-2.5%. This way, if one end is 2.5% fast, and the other is 2.5% slow, your overall error is still only 5%.

Anyways. The Uno uses a ATmega328P as the primary MCU, and a ATmega16U2 as the USB-serial interface. We're also fortunate here in that both these MCUs use similar harware USARTs, as well as 16 Mhz clocks.
Since both MCUs have the same harware and clock-rate, they'll both have the same baud-rate error in the same direction, so we can functionally ignore the baud error issue.
Anyways, the "proper" answer to this question would involve digging up the source for the ATmega16U2, and working out the possible baud-rates from there, but since I'm lazy, I figure simple, empirical testing will work.
A quick glance at the ATmega328P datasheet produces the following table:

So given the max stated baud-rate of 2 Mbps, I wrote a quick test program:
void setup(){};

void loop()
{

  delay(1000);
  Serial.begin(57600);
  Serial.println("\r\rBaud-rate = 57600");
  delay(1000);
  Serial.begin(76800);
  Serial.println("\r\rBaud-rate = 76800");
  delay(1000);
  Serial.begin(115200);
  Serial.println("\r\rBaud-rate = 115200");
  delay(1000);
  Serial.begin(230400);
  Serial.println("\r\rBaud-rate = 230400");
  delay(1000);
  Serial.begin(250000);
  Serial.println("\r\rBaud-rate = 250000");
  delay(1000);
  Serial.begin(500000);
  Serial.println("\r\rBaud-rate = 500000");
  delay(1000);
  Serial.begin(1000000);
  Serial.println("\r\rBaud-rate = 1000000");
  delay(1000);
  Serial.begin(2000000);
  Serial.println("\r\rBaud-rate = 2000000");
};

And then looking at the relevant serial port with a serial terminal:

So it appears the hardware can run at 2,000,000 baud without problems.
Note that this baud rate only gives the MCU 64 80 clock-cycles per byte, so it would be very challenging to keep the serial interface busy. While the individual bytes may be transferred very rapidly, there is likely to be lots of time when the interface is simply idle.

Edit: Actual Testing!
The 2 Mbps is real:

each bit-time is 500 ns, which matches exactly with what is expected.
Performance issues! Overall packet length:
500 Kbaud:

1 Mbaud:

2 Mbaud:

Note: The noticeable overshoot is due to poor scope probe grounding practices, and is probably not real. I'm using the ground-clip-lead that's part of my scope probe, and the lead-inductance is likely the cause of the majority of the overshoot.
As you can see, the overall transmission length is the same for 0.5, 1 and 2 Mbaud. This is because the code that is placing the bytes in the serial buffer is poorly optimized. As such, you will never achieve anything better then an effective 500 Kbaud, unless you write your own serial libraries. The Arduino libraries are very poorly optimized, so it probably wouldn't be too hard to get a proper 2 Mbaud, at least for burst transmissions, if you spent a bit of time on it.

Nice illustration of the throughput limitation!

@jippie - I had the scope up, and was running the program in my answer that cycles through baud rates. It was very little additional work, and does illustrate the issue quite nicely. Also, the segmented memory on my scope is awesome.

DS2000 series? Does lowering the bitrate to 250kb actually double the time of the transmission? I think I can still easily spot the start/stop bits in the 500kb image.

@jippie - 4000 series. I loves me some 4 channels.

If you skip the Serial library, you can get much faster.

@Cybergibbons - Yep. See the note at the end about optimization.

Wow I thought that the 9600 baud was pretty good for an AVR device but I never expected 2 MBPS!

@AnnonomusPerson - If you switch to a 20 Mhz clock, you can do 2.5 Mbps.

@FakeName 20 Mhz main crystal or on the USB chip?

@AnnonomusPerson - You'd need to swap both, or use a FTDI usb-serial interface with a 20 Mhz ATmega328P oscillator. The ATmega328P can't do 2.5 Mbps without a 20 Mhz crystal/resonator. The same is true for any ATmega16U2 interfaces.

Great answer! Just one small correction: at 2 Mb/s, each byte transmission takes 80 CPU cycles, not 64. This is because, time-wise, each byte is worth 10 bits (1 start, 8 data, 1 stop).

@EdgarBonet - You are quite correct (and whoops). Fixed.

This is a great answer with one exception in that it doesn't account for the affects of the physical media (wire/cable used to connect to the other device). This will also be a major limiting factor in useful baud rates. Serial communication is pretty boring with just one device (loopback included). ::grin::

@linhartr22 - Wires only really come into play if they're long, as in 12"+. I think it's probably unlikely that too many people are using 100 foot long cables too much. Besides, the question was how high the arduino/ATmega baud rate can go, not how high an arbitrary cable assembly can go.

@ConnorWolf, I don't know if I agree 100% with this statement, "Since both MCUs have the same harware and clock-rate, they'll both have the same baud-rate error in the same direction, so we can functionally ignore the baud error issue."  I don't see how being the same UART would guarantee error in the same direction, as individual chips can still vary randomly right?--and although the chips both are the same freq, which means serial freq calculation error is in the same direction, I know the chips don't use the same clock source (16U2 uses crystal, 328 uses separate ceramic oscillator).

@GabrielStaples - You're missing the error I'm talking about. Basically, the way the ATmega UARTs work is they use an integer divider from the MCU clock to generate the serial timing. As such, some baud rates cannot be directly achieved, as the ratio between the baud rate and the system clock is not an integer. Generally, in this situation, the closest option is chosen, which results in the error I'm talking about here (abs(closest option - target baud) = err). This error will be matched between the two different parts.

While chips can vary, the operation of the UART is deterministic, so if you drive two parts with the same clock source, you'll get the same outputs (minus some small potential jitter).

@ConnorWolf, I see, so what this implies is that if you want to maximize the possibility of two devices to talk at a very high baud-rate, since this is asynchronous communication, you should have them both use the same frequency clock so that their actual baud-rates are skewed in the same direction, thereby aligning their bit-timing better? Is that right? ie: a 16MHz Arduino with a 16MHz USB to UART device is better than a 16Mhz Arduino with a 20MHz USB to UART device?

Basically, the issue is that you have a MCU with a 20 MHz clock, you might get a -1.5% error from the baud-rate divisor and the oscillator variance could be -1%. Then, if talking to a MCU with a 16 MHz osc which produces a +2% divisor error, and a +1.5% oscillator error, all your errors sum up to 5% in total. However, if you share the same reference oscillator frequency, the baud rate divisor errors match, so they cancel out, and the only relevant factor becomes the oscillator error.

Edit: Yeah, you've got it. However, the baud-rate generation logic is specific to a device/line-of-devices,so comparing between different manufacturers can be complicated.

I see now. I just checked the ATmega328 datasheet. Here's another table (from pg. 175) you might want to throw in your answer under the first one. It helps calculate the baud-rates to verify their errors in the table, and it makes it clear to me how they got their errors. For example, 115.2k shows -3.5% error for asynchronous normal mode (U2Xn=0). The formula goes: 16e6/(16*(8+1)) = 111111.11bps. That's the closest option. So, the error is 111111.11/115200 = 0.9645 = -3.5%.

Funny that the 1MBPS baud and 2MBPS baud will take the same time to transmit. It's because of the bytes not being copied fast enough?
This might also mean that you won't be able to receive the bytes at this speed. Ofcourse you can receive 1 byte at 2Mbaud, but for receiving multiple bytes, it depends on how fast the Arduino clears the serial buffer (and thus another byte can be received).

@Paul - The arduino doesn't do anything. The ATMega328p, on the other hand, does lots of stuff. Anyways, The throughput issues are a function of the efficiency of the transmit interrupt handler speed. As a rule, the code in the default arduino libraries is, well, really poor quality. It should be entirely possible to saturate the serial link for at least short bursts.

Do you think that  adding de-bouncing caps (~10-2pf) to ground may increase the stability?

@tuskiomi - What? No, the issue is the inductance of the ground clip wire that's part of my scope probe. The proper solution is to use a probe tip ground, but unless you're specifically trying to measure things like risetime, as long as you know the ringing isn't real, it's not a significant issue.

@ConnorWolf I'm not sure. for example, over on my question, The capacitors negated most  of the spiking, which would not happen if it was a probe thing.

@tuskiomi - That's to be expected, since the capacitors slow down the edge-rate, which means the inductance of the ground clip has a smaller effect. The point is, the spiking is 1. not harmful, 2. in the great majority of the cases, not actually real, but rather a measurement artifact. Additionally, if anything, the capacitors are worse for the circuit, since they're a load directly on the output drivers of the IC driving the bus. In general, there are very few cases where you ever want to add capacitance to a data bus.

Basically, before starting to stick capacitors everywhere, learn to use your tip ground, and check with that. Here is a white-paper by Teledyne LeCroy on the topic. Here is another from Tektronix.

Remember, even if your data rate is relatively slow, it's the edge rate that determines the effect the ground lead inductance has, rather then the edge frequency. Even slow little devices like ATMega ICs can produce quite fast edges.

There is also the issue of the ceramic resonator used for the MCU clock on some Arduinos, e.g. Arduino Uno (they don't technically lie on the product page, but the quartz oscillator is used only for the USB helper MCU, not the main microcontroller). It introduces an up to 0.5% error. This may or may not be significant, depending on the circumstances (for instance, using the second serial port). Perhaps cover this as well in the answer?

The error accumulates, so the last bit's time may already be off by close to 5% due to the ceramic resonator. How much can be tolerated as the accumulated error? 8%?

The Arduino Serial Monitor window limits you to 115200, but that's not the highest baud rate capable. You can read the Atmel and the FT232 (or whatever you're using) datasheets to find out the maximum but I am able to successfully use 230400 (twice as fast as the largest the Arduino Serial Monitor supports) with no issues.
If you want to see the results in your computer, you will need another serial monitor that supports other baud rate options. I like CoolTerm and Termite.
Do note that this heavily depends on your clock speed as well.
Here's a calculator to help you with calculating what's possible.

As you start going faster and faster, the limitation becomes the Serial library - it's implementation isn't very efficient.

website of link is dead

"The Arduino Serial Monitor window limits you to 115200," - That's no longer true. It goes up to 2Mbps

This is probably one of the few aspects where el-Cheapo boards differ from original boards. The maximum serial transfer rate is pretty much only limited by the quality of the board and its layout. Once the serial data enters either AVR or USB interface chip, the data will be processed differently from the serial UART protocol.
Keep in mind though that the microcontroller has some basic hardware to shift in/out serial data to/from the IO pins, but the absolute maximum rate is limited to the 16MHz clock (for AVRs). Once a byte is moved to the serial buffer, the UART hardware will take over and push out / pull in the bits on its own. An AVR at best reaches 16M instructions per second and the interrupts used to fill the serial buffer have some overhead (at least 8 clock ticks for the interrupt handling + instructions to save current state + several instructions for actually filling the buffer). At a given bitrate, the protocol will run at a whopping n bits per second, but your controller needs more time to fill the serial buffer than it needs to actually output the data, resulting in a lower average throughput than you expect and the UART idling for a relatively long time. Disadvantage is the increased probability for bit errors.
Another effect to remember is that all the overhead required to push data out onto UART (or pull it in) cannot be spent in your actual program, again affecting the average practical throughput. You can only use every instruction cycle once, either for filling the buffer or for computing the main loop.
The maximum throughput is therefore dependent on the application you use (how fast is data generated/computed/ready to move to/from the serial buffer) and the actual 'physical' bitrate is only a small part of the design decision.

I really, REALLY doubt any of the boards out there have layout issues severe enough to prevent a 2 Mhz signal from working fine. 2 Mhz isn't exactly high frequency.

@FakeName At least one board on my desk here has increased BER when I push serial speed. I usually use 9600, that is more than enough for most applications and is robust.

No kidding! Huh. I wonder how bad the layout has to be to have that happen? I'd suspect it's not layout as much as poor-tolerance resonators/crystals, though.

High baud-rates, particularly if U2Xn = 1 in the USART, tend to get pretty cranky about mismatch.

@FakeName I'm a dinosaur, I kinda like "9600 8N1" for all the wrong legacy reasons you can think of ;o)

Hell, I use 9600 myself for most debugging crap. It's not just you. It's just occationally I need to push a lot of data around, and knowing the limits is important.

I wouldn't be surprised if the increased BER is due to a cheap fake serial chip. (FTDI counterfeit) @ConnorWolf

Error checking is actually very easy and there is an AVR lib that does this in a one liner.
Read up on  util/crc16.h and you should be good to go in no time with the included examples.
CRC is quite robust and fast for simple applications.

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


text:
What are the SVG pins for on the SainSmart Uno clone?
I bought a SainSmart clone board which is compatible with the Arduino Uno R3. Alongside each of the standard IO pins, there is a row of 3 additional pins (male). They are arranged in columns, marked S, V, and G.
They can be seen on this image:

Most of them are immediately above the SainSmart and UNO logos. The SVG pins corresponding to the analog pins can be seen immediately below the microprocessor.
What are these pins for? Is this a standard format for some applications, or is it something unique to the SainSmart?

SVG = Signal, Voltage, Ground.
The Signal pin will carry the actual output, which may be high or low at any given time. It's basically just a male version of the corresponding standard GPIO pin. The Voltage pin will always be high (which can be 5v or 3.3v on this board, depending on the output level switch). The Ground pin is exactly what the name suggests -- it's connected to the board's ground.
This obviously means there is a lot of duplication. Why have two signal pins? And why bother having so many Voltage and Ground pins if they're all the same anyway?
The reason is simply convenience.
If you have a standalone external component (such as a motor), you would normally have to run 3 separate wires to it. With the regularly-spaced SVG pins on the board, you can instead use a 3-way cable with a suitable female header block. You can run that to an equivalent set of 3 pins on the external component. That means you are able to attach/detach the component by plugging/unplugging (effectively) a single cable.
I don't think the SVG idea is a 'standard' as such, largely because (in this form) it's only really of benefit to people who are experimenting or prototyping (as opposed to designing a more permanent system). It seems to be fairly popular among hobbyists and enthusiasts though. You just need to watch out for components which may put their equivalent SVG pins in a different order.

Servos usually have the same pinout so I guess the other benefit is that you can easily plug them in. http://www.imagesco.com/servo/connectors.jpg

Great point. I'd meant to mention servos, but obviously forgot!

This is also useful for plugging potentiometer to analog pins. If you plug the external pot pins to V & G and the middle pin to S, then you have an instant voltage divider.

I should point out that it appears the V pin in this configuration is not powerful enough to drive a standard servo.  This is unfortunate, because it is really convenient to plug a servo directly into this header.  It seems to work at first, but eventually the board will go into an unresponsive state, presumably because it can't drive that much current, or the voltage is fluctuating.  I'm not exactly sure why, but driving the servo off of the Arduino header 5v pin seems to work just fine.  Kind of a bummer.

It's not really a good idea to power a servo of of any pin on an Arduino, as those would either have too high a voltage or be sourced from the logic regulator, and as servos are notoriously power hungry and electrically noise, it is preferable that they not share the same regulator as logic.


text:
Are there different revisions of Arduino Uno SMD?
I know there are different revisions of the Arduino Uno itself, but are there any revisions of the SMD? If they are is SMD R2 identical to through-hole R2? I have a board marked R2 SMD and I am wondering if that is the only version that they produced in SMD format and just are signifying that it is compatible with the standard R2.

I have a R3 SMD uno, if that helps

@TheDoctor I don't think there is an R3 SMD. The R2, R3 are for the DIP boards. The only SMD board is the "Uno SMD"

@sachleen -  Yep i do - see my answer below

The only difference with the SMD Uno is the fact you can't remove the chip. There are also 2 extra analog comparators not connected to anything.
The SMD boards are compatible with the thru-hole boards, but they have SMD components, which apparently make them easier to make and cheaper. As I said before, the two extra analog inputs (A7 and A6) are left unconnected on the official boards.
Here is my Uno R3:


text:
Can a function be called automatically when an input changes?
Currently, my sketch is checking an input pin every time round the main loop. If it detects a change, it calls a custom function to respond to it. Here's the code (trimmed down to the essentials):
int pinValue = LOW;

void pinChanged()
{
    //...
}

void setup()
{
    pinMode(2, INPUT);
}

void loop()
{
    // Read current input
    int newValue = digitalRead(2);

    // Has the input changed?
    if (newValue != pinValue) {
        pinValue = newValue;
        pinChanged();
    }
}

Unfortunately, this doesn't always work properly for very short changes on the input (e.g. brief pulses), especially if loop() is running a bit slowly.
Is there a way to make the Arduino detect the input change and call my function automatically?

What you are looking for its a External Interrupt

You can do this using external interrupts. Most Arduinos only support this on a limited number of pins though. For full details, see the documentation on attachInterrupt().
Assuming you're using an Uno, you could do it like this:
void pinChanged()
{
    //...
}

void setup()
{
    pinMode(2, INPUT);
    attachInterrupt(0, pinChanged, CHANGE);
}

void loop()
{
}

This will call pinChanged() whenever a change is detected on external interrupt 0. On the Uno, that corresponds to GPIO pin 2. The external interrupt numbering is different on other boards, so it's important to check the relevant documentation.
There are limitations to this approach though. The custom pinChanged() function is being used as an Interrupt Service Routine (ISR). That means the rest of the code (everything in loop()) is temporarily stopped while the call is executing. In order to prevent disrupting any important timing, you should aim to make ISRs as fast as possible.
It's also important to note that no other interrupts will run during your ISR. That means anything relying on interrupts (such as the core delay() and millis() functions) may not work properly inside it.
Lastly, if your ISR needs to change any global variables in the sketch, they should usually be declared as volatile, e.g.:
volatile int someNumber;

That's important because it tells the compiler that the value could change unexpectedly, so it should be careful not to use any out-of-date copies/caches of it.

regarding the "brief pulses" mentioned in the question, is there a minimum time the pin must be at a state for it to trigger the interrupt? (obviously it'll be much less than polling, which depends on what else is happening in the loop)

@sachleen That will work as long as it does not happen during the execution of an ISR function (as explained in the answer); that's why pinChanged() should be as short as possible. Hence typically the minimum time should be the time to execute the pinChanged() function itself.

+1 for this very detailed answer which includes all imortant stuff one must care about when using interrupts!

In addition to declaring shared globals volatile, if the global variable is wider than 1 byte, as someNumber is, you must protect against the pin-change interrupt occurring between byte accesses by the program. A statement like someNumber +=5; involves adding the low bytes and adding the high bytes with carry included. These two (more, for wider variables) must not be divided by an interrupt. Turning the interrupts off and restoring them before and after the operation (respectively) is sufficient.

@sachleen - regarding the minimum pulse size. It is hard to find a definite answer in the datasheet, but judging by the timing for pin-change interrupts, they are latched within half a clock cycle. Once the interrupt is "remembered" it stays remembered until the ISR kicks in and deals with it.

Any state of change on any pin configured as digital input can create an interrupt. Unlike the unique vectors for the interrupts causes by INT1 or INT2 the PinChangeInt feature uses a common vector and then Interrupt Service Routine (aka ISR) for this vector needs to then determine which pin changed.
Fortunately PinChangeInt Library makes this easy.
PCintPort::attachInterrupt(PIN, burpcount,RISING); // attach a PinChange Interrupt to our pin on the rising edge
// (RISING, FALLING and CHANGE all work with this library)
// and execute the function burpcount when that pin changes

In the event that you want to detect a voltage passing a threshold, rather than being merely HIGH or LOW, you can use the analog comparator. Example sketch:
volatile boolean triggered;

ISR (ANALOG_COMP_vect)
  {
  triggered = true;
  }

void setup ()
  {
  Serial.begin (115200);
  Serial.println ("Started.");
  ADCSRB = 0;           // (Disable) ACME: Analog Comparator Multiplexer Enable
  ACSR =  bit (ACI)     // (Clear) Analog Comparator Interrupt Flag
        | bit (ACIE)    // Analog Comparator Interrupt Enable
        | bit (ACIS1);  // ACIS1, ACIS0: Analog Comparator Interrupt Mode Select (trigger on falling edge)
   }  // end of setup

void loop ()
  {
  if (triggered)
    {
    Serial.println ("Triggered!");
    triggered = false;
    }

  }  // end of loop

This can be useful for things like light-detectors, where you might need to detect a change from (say) 1V to 2V on an input.
Example circuit:

You can also use the Input Capture Unit on the processor, which will remember the exact time of certain inputs, by saving the current count of Timer/Counter 1. This lets you store the exact (well, almost exact) moment that the event of interest occurred, rather than introducing the delay (of probably a few microseconds) before an ISR can be used to capture the current time.
For timing-critical applications, this can give somewhat increased accuracy.
Example application: Turn your Arduino into a capacitor tester