message:
What can I do if I run out of Flash memory or SRAM?

According to the Arduino documentation, the ATmega328 has 32KB of Flash memory for the bootloader + uploaded sketch, and only 2KB SRAM for runtime data. The ATmega2560 has quite a bit more, totalling 256KB and 8KB respectively.

In either case, those limits seem rather small, especially when compared to similarly sized consumer devices, such as smartphones.

What can you do if you run out? E.g. if your sketch is too big, or you need to process a lot of data (such as strings) at runtime? Is there any way to expand the Flash or SRAM?

body:
**Optimisation**
Low-level programming for embedded systems is quite different from programming for general purpose devices, such as computers and cell phones. Efficiency (in terms of speed and space) is far more important because resources are at a premium. That means the very first thing to do if you run out of space is to look at what parts of your code you can optimise.

In terms of reducing program space (Flash) usage, the code size can be quite difficult to optimise if you're inexperienced, or if you're more used to programming for desktop computers which don't tend to need that skill. Unfortunately, there's no 'magic bullet' approach which will work for all situations, although it helps if you consider seriously what your sketch really *needs* to have. If a feature isn't needed, take it out.

Sometimes it's also helpful to identify where multiple parts of your code are the same (or very similar). You may be able to condense them into reusable functions which can be called from multiple places. However, be aware that sometimes trying to make code *too* reusable actually ends up making it more verbose. It's a tricky balance to strike that tends to come with practice. Spending some time looking at how code changes affect the compiler output can help.

Runtime data (SRAM) optimisation tends to be a bit easier when you're used to it. A very common pitfall for beginner programmers is using too much global data. Anything declared at global scope will exist for the entire lifetime of the sketch, and that isn't always necessary. If a variable is only used inside one function, and it doesn't need to persist between calls, then make it a local variable. If a value needs to be shared between functions, consider if you can pass it as a parameter instead of making it global. That way you'll only use SRAM for those variables when you actually need it.

Another killer for SRAM usage is text processing (e.g. using the `String` class). Generally speaking, you should avoid doing String operations if possible. They are massive memory hogs. For example, if you're outputting lots of text to serial, use multiple calls to `Serial.print()` instead of using string concatenation. Also try to reduce the number of string literals in your code if possible.

Avoid recursion if possible as well. Each time a recursive call is made, it takes the stack a level deeper. Refactor your recursive functions to be iterative instead.

**Use EEPROM**
EEPROM is used for long-term storage of things that only change occasionally. If you need to use large lists or look-up tables of fixed data, then consider storing it in EEPROM in advance, and only pulling out what you need when necessary.

Obviously EEPROM is quite limited in size and speed though, and has a limited number of write cycles. It's not a great solution to data limitations, but it might be enough to ease the burden on Flash or SRAM. It's also quite possible to interface with similar external storage, such as an SD card.

**Expansion**
If you've exhausted all other options, then expansion may be a possibility. Unfortunately, expanding Flash memory to increase program space isn't possible. However, it *is* possible to expand SRAM. This means you may be able to refactor your sketch to reduce code size at the expense of increasing data size.

Getting more SRAM is actually fairly straightforward. One option is to use one or more [**23K256**][1] chips. They are accessed via SPI, and there is the [**SpiRAM library**][2] to help you use them. Just beware that they operate at 3.3V **not** 5V!

If you're using the Mega, you could alternatively get SRAM expansion shields from [**Lagrangian Point**][3] or [**Rugged Circuits**][4].

  [1]: http://ww1.microchip.com/downloads/en/DeviceDoc/22100D.pdf
  [2]: http://playground.arduino.cc/Main/SpiRAM
  [3]: http://lagrangianpoint.net/store/arduino-mega-sram-expansion-shield-kit
  [4]: http://www.ruggedcircuits.com/html/quadram.html


sender: user

sender: assistant

body:
When you upload your code to your Arduino, say an Uno for example, it'll tell you how many bytes it uses up out of the 32K available. That's how much flash memory you have (think computer hard disk). While your program is running, it's using whats called SRAM, and there is much less of that available.

Sometimes you'll notice your program behaving oddly at a point that you haven't even touched in a while. It could be that your most recent changes cause it to run out of memory (SRAM). Here are a few tips on how to free up some SRAM.

## Storing strings in Flash instead of SRAM.

One of the most common things I've seen is the chip running out of memory because there are too many long strings.

Use the `F()` function when using strings so they are stored in Flash instead of SRAM, since you have much more of that available.

    Serial.println(F("This string will be stored in flash memory"));

## Use the right data types

You can save a byte by switching from an `int` (2 bytes) to a `byte` (1 byte). An unsigned byte will give you 0-255 so if you have numbers that don't go higher than 255, save a byte!

## How do I know I'm running out of memory?

Usually you'll observe your program behaving strangely and wonder what went wrong... You didn't change anything in the code near the point where it's messing up, so what gives? It's running out of memory.

There are a couple of functions to tell you how much available memory you have.

[Available Memory][1]

  [1]: http://playground.arduino.cc/Code/AvailableMemory


body:
In addition to what others have said (on which I fully agree), I would advise to read [this adafruit article][1] about memory; it's well written, explains a lot of things about memory and provide hints on how to optimize it.

At the end of the read, I think you would get a quite complete answer to your question.

To sum it up, you have 2 possible optimization targets (depending on where you memory problems are located):

- **Flash** (ie Program Memory); for this, you can:
    - remove dead code (e.g. any code that is included but not used) and unused variables (that one also helps with SRAM)
    - factor out duplicated code
    - remove the bootloader altogether (you can gain between 0.5K for a UNO and 2 or 4K for other Arduino models); this has some downsides though
- **SRAM** (ie stack, heap and static data); for this you can:
    - remove unused variables
    - optimize the size of each variable (eg don't use long -4 bytes- if you need only int -2 bytes)
    - use the right scope for your variables (and prefer stack to static data when possible)
    - reduce buffers size to the strict minimum
    - move constant data to PROGMEM (ie your static data will stay in Flash memory and won't get copied to SRAM at program start); that also applies to constant strings for which you can use `F()` macro)
    - avoid dynamic allocation if it is not absolutely necessary; you will avoid a *fragmented heap* that may not shrink even after freeing memory

An additional approach to reduce SRAM usage is also described (but seldom used, because it is a bit heavy when coding and not very efficient), it consists in using EEPROM to store data built by your program, but not used until later when some conditions occur, when data can be loaded back from EEPROM.

  [1]: http://learn.adafruit.com/memories-of-an-arduino/you-know-you-have-a-memory-problem-when-dot-dot-dot


body:
There are two things to do if you run out of storage:

* Somehow "optimize" your code so it needs less storage; or at least uses less of the particular kind of storage that you ran out of (and uses more of the kind of storage that you still have plenty of). Or,
* Add more storage.

There are lots of tips online on how to do the first (and for the vast majority of things people do with the Arduino, the build-in storage is more than enough after "optimizing").
So I'll focus on the second:

There are 3 things that use up flash or SRAM; each one needs a slightly different approach to adding storage:

* variable storage: it is possible to expand SRAM, as sachleen has already pointed out.
**SRAM, FRAM, and NVSRAM** are all appropriate for rapidly-changing variables.
(While in principle you could use flash to store variables, then you have to worry about flash wear-out).
SPI (a serial protocol) is the easiest to connect to the Arduino.
The [SpiRAM library][1] works with the Microchip [23K256][2] serial SRAM chip.
The Ramtron [FM25W256 serial FRAM][3] chip (now owned by Cypress) also uses SPI.
The Cypress [CY14B101 NVSRAM][4] also uses SPI.
Etc.

* constant data that needs to still be there the next time the power comes on: this is almost as simple as expanding SRAM. There are many external **EEPROM, FRAM, NVSRAM, and FLASH** storage devices available.
Currently the lowest cost per MB are **SD flash cards** (which can accessed via SPI).
The Ramtron FM25W256 (see above), the Cypress CY14B101 (see above), etc. can also store constant data.
Many expansion shields include a SD card slot,
and several [libraries][5] and [tutorials][6] support reading and writing to (flash) SD cards.
(We can't use SRAM for this, because SRAM forgets everything when the power goes out).

* executable code: Unfortunately, expanding an Arduino's Flash memory to increase program space isn't possible. However, a programmer can always refactor a sketch to reduce code size at the expense of increasing data size and making it run slightly slower. (In theory, you could go so far as translate your entire sketch into some interpreted language, store that version of your sketch on a SD card, and then write a interpreter for that language that runs on the Arduino to fetch and execute instructions from the SD card -- [Forth on Arduino][7], a BASIC interpreter, a Tom Napier Picaro interpreter, some application-specific language, etc.).

  [1]: http://playground.arduino.cc/Main/SpiRAM
  [2]: http://ww1.microchip.com/downloads/en/DeviceDoc/22100D.pdf
  [3]: http://www.cypress.com/?docID=44787
  [4]: http://www.cypress.com/?rID=45568
  [5]: http://arduino.cc/en/Reference/SDCardNotes
  [6]: http://learn.adafruit.com/adafruit-micro-sd-breakout-board-card-tutorial/look-out
  [7]: http://playground.arduino.cc//CommonTopics/ForthOnArduino


message:
Is it possible to program an Arduino Pro Mini using an Arduino Uno R3?

I've recently received an Arduino Pro Mini as a gift, and I don't have an external USB programmer to program the Pro Mini. However, I do own an Arduino Uno R3, and I think it would be possible because they both have the same clock speed and micro-controller (16Mhz with an atmega328).

Is it possible to program an Arduino Pro Mini using an Arduino Uno?
If yes, how does one do so?

body:
Just hook up the pins (RX, TX, reset, Power, and Ground) to the corresponding pins on your Uno.

You may have to take the ATMega328 out of your Uno for this to work.

Keep in mind that you need to hook it up to the correct power pin! If your pro mini is running at 3.3v then you must hook it up to the 3.3 pin on your Uno.

Check out the [ArduinoToBreadboard][1] page for a bit more info. Scroll down to "Uploading Using an Arduino Board". Although it shows you how to program an Arduino on a breadboard, the wiring is the same.

  [1]: http://arduino.cc/en/Tutorial/ArduinoToBreadboard


body: you can program with an SMD board, you dont link the reset line, hold down the reset on the uno throughout the whole process, and tap the reset on the mini soon as the ide says upload to upload the sketch, by holding the uno in reset it doesn't interfere with the serial comms


body: There is another method by which you can upload your sketch programs.  Program the UNO with the "Arduino as ISP" sketch and connect the pro mini via the SPI pins (plus reset line).  See "Upload with Programmer" on the Arduino website and elsewhere on the internet including stack exchange.  This method will allow you to use the full memory of the chip and avoid using the bootloader, but you will need to upload with SPI each time.


message:
What is the real lifetime of EEPROM?

ATMEL says the cell lifetime of an EEPROM cell is about 100,000 write cycle/ cell.
Is this actually how the EEPROM performs in the wild?

If I do not change the value of a cell, does this stress the lifetime? For example, if I write the value `0xFF` to the same cell again and again, is this any different to writing `0x00`, `0xFF`, `0x00` etc.

body:
I once ran an experiment on an external EEPROM with 1 million max rated cycles. It took about 6 million cycles to become majorly corrupted, and before that it had progressed having sporadic amounts of corruption.

When you say you do not change the value, i am assuming you are writing the same data to an address multiple times. This almost certainly would stress the life, although it would probably not stress the surrounding cells.


body:
As you state, the internal EEPROM has a lifetime of 100,000 write cycles. This isn't a guess - a very significant proportion of ATmega328 will reach this number with no issues. I have tested three processors before, and all reached 150,000 cycles with no issues.

It is important to note the failure mode of EEPROM. Most "EEPROM destroyer" projects repeatedly read/write until the data is not written at all. Before this point, the EEPROM will still be damaged. This would be manifested by data not being retained for a reasonable period. It is unwise to rely on anything more than 100,000 write cycles for this reason.

EEPROM is different to the RAM on an ATmega. Writing to it is not simple or quick, but it is wrapped up in a [friendly Arduino library][1], hiding this complexity from the user.

The first level of indirection is the [EEPROM library][2], which is trivially simple], just calling two other functions for read and write. This calls eeprom_write_byte, found [here][3].

This function uses inline assembly, so might not be easily understood. There is a comment that is easily understood though:

> Set programming mode: erase and write

This hints to one of the complexities of dealing with EEPROM - to write to
it, you first need to erase it. This means that if you call EEPROM.write(), it will perform a write cycle regardless of the value you are writing.

This means that repeatedly writing 0xFF will likely have the same effect as writing 0xFF,0x00,0xFF,0x00 etc.

There are ways to work around this - you can try calling EEPROM.read() before EEPROM.write() to see if the value is already the same, but this takes additional time.

There are other techniques to avoid excessive EEPROM wear, but their use depends on your application.

  [1]: http://arduino.cc/en/Reference/EEPROM#.Uv8RdHnG

  [2]: https://github.com/arduino/Arduino/blob/598ab1d5c003e02b6bb193640fac8526ad8ab912/libraries/EEPROM/EEPROM.cpp
  [3]: https://github.com/arduino/Arduino/blob/598ab1d5c003e02b6bb193640fac8526ad8ab912/build/windows/eeprom.h


body:
http://hackaday.com/2011/05/16/destroying-an-arduinos-eeprom/

>The Arduino was plugged into a wall wart and sat, “behind a couch for a couple of months.” The EEPROM saw it’s first write error after 47 days and 1,230,163 cycles. This is an order of magnitude better than the spec on the atmel datasheet, but similar to the results of similar experiments.


body:
The magic solution - if you dont want to code what Cybergibbons said about reading before writing, is the EEPROM.update() function. It does exactly that:

EEPROM.update(address, value);

will only write and stress the memory if value is different from that already stored.


body:
Couple years ago I made run time logger for piece of equipment.  Memory got corrupted after 6 months 40 hours logged with 1s resolution => 144000 writes.
My solution was to spread writes over entire eeprom.


message:
Are there any good and maintained libraries for using DS2482 I2C to 1-Wire bridge?

The [DS2482-100][1] and [DS2482-800][2] are I2C to 1-Wire bridges which are useful for driving complex 1-Wire networks.

These are natively supported by a number of packages in Linux so you can interface easily with them on a Raspberry Pi.

I was surprised to find there is not an obvious library for accessing them on an Arduino however.

I have found the following:

 - An [Arduino library][3] - has some quirks and not-maintained.
 - [Part][4] of AVR-Liberty - less quirks, not sure if maintained, not "Arduino" as
   such, more AVR.

It is helpful to be able to rely on maintained libraries to deal with any changes to the Arduino environment.

Arduino libraries are often easier to use than ones designed for AVR in general, which means more people are able to use the software.

Is there a better library available?

  [1]: http://www.maximintegrated.com/datasheet/index.mvp/id/4382
  [2]: http://www.maximintegrated.com/datasheet/index.mvp/id/4338
  [3]: https://github.com/paeaetech/paeae
  [4]: https://github.com/dreamiurg/avr-liberty/blob/e08e41d073be523a8a8e4202afb5b3c1e061d300/src/rsl/ds2482.c

body:
I have implemented [a library][1], based on the Paeaetech one linked to above, but tidying up defines, fixing the listed issue, adding lookup table based CRC and support for passively powered sensors.

  [1]: https://github.com/cybergibbons/DS2482_OneWire


body:
I believe the library linked by Cybergibbons has a bug in

uint8_t OneWire::wireSearch(uint8_t *address)

A discrepancy at i = 0 (bit zero in this library, id_bit_number = 1 in a Maxim example) only follows the direction = 1 path and fails to find ROM addresses where bit zero = 0 (i.e. even family codes are missed when mixed devices, some with even and others with odd family codes, are present on the 1-wire bus).

A fix I have just implemented and appears to work is to modify the library to declare searchLastDiscrepancy and last_zero as int8_t (not uint8_t), initialise/reset them to -1 (not zero) and, near the end of the method

        if (!last_zero)
                searchLastDeviceFlag = 1;

becomes

        if (last_zero == -1)
                searchLastDeviceFlag = 1;

I hope that helps.


message:
Controlling mains (230 V) supply up to 5/10 amps using Arduino

I am looking for a simple, low cost solution to control on/off of mains supply to certain equipment. The control will be done using one of the output pin of Arduino Uno.

The input trigger and how to control it is application dependent.  e.g. controlling an equipment or controlling supply to section of home but in principle mains control module implementation remains same. So looking for solution which is safe while doing connections as well as while in use in  indoor conditions for years.

body:
The [PowerSwitch Tail 2](https://www.sparkfun.com/products/10747) is a great way for experimenters to control mains voltages. It is insulated and internally decoupled, so you only have to hook up 5v, gnd, and a signal line to control it.

This model supports only 120V, but there are also [kits][1] for 230V.

![enter image description here][2]

image from sparkfun

  [1]: http://www.powerswitchtail.com/Pages/PSTKKit.aspx
  [2]: https://i.stack.imgur.com/kHPjV.png


body:
Playing with mains is dangerous - so best to use a kit designed for that purpose. Be careful with units designed in the US - their safety requirements are a bit different from UK and Europe.

For example the Power Switch Tail kits do not include a fuse - if the appliance being controlled goes faulty and starts drawing a bigger current, the switch could burn up.

Here is one designed with Uk safety features in mind:

[http://www.sf-innovations.co.uk/mains-switch-widget.html][1]

  [1]: http://www.sf-innovations.co.uk/mains-switch-widget.html


message:
How to power Arduino externally for long term?

For a robotic project, I need to keep an Arduino powered up for a long time in an outdoor environment. What can I use to power the board?
If battery is the only solution, can the device tell me remotely that battery is getting low?

It needs to be powered for at least few days ( at least). The unit monitors an outdoor sensor that is shaded from sun but still exposed to wind and moisture. The unit does not move.

body:
There are several options for Arduino power in an external environment.

* [Wall wart](https://www.sparkfun.com/products/298): Connects to a wall socket, provides a great long-term source of power
* [Rechargeable battery](https://www.sparkfun.com/products/8483): Doesn't last long, but they can be recharged and monitored with a [low cost board](https://www.sparkfun.com/products/10217)
* [Alkaline Battery](https://www.sparkfun.com/products/10218): Last longer, there are some monitoring systems available.
* [Solar](https://www.sparkfun.com/products/7840): Only works when the sun is out, unless you combine it with a rechargable battery ([example](https://www.sparkfun.com/products/11496))
* Nuclear power: NOT RECOMMENDED!!!


message:
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!

body:
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][1]

  [1]: https://en.wikipedia.org/wiki/Quartz_clock

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


body:
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


body:
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:

1. 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.
2. then repeatedly call millis() until at least 120h ("arduino hours", that would be around 5 days) have elapsed
3. 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)
4. 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)
5. 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.


body:
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][blog post], 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:

[![Allan deviation of Arduino Clock Frequency][adev plot]][adev plot]
<sub>(source: [jorisvr.nl](http://jorisvr.nl/images/arduinofreq/allandev_small.png))</sub>

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.

[blog post]: http://jorisvr.nl/article/arduino-frequency
[Allan deviation]: https://en.wikipedia.org/wiki/Allan_variance
[adev plot]: https://i.stack.imgur.com/Cy5Le.png


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

*

![enter image description here][1]
                    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)?

  [1]: https://i.stack.imgur.com/Z1yB0.png
  [2]: https://i.stack.imgur.com/6tnNC.png

body:
Have you tried a low pass filter? I found an example [here](http://arduino.cc/en/Tutorial/Smoothing) an another one [here](http://playground.arduino.cc/main/smooth).

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


body:
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][1].

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

  [1]: http://playground.arduino.cc/Main/Average


body:
[Microsmooth][1] 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"

  [1]: https://github.com/AsheeshR/Microsmooth


body:
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][1]
* [Paul Badger: digitalSmooth digital low-pass filter with outlier rejection][2]
* [David A. Mellis and Tom Igoe: Smoothing tutorial][3]
* [Majenki: Average Library][4]

signal-smoothing libraries at github:

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

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

  [1]: http://playground.arduino.cc/Main/Smooth
  [2]: http://playground.arduino.cc/Main/DigitalSmooth
  [3]: http://arduino.cc/en/Tutorial/Smoothing
  [4]: http://playground.arduino.cc/Main/Average
  [5]: https://github.com/AsheeshR/Microsmooth
  [6]: http://github.com/jeroendoggen/Arduino-signal-filtering-library
  [7]: http://github.com/karlward/Filter
  [8]: http://github.com/sebnil/FIR-filter-Arduino-Library
  [9]: http://github.com/daPhoosa/MedianFilter
  [10]: http://github.com/arc12/LibSimpleFilters
  [11]: http://github.com/sebnil/Selfbalancing-robot


body:
Check out [the Arduino Smooth library][1]. 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.

  [1]: https://github.com/ripred/Smooth


message:
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?

body:
A simple IR diode like [this](https://www.sparkfun.com/products/10266) can receive raw IR data. There are several chips which are designed to decode these signals, such as [this](https://www.sparkfun.com/products/8753) one.

![Ir diode][1]  ----------------  ![Ir decoder chip][2]

Ir Diode ------------------------------- Ir Decoder

  [1]: https://i.stack.imgur.com/yuUSq.png
  [2]: https://i.stack.imgur.com/Pj4C0.png


body:
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][1] 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][2].

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.

  [1]: http://learn.adafruit.com/ir-sensor/ir-remote-signals
  [2]: https://github.com/shirriff/Arduino-IRremote


body:
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()`][1]. 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.

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


body:
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](http://pastebin.com/gpFxDbkP) is a file which contain recorded values of a Videocon DTH setup box's remote


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

body:
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][1] (that means [Accessory Development Kit][2]).

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][3].

  [1]: http://arduino.cc/en/Main/ArduinoBoardADK
  [2]: https://developer.android.com/tools/adk/index.html
  [3]: http://www.wrox.com/WileyCDA/WroxTitle/Professional-Android-Open-Accessory-Programming-with-Arduino.productCd-1118454766,descCd-DOWNLOAD.html


body:
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)][5] [(b)][6]
* The IOIO board [(a)][1] [(b)][2]
* The Android Accessory Development Kit (ADK) [(a)][3] [(b)][4] (c)

(The Amarino [(a)][9] and Cellbots [(a)][7] [(b)][8] take yet another completely different approach).

  [1]: https://www.sparkfun.com/tutorials/280
  [2]: https://github.com/ytai/ioio/wiki
  [3]: http://makezine.com/2011/05/12/why-google-choosing-arduino-matters-and-the-end-of-made-for-ipod-tm/
  [4]: http://developer.android.com/tools/adk/
  [5]: https://en.wikipedia.org/wiki/Microbridge
  [6]: https://code.google.com/p/microbridge/
  [7]: http://www.cellbots.com/
  [8]: https://code.google.com/p/cellbots/
  [9]: http://www.amarino-toolkit.net/


body:
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


body:
## 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](https://play.google.com/store/apps/details?id=com.primavera.arduino.listener)
 - 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](https://www.google.com/search?q=arduino+bluetooth&qscrl=1&tbm=isch&imgil=WyPC4O05Xn4rhM%3A%3Bhttps%3A%2F%2Fencrypted-tbn2.gstatic.com%2Fimages%3Fq%3Dtbn%3AANd9GcSfTtWqIuN9YYdd90OO_tlxsvLUYhV_pl7NfaMhHDzSRq9N6W9rNA%3B1200%3B1200%3B1soQc4CzMzh0MM%3Bhttp%253A%252F%252Fm.dhgate.com%252Fproduct%252Fjy-mcu-arduino-bluetooth-wireless-serial%252F151048482.html&source=iu&usg=__KyMLS4aeubxJnDaMvprgRgADxAs=&sa=X&ei=1BUCU635IYmEygGO1oHwCQ&ved=0CGkQ9QEwBg&biw=1280&bih=899) (Note: I just picked a random link but there are hundreds of similar BT adapters)


body:
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


message:
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?

body:
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()`][1], 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][2], 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][3]

  [1]: http://arduino.cc/en/Serial/begin
  [2]: http://en.wikipedia.org/wiki/Parity_bit
  [3]: http://en.wikipedia.org/wiki/Asynchronous_serial_communication


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


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


message:
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?

body:
Too long for a comment...

Look at some of their docs for [examples][1]. 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][2]):

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

  [1]: http://www.libelium.com/development/waspmote/examples/ga-11-co-sensor-on-socket4-reading/
  [2]: http://www.libelium.com/forum/viewtopic.php?f=15&t=8811


message:
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?

body:
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][1] (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](http://www.technologystudent.com/elec1/transis1.htm)

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](https://www.sparkfun.com/products/10636)

![from Sparkfun][2]

  [1]: https://en.wikipedia.org/wiki/MOSFET
  [2]: https://i.stack.imgur.com/71AlP.png


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


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

> Related to:
> https://arduino.stackexchange.com/questions/189/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?

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


body:
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][1])

So, here, `digitalPinToBitMask` seems to be using `pin` to compute an intermediate bit. Exploring further, `digitalPinToBitMask` is a macro defined in [`Arduino.h`][2] 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`][3] 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`.

  [1]: https://github.com/arduino/Arduino/blob/master/hardware/arduino/cores/arduino/wiring_digital.c
  [2]: https://github.com/arduino/Arduino/blob/cc6d7cdbd1f97aa90ffcb759b5fc4c5ba553304e/hardware/arduino/cores/arduino/Arduino.h
  [3]: https://github.com/arduino/Arduino/blob/2a8c06381fbc6fdb7e6363d0cb5d1c16019ccab0/hardware/arduino/variants/standard/pins_arduino.h


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

body:
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][1]

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.

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


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


body:
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](http://wirespeed.xs4all.nl/mediawiki/index.php/Udev_rules_file_for_Arduino_boards).

Other than that, what you are describing is pretty much a simple form of [version control](https://en.wikipedia.org/wiki/Revision_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();`.


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

 1. 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.
 2. 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.
 3. 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).
 4. There are many chips with globally unique serial IDs in them e.g. the Microchip [11AA02E48][1], 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.
 5. 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.

  [1]: http://www.microchip.com/wwwproducts/Devices.aspx?dDocName=en538621


body:
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](http://www.gammon.com.au/forum/?id=11633). 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.


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


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


body:
    #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


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

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


body:
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][1]:

> 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][2] with [example code][3]. This [SO question][4] might be useful, too.

[ArduinoThread][5] is a good one too.

  [1]: http://dunkels.com/adam/pt/
  [2]: http://harteware.blogspot.com/2010/11/protothread-powerfull-library.html
  [3]: http://harteware.blogspot.com/2010/11/protothread-and-arduino-first-easy.html
  [4]: https://stackoverflow.com/questions/6230878/some-problems-with-arduino-protothreads
  [5]: https://github.com/ivanseidel/ArduinoThread


body:
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/


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


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


body:
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


body:
A simple solution is to use a [Scheduler][1]. 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()][2] or [delay()][3]. 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][4]. 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][5] 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][6] 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][7] and [Semaphore][8].

  [1]: https://github.com/mikaelpatel/Arduino-Scheduler
  [2]: https://www.arduino.cc/en/Reference/SchedulerYield
  [3]: https://www.arduino.cc/en/Reference/Delay
  [4]: https://github.com/mikaelpatel/Arduino-Scheduler/tree/master/examples
  [5]: https://github.com/mikaelpatel/Arduino-Scheduler/blob/master/examples/SchedulerBlinkTemplateFunctions/SchedulerBlinkTemplateFunctions.ino
  [6]: https://github.com/mikaelpatel/Arduino-Scheduler/blob/master/examples/SchedulerBenchmark/SchedulerBenchmark.ino
  [7]: https://github.com/mikaelpatel/Arduino-Scheduler/blob/master/Scheduler/Queue.h
  [8]: https://github.com/mikaelpatel/Arduino-Scheduler/blob/master/Scheduler/Semaphore.h
  [9]: https://github.com/mikaelpatel/Arduino-Scheduler/blob/master/examples/SchedulerSemaphore/Semaphore.h


body:
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:

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

How to use
----------
Threads can be created via c++ inheritance

```c++
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
```c++
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:
```c++
ThreadHandler::getInstance()->enableThreadExecution();
```


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

  * [Home page](https://nxg.me.uk/dist/pqrst/)
  * [Class-level documentation](https://nxg.me.uk/dist/pqrst/docs/)
  * [Repository](https://bitbucket.org/nxg/pqrst/), with [downloads](https://bitbucket.org/nxg/pqrst/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());
    }


message:
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)?

body:
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][1] is that you can only communicate with one device at a time.

This means you'll have to make a call to [`listen()`][2]

    sensor1.listen()

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

  [1]: http://arduino.cc/en/Reference/SoftwareSerial
  [2]: http://arduino.cc/en/Reference/SoftwareSerialListen


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


body:
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][1] 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][2]. 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

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

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

  [1]: https://www.pjrc.com/teensy/td_libs_NewSoftSerial.html#cpu
  [2]: https://www.pjrc.com/teensy/td_libs_AltSoftSerial.html
  [3]: https://www.sparkfun.com/products/9981


message:
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?**

body:
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](http://arduino.cc/en/Main/FAQ)

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


body:
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][1] on the Arduino blog.

  [1]: http://blog.arduino.cc/2013/07/10/send-in-the-clones


message:
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?

body:
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][1] and [Termite][2].

Do note that this heavily depends on your clock speed as well.

Here's a [calculator][3] to help you with calculating what's possible.

  [1]: http://freeware.the-meiers.org/
  [2]: http://www.compuphase.com/software_termite.htm
  [3]: http://www.wormfood.net/avrbaudcalc.php


body:
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:
![enter image description here][1]

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:

![enter image description here][2]

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:
![enter image description here][3]
each bit-time is 500 ns, which matches exactly with what is expected.

Performance issues! Overall packet length:
500 Kbaud:
![enter image description here][4]

1 Mbaud:
![enter image description here][5]

2 Mbaud:
![enter image description here][6]
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.

  [1]: https://i.stack.imgur.com/P8kN2.png
  [2]: https://i.stack.imgur.com/US17S.png
  [3]: https://i.stack.imgur.com/APzfe.jpg
  [4]: https://i.stack.imgur.com/rlBti.jpg
  [5]: https://i.stack.imgur.com/9ACpH.jpg
  [6]: https://i.stack.imgur.com/vUDoN.jpg


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


body:
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`][1] and you should be good to go in no time with the included examples.

CRC is quite robust and fast for simple applications.

  [1]: http://www.nongnu.org/avr-libc/user-manual/group__util__crc.html


message:
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:

![Photo of SainSmart Uno R3 clone board][1]

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?

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

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


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

body:
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:

![enter image description here][1]

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


message:
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?

body:
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()`][1].

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.

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


body:
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](http://playground.arduino.cc/Main/PinChangeInt) 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