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

<!-- language-all: lang-C++ -->

    volatile boolean triggered;

    ISR (ANALOG_COMP_vect)
      {
      triggered = true;
      }

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

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

      }  // end of loop

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

Example circuit:

![enter image description here][1]

You can also use the Input Capture Unit on the processor, which will remember the exact time of certain inputs, by saving the current count of Timer/Counter 1. This lets you store the exact (well, almost exact) moment that the event of interest occurred, rather than introducing the delay (of probably a few microseconds) before an ISR can be used to capture the current time.

For timing-critical applications, this can give somewhat increased accuracy.

Example application: [Turn your Arduino into a capacitor tester](http://www.gammon.com.au/forum/?id=12075)

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


sender: user

message:
How precise is the timing of pulseIn()?

I've been using the `pulseIn()` function for processing PWM-based binary data encoding. It works well for distinguishing pulses which are significantly different lengths, e.g. 500us vs. 1500us. That makes it more than sufficient for handling typical IR remotes.

However, I want to make my own IR system which can use more than 2 pulse lengths, so that data transfer can occur faster. Ideally, I'd like to use 8 different pulse lengths for octal encoding (e.g. 200us, 400us, 600us, etc.).

I've noticed quite significant variations in the values returned by `pulseIn()` though (+/- 10%). I expect at least some of it is introduced by the IR transmitter and receiver modules, but I don't have good enough equipment to verify that.

Assuming I can mitigate that external error, is `pulseIn()` likely to be precise enough to distinguish such similar pulses?

sender: assistant

body:
Here is some test data of a `pulseIn` test. One Arduino sent what were supposed to be 14us pulses, and the other spat out this data:

> 18,18,18,12,18,18,18,18,18,18,18,18,18,18,18,18,18,24,19,18,18,18,18,18,24,18,18,18,19,18,18,12,18,18,19,18,18,18,18,18,18,18,18,18,18,18,19,18,19,24,18,18,18,18,18,18,18,24,18,18,18,18,18,18,18,18,18,18,18,18,18,19,18,18,18,18,18,18,18,18,18,18,19,18,18,18,11,18

As you can see, the pulses are by no means accurate. The time would be more accurate if the sending and recieving ends were written in assembly, or even offloaded to their own processors.


body:
The pulsein() function is very lossy, in that it is a hard loop and returns a number * the assumed clock cycles it takes for per loop

    ...
    // wait for the pulse to stop
    while ((*portInputRegister(port) & bit) == stateMask) {
      if (numloops++ == maxloops)
        return 0;
      width++;
    }

    // convert the reading to microseconds. The loop has been determined
    // to be 20 clock cycles long and have about 16 clocks between the edge
    // and the start of the loop. There will be some error introduced by
    // the interrupt handlers.
    return clockCyclesToMicroseconds(width * 21 + 16);

----------

The most accurate method for capturing the timing of a PIN is use the INPUT CAPTURE FEATURE. Look at the [this example ](https://gist.github.com/mpflaga/4404996). It enables the input capture at 1x of CPU for max resolution and each edge of the input pin captures the timer's clock value for reading from the generated Interrupt service. It also enables the timer overflow interrupt to as to maintain large absolute time, to be capture. Since the 1x will roll rather quickly. The captures store the time into an array for reading by the main loop.

----------

Where for signals over IR the typical library to use is [shirriff/Arduino-IRremote](https://github.com/shirriff/Arduino-IRremote) library. Where it has several demo's that will read and send the IR from a demodulated signal. To allow one to build a sketch of their own design. This code originally creates a timer interrupt that polls the input pin at a rate determine by

    #define USECPERTICK 50  // microseconds per clock interrupt tick

in the IRremote.h file. For my purposes I have change it to 25 us. Where I find this still can be intermittently missing pulse streams.

Note the demodulation is best accomplished within the IR receiver, which in turn outputs this signal of interest. Where to add some background. Using the typical 38KHz modulation, equates to a minimum resolution of 26.3uS per pulse's cycle. sherriff's library shows typically most bauds or bits are in the order of 10+ pulses. Which appear to meet your desired timings.

[microtherion/Arduino-IRremote](https://github.com/microtherion/Arduino-IRremote) fork of shirriff's work improves the reception by replacing the timer interrupt polling of the pin with the use of PinChangeInterrupts. Which I have merged into my own [mpflaga/Arduino-IRremote](https://github.com/mpflaga/Arduino-IRremote) fork, that adds several other features.

So you could use any of the above libraries. Or create your own app that uses either of the below to capture edges.

 1. polls on a Timer event (e.g. 50uS)
 2. captures the micros() on a PinChangeInterrupt
 3. uses Input Capture Interrupts to grab the exact time


message:
Why is int only 2 bytes?

When using C/C++ on other platforms, the `int` type is typically 4 bytes (or potentially more). However, on Arduino, it's only 2 bytes.

Why is it different? Does it affect performance if I always use the 4 byte `long` instead?

body:
The ATmega328 used in a lot of Arduinos is a 8-bit microcontroller. This means that registers are 8-bits, the data bus is 8-bits, the ports are 8-bits. There are some minimal 16-bit aspects to the system (e.g. one of the timers), but nearly everything is 8-bits.

Therefore, most operations handle 8-bits at a time. Working on anything except 8-bits (i.e. 16-bit or 32-bit integers and floating point numbers) requires what could essentially be described as software emulation, where the compiler uses multiple instructions to work on these larger variables.

8-bits is obviously adequate to address a 8-bit port. It's also enough to deal with many loop counters, return values, and ASCII characters. It isn't really enough though when dealing with numbers. A signed 8-bit int (int8_t) can only represent -128 -> +127. Unsigned (uint8_t) can only represent 0 -> 255.

8-bit integers are quite limiting. C/C++ int must represent at least -32,678 -> +32,767 so maps to int16_t - the smallest size that will do so. This gives a good balance of range and efficiency. This is especially important when beginners are learning - overflow is not really something that non-programmers understand.

There is a performance impact of doing this however, because most 16-bit operations take at least twice as long as an 8-bit operation, and use twice as many registers. This may or may not make a difference to you.

Many of us switch to the native types such as int8_t and uint8_t as it gives you far more control.


body:
One important fact about C and C++ languages is that their respective standards do not define the size (in bytes) of integral and floating point number types.

They just define minimal ranges and relation between these ranges, e.g.

    range(short) <= range(int) < range(long)

So the size of e.g. an `int` will typically depend on:

- the target platform (processor)
- the compiler itself


message:
Why do I need to include libraries used in other libraries?

I have a simple library which uses another library.

Here is the header:

    #ifndef __DERIVEDCLASS_H__
    #define __DERIVEDCLASS_H__

    #include <HardwareSerial.h>

    class DerivedClass
    {
    private:
     HardwareSerial* serial;

    public:
     DerivedClass();
    };
    #endif

And the CPP:

    #include "DerivedClass.h"

    DerivedClass::DerivedClass()
    {

    }

And the sketch:

    #include <DerivedClass.h>

    void setup()
    {
    }

    void loop()
    {
    }

This works fine.

However, if I change the library header to this:

    #ifndef __DERIVEDCLASS_H__
    #define __DERIVEDCLASS_H__

    #include <SoftwareSerial.h>

    class DerivedClass
    {
    private:
     SoftwareSerial* serial;

    public:
     DerivedClass();
    };
    #endif

The sketch fails to compile:

> /Users/andrew/Documents/Arduino/libraries/DerivedClass/DerivedClass.h:9:
> error: ISO C++ forbids declaration of 'SoftwareSerial' with no type
> /Users/andrew/Documents/Arduino/libraries/DerivedClass/DerivedClass.h:9:
> error: expected ';' before '*' token

If I change the sketch to:

    #include <DerivedClass.h>
    #include <SoftwareSerial.h>

    void setup()
    {
    }

    void loop()
    {
    }

i.e. including the SoftwareSerial library in the top level sketch, it compiles fine.

If I expand the library out so it actually performs actions, then if it compiles, it works.

Why is this? HardwareSerial is a built-in part of the Arduino, located in *hardware/arduino/cores/arduino* and SoftwareSerial is in *libraries*, but why would the build process differentiate between the two.

body:
If I remember correctly this is in fact a limitation of the **Arduino IDE**.

If you use a better IDE (personally I use Eclipse with the Arduino plugin) it works as it should, i.e. if you include a library A that includes another library B, then in the end you won't get compile-time errors and both B and A will be included in the final binary.


message:
How can I adapt the DallasTemperature library to accept another 1-Wire class?

A commonly used library is the [DallasTemperature][1] library, used to access DS18B20 sensors on a 1-Wire bus. When creating a DallasTemperature object you pass a reference to a [OneWire][2] object. OneWire can create a 1-Wire bus on pretty much any port of an Arduino.

An example of this is like so:

    // Setup a oneWire instance to communicate with any OneWire devices (not just Maxim/Dallas temperature ICs)
    OneWire oneWire(ONE_WIRE_BUS);

    // Pass our oneWire reference to Dallas Temperature.
    DallasTemperature sensors(&oneWire);

However, there are some issues with using OneWire to drive a 1-Wire bus, mainly around driving longer bus lengths, dealing with shorts, and other errors.

There is a commonly available chip called the DS2482-100 that can drive longer busses (hundreds of feet), deals with shorts and other errors. It is also less CPU heavy and it deals with a number of the slower aspects of 1-Wire.

For this reason, I would like to be able to pass a reference to a library that I have created instead. Currently, I am doing this by:

 - Calling the library OneWire
 - Replicating all the methods called by the DallasTemperature library
 - Swapping out the OneWire library for mine

This is relatively messy. I would ideally like to be able to pass either a reference to my library or a 1-Wire library, so that people can chose which interface to use.

How would I go about doing this?

  [1]: http://milesburton.com/Dallas_Temperature_Control_Library
  [2]: http://www.pjrc.com/teensy/td_libs_OneWire.html

body:
The typical way to achieve what you want would normally be to create your own **subclass** of `OneWire` class and **override** the methods you need to change, then pass a pointer to an instance of your class to the `DallasTemperature` constructor.

However, for this to work, the `OneWire` class must have been developed with extensibility (subclassing) in mind, i.e. use **virtual** methods that you can override.

Unfortunately, a quick look at `OneWire.h` shows that no method is virtual in there.

So that means in the end you will have to perform some hacks, just as you do now.

What you could potentially do (that's still a hack, but maybe a bit less dirty) is:

- replace `OneWire.h` to make all methods virtual (at least those you need to override)
- keep the original `OneWire.cpp` that should still compile with the newly adapted header file
- create a new `MyOneWire.h` / `MyOneWire.cpp` to define your own `OneWire` subclass that overrides all necessary methods as you want

Then you can pass either a `OneWire` or a `MyOneWire` instance to `DallasTemperature` constructor.

NB: when I see my answer, this makes me think your question is more a general C++ question than an Arduino-related one.


body:
> The DS2482-100 is an I2C-to-1-Wire®bridge device that interfaces directly to standard (100kHz max) or fast (400kHz max) I2C masters to perform bidirectional protocol conversion between the I2C master and any
downstream 1-Wire slave devices.

It uses a higher level protocol over I2C which does not directly match the bit-banged OneWire interface above.

A possible solution is to "only" reuse the OneWire interface and reimplement it. Sub-classing will not work as the member functions are not virtual. Unfortunately this will not work directly due to error handing, timing, etc. The DallasTemperature class will also need modifying.

Please see the [DS2482-100 product description and protocol][1].

To achieve your goal of allowing either bit-banged or DS2482-100 based 1-Wire master would require 1) an abstract interface (class) used by 1-Wire master device drivers, 2) sub-classes for each implementation master variant.

As the 1-Wire protocol has a number of common commands a delegation pattern is more useful. Please see the [Cosa OWI::Driver][2] and [DS18B20][3] device driver for an example of the delegation pattern.

  [1]: http://datasheets.maximintegrated.com/en/ds/DS2482-100.pdf
  [2]: https://github.com/mikaelpatel/Cosa/blob/master/libraries/OWI/OWI.hh
  [3]: https://github.com/mikaelpatel/Cosa/blob/master/libraries/DS18B20/DS18B20.hh


message:
Why can't I use Jeelib Sleepy on the Teensy 2 along with Serial

I have been using the [Jeelib Sleepy][1] functionality for several years now to achieve low power states on the Arduino ATmega328/1280/2560 boards, specifically the LoseSomeTime functionality.

I want to get my Teensy 2 to go into a similar low power state, so I tried a very simple sketch that simply put the device to sleep, flashed an LED, and posted some Serial messages. I did need to comment out a few lines in Jeelib:

    // adjust the milli ticks, since we will have missed several
    #if defined(__AVR_ATtiny84__) || defined(__AVR_ATtiny85__) || defined (__AVR_ATtiny44__) || defined (__AVR_ATtiny45__)
        extern volatile unsigned long millis_timer_millis;
        millis_timer_millis += msecs - msleft;
    #else
        extern volatile unsigned long timer0_millis;
        timer0_millis += msecs - msleft;
    #endif

This had to be done as the delay() and millis() functions on the Teensy use different variable names for the adjustment, and it was the quickest way of solving the problem. LoseSomeTime works on the ATmega328 hardware with this change.

I found that although the LoseSomeTime function did sleep for a period, the Serial functionality stopped working entirely - no messages were being printed at all. I have encountered this before on ATmega328 hardware because the microcontroller has gone to sleep before the serial buffer was flushed. I added a number of delay()s after the Serial.writes and also tried using Serial.flush() to make sure the buffer was empty.

LoseSomeTime requires setting an interrupt on the watchdog timer, but I can't see how this would impact Serial operation.

  [1]: http://jeelabs.net/pub/docs/jeelib/classSleepy.html

body:
This is a problem with the Teensy boards - or more correctly that the Jeelib Sleepy library does not support the Teensy boards.

You will need to modify the library to make it work for Teensy boards. Or you could use another low power/sleep library.


message:
Can I link another device to the Uno's clock?

I'm trying to use an unusual 16x2 LCD display with my Uno. As far as I know, it's an EA-X16027AR. It doesn't seem to be compatible with the HD44780 driver, which is typically used for Arduino LCD's.

According to the datasheet, the display's ENB (Enable) pin requires a clock input, described as follows:

> Basical Clock to perform Instructions in Controller LSI. The Clock at the same timing as MPU are usually input.

The timing graphs elsewhere in the datasheet show it wants a speed of around 2 MHz.

Is it possible to get the internal clock signal from the Uno, scale it down to 2 MHz, and output it to a GPIO pin or similar? Alternatively, is it possible to emulate a clock signal at that speed on-board, without adding additional timing components?

body:
Rather than using microprocessor-specific low-level programming, I was able to get a suitable signal using the core `tone()` function:

    tone(11, 2000000);

It can be used to generate a 50% duty cycle square wave of a custom frequency on any individual GPIO pin (I'm using 11 in this case). Given the name, it's obviously designed for producing simple audio output, and 2 MHz is way above the range of human hearing.

The documentation doesn't list any upper limit on the frequency though, and the code it's based on doesn't appear to introduce any limitations. With that said, it clearly can't run faster than the internal timer it's based on (which I think will typically be 8 or 16 MHz).

It seems reasonable to assume that it will be in-sync with the microprocessor's internal clock, although I haven't been able to confirm that empirically as I don't have suitable equipment at home. Similarly, I haven't been able to confirm that it's *actually* producing a 2 MHz signal, but the LCD display is working properly so it's likely to be in the right vicinity. I had previously tried running it from regular PWM, but that didn't work, so frequency is obviously important here.

The signal can be stopped by calling:

    noTone(11);

There are a couple of caveats to be aware of when using `tone()`. First of all, it can only work on a single pin at a time, so you can't generate multiple signals with it. And secondly, it will prevent some PWM output from working properly (on pins 3 and 11, according to the documentation). This is because it has to reconfigure one of the internal timers which is normally used for PWM.


message:
Can a stepper motor be controlled directly from an Arduino?

I'm planning to build a simple XY plotter, and have been looking at the possibility of using a pair of small 5V 4-phase steppers to provide the movement. In my research, I've often seen stepper driver boards advertised, ranging from very big and expensive, through to quite small and cheap. Some of them actually look like little more than a darlington array on a PCB.

Do I really need one of those external driver boards, or can I control the steppers directly from my Arduino?

body:
Generally, stepper motors cannot be controlled by an Arduino pin. They have a current draw of over the 20mA any single pin can supply.

Kickback is also a problem. Because the motors have moving magnetic parts inside, they will continue to generate electricity after power has been cut. this will almost certainly cause enough negative voltage that is enough to fry your Arduino.

A solution is to use a motor driver chip or shield. [This one](https://www.sparkfun.com/products/9815) is a good example. These have transistor based chips that can drive enough current to power a motor, and diodes to mitigate the kickback from the motors.


message:
Controlling water temperature accurately

I have following setup:

- Arduino Duemilanove
- Small water heater connected with optical relay (PWM is ok)
- Waterproof DS18B20 temperature sensor
- Unknown amount of water (but temperature sensor and heater are always underwater).

How can I accurately control water temperature, based on temperature sensor readings? By accurately, I mean up to accuracy of temperature sensor (in this case, ±0.5°C). Everything should run on Arduino, so no additional data storage or processing power is available. For debugging, I can obviously use computer.

I have tried running PID, but it seems really hard to

1. Avoid overshooting - going over target temperature either initially, or when (cold) water is added
2. Stabilize properly after adding cold water.

body:
You need to know the response time of your system and the repeatability of your measurements to characterize your data (establish confidence). I suggest taking samples and average them before turning the heater back on.

Imho, water will not happily stay within 0.5°C. Can you allow for coarse and fine modes? Use a higher PWM for great differences and then lower PWM for when close to target.

Once homed in on your target, there are a few means you can try to improve temperature stability. While pre-built things like PID work for many, I normally implement functionality like this manually.


message:
Would an infinite loop inside loop() perform faster?

When you're writing a typical sketch, you usually rely on `loop()` being called repeatedly for as long as the Arduino is running. Moving in and out of the `loop()` function must introduce a small overhead though.

To avoid that, you could presumably create your own infinite loop, like this:

    void loop()
    {
        while (true)
        {
            // do stuff...
        }
    }

Is that a viable way to improve performance? Will it cause other problems if `loop()` never returns?

body:
The part of the code on an ATmega core that does setup() and loop() is at follows:

    #include <Arduino.h>

    int main(void)
    {
            init();

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

            setup();

            for (;;) {
                    loop();
                    if (serialEventRun) serialEventRun();
            }

            return 0;
    }

Pretty simple, but there is the overhead of the serialEventRun(); in there.

Let's compare two simple sketches:

    void setup()
    {

    }

    volatile uint8_t x;

    void loop()
    {

        x = 1;

    }

and

    void setup()
    {

    }

    volatile uint8_t x;

    void loop()
    {
     while(true)
     {
      x = 1;
     }
    }

The x and volatile is just to ensure it isn't optimised out.

In the ASM produced, you get different results:
![Comparison of two][1]

You can see the while(true) just performs a rjmp (relative jump) back a few instructions, whereas loop() performs a subtraction, comparison and call. This is 4 instructions vs 1 instruction.

To generate ASM as above, you need to use a tool called avr-objdump. This is included with avr-gcc. Location varies depending on OS so it is easiest to search for it by name.

avr-objdump can operate on .hex files, but these are missing the original source and comments. If you have just built code, you will have a .elf file that does contain this data. Again, the location of these files varies by OS - the easiest way to locate them is to turn on verbose compilation in preferences and see where the output files are being stored.

Run the command as follows:

> avr-objdump -S output.elf > asm.txt

And examine the output in a text editor.

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


body:
[Cybergibbons's answer][1] describes quite nicely the assembly code generation and the differences amongst the two techniques. This is intended to be a complementary answer looking at the issue in terms of *practical* differences, i.e. how much of a difference either approach will make in terms of *execution time*.

---
##Code Variations
I did an [analysis][2] involving the following variations:

- Basic `void loop()` (which gets inlined on compilation)
- Un-inlined `void loop()` (using `__attribute__ ((noinline))`)
- Loop with `while(1)` (which gets optimized)
- Loop with un-optimized `while(1)` (by adding `__asm__ __volatile__("");`. This is a `nop` instruction that prevents optimization of the loop without resulting in additional overheads of a `volatile` variable)
- An un-inlined `void loop()` with optimized `while(1)`
- An un-inlined `void loop()` with un-optimized `while(1)`

The sketches can be found [here][3].

##Experiment
I ran each of these sketches for 30 seconds, thereby accumulating [300 data points each][4]. There was a 100 millisecond `delay` call in each loop (without which [bad things happen][5]).

##Results
I then calculated the mean execution times of each loop, subtracted 100 milliseconds from each and then plotted the results.

[![][6]][7]

#Conclusion

- An un-optimised `while(1)` loop within `void loop` is faster than a compiler optimised  `void loop`.
- The time difference between the un-optimized code and default Arduino  optimized code is insignificant *practically*. You will be better off compiling manually using `avr-gcc` and using your own optimisation flags rather than depending on the Arduino IDE to help you with it (if you need microsecond optimisations).

---

**NOTE:** The actual time values are not of significance here, the difference between them is. The ~90 microseconds of execution time includes a call to `Serial.println`, `micros` and `delay`.

**NOTE2:** This was done using the Arduino IDE and the default compiler flags that it supplies.

**NOTE3:** Analysis (plot and calculations) was done using R.

  [1]: https://arduino.stackexchange.com/questions/337/would-an-infinite-loop-inside-loop-perform-faster#339
  [2]: http://github.com/AsheeshR/Arduino-Loop-Analysis
  [3]: http://github.com/AsheeshR/Arduino-Loop-Analysis/tree/master/Code/Sketches
  [4]: http://github.com/AsheeshR/Arduino-Loop-Analysis/tree/master/Data
  [5]: https://electronics.stackexchange.com/q/12300/18583
  [6]: http://raw2.github.com/AsheeshR/Arduino-Loop-Analysis/master/Figures/timeplot.png
  [7]: http://github.com/AsheeshR/Arduino-Loop-Analysis/blob/master/Data/Munged/runtime.csv


message:
SMPTE Timecode Reader with LCD display coding question

I've managed to adapt some code from the Arduino forums to display timecode on an LCD display.

What I would like some extra help with is first is there a way of defining the `one_time_max` etc differently depending on the high low state of a pin? This way I could use a switch to change the times so it could switch between NTSC and PAL.

Secondly would anyone be kind enough to explain what is happening in the middle part of this code? I've made some notes but any help would be really appreciated.

Here is a picture of how it's going so far. I'll keep you guys up to date as the project continues :)

[![enter image description here][1]][1]

```c++
    // Code from forum post Dec 12, 2007

    // include the library code:
    #include <LiquidCrystal.h>

    // initialize the library with the numbers of the interface pins
    LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
    #define one_time_max 600 // these values are setup for PA video
    #define one_time_min 400
    // It's the durstion of a one and zero with a little bit of room for error.
    #define zero_time_max 1050 //
    #define zero_time_min 950 //

    #define icpPin 8 // ICP input pin on arduino
    //#define one_time_max 475 // these values are setup for NTSC video
    //#define one_time_min 300 // PAL would be around 1000 for 0 and 500 for 1
    //#define zero_time_max 875 // 80bits times 29.97 frames per sec
    //#define zero_time_min 700 // equals 833 (divide by 8 clock pulses)

    #define end_data_position 63
    #define end_sync_position 77
    #define end_smpte_position 80

    volatile unsigned int pin = 13;
    volatile unsigned int bit_time;
    // volatile instructs the variable to be stored in RAM
    volatile boolean valid_tc_word;
    // boolean can be either of two values true or false but default to false
    volatile boolean ones_bit_count;
    // boolean can be either of two values true or false but default to false
    volatile boolean tc_sync;
    // boolean can be either of two values true or false but default to false
    volatile boolean write_tc_out;
    // boolean can be either of two values true or false but default to false
    volatile boolean drop_frame_flag;
    // boolean can be either of two values true or false but default to false
    volatile byte total_bits; //this stores a an 8-bit unsigned number
    volatile byte current_bit; //this stores a an 8-bit unsigned number
    volatile byte sync_count; //this stores a an 8-bit unsigned number

    volatile byte tc[8]; //this stores a an 8-bit unsigned number
    volatile char timeCode[11]; //this stores a an 8-bit unsigned number

    /* ICR interrupt vector */
    ISR(TIMER1_CAPT_vect) {
      //ISR=Interrupt Service Routine, and timer1 capture event
      //toggleCaptureEdge
      TCCR1B ^= _BV(ICES1);
      //toggles the edge that triggers the handler so that the duration of both high and low pulses is measured.
      bit_time = ICR1; //this is the value the timer generates
      //resetTimer1
      TCNT1 = 0;
      // Ignore phase changes < time for 1 bit or > time for zero bit (zero bit phase change time is double that of 1 bit)
      if ((bit_time < one_time_min) || (bit_time > zero_time_max)) {
        // this gets rid of anything that's not what we're looking for
        total_bits = 0;
      } else {
        // If the bit we are reading is a 1 then ignore the first phase change
        if (ones_bit_count == true)
          // only count the second ones pulse
          ones_bit_count = false;
        else {
          // We have already checked the outer times for 1 and zero bits so no see if the inner time is > zero min
          if (bit_time > zero_time_min) {
            // We have a zero bit
            current_bit = 0;
            sync_count = 0; // Not a 1 bit so cannot be part of the 12 bit sync
          } else {
            // It must be a 1 bit then
            ones_bit_count = true; // Flag so we don't read the next edge of a 1 bit
            current_bit = 1;
            sync_count++; // Increment sync bit count
            if (sync_count == 12) {
              // part of the last two bytes of a timecode word
              // We have 12 1's in a row that can only be part of the sync
              sync_count = 0;
              tc_sync = true;
              total_bits = end_sync_position;
            }
          }

          if (total_bits <= end_data_position) {
            // timecode runs least to most so we need
            // to shift things around
            tc[0] = tc[0] >> 1;
            for(int n=1;n<8;n++) {
              //creates tc[1-8]
              if(tc[n] & 1) tc[n-1] |= 0x80;
              tc[n] = tc[n] >> 1;
            }
            if(current_bit == 1) tc[7] |= 0x80;
          }
          total_bits++;
        }
        if (total_bits == end_smpte_position) {
          // we have the 80th bit
          total_bits = 0;
          if (tc_sync) {
            tc_sync = false;
            valid_tc_word = true;
          }
        }
        if (total_bits <= end_data_position) {
          // timecode runs least to most so we need
          // to shift things around
          tc[0] = tc[0] >> 1;
          for(int n=1;n<8;n++) {
            //creates tc[1-8]
            if(tc[n] & 1) tc[n-1] |= 0x80;
            tc[n] = tc[n] >> 1;
          }
          if(current_bit == 1) tc[7] |= 0x80;
        }
        total_bits++;
      }

      if (total_bits == end_smpte_position) {
        // we have the 80th bit
        total_bits = 0;
        if (tc_sync) {
          tc_sync = false;
          valid_tc_word = true;
        }
      }

      if (valid_tc_word) {
        valid_tc_word = false;
        timeCode[10] = (tc[0]&0x0F)+0x30;
        // frames  this converst from binary to decimal giving us the last digit
        timeCode[9] = (tc[1]&0x03)+0x30;
        // 10's of frames this converst from binary to decimal giving us the first digit
        timeCode[8] =  ':';
        timeCode[7] = (tc[2]&0x0F)+0x30; // seconds
        timeCode[6] = (tc[3]&0x07)+0x30; // 10's of seconds
        timeCode[5] =  ':';
        timeCode[4] = (tc[4]&0x0F)+0x30; // minutes
        timeCode[3] = (tc[5]&0x07)+0x30; // 10's of minutes
        timeCode[2] = ':';
        timeCode[1] = (tc[6]&0x0F)+0x30; // hours
        timeCode[0] = (tc[7]&0x03)+0x30; // 10's of hours
        drop_frame_flag = bit_is_set(tc[1], 2);
        //detects whether theree is the drop frame bit.
        write_tc_out = true;
      }
    }

    void setup() {
      lcd.begin (16, 2);
      pinMode(icpPin, INPUT); // ICP pin (digital pin 8 on arduino) as input
      bit_time = 0;
      valid_tc_word = false;
      ones_bit_count = false;
      tc_sync = false;
      write_tc_out = false;
      drop_frame_flag = false;
      total_bits =  0;
      current_bit =  0;
      sync_count =  0;
      lcd.print("FINISHED SETUP");
      delay (1000);
      TCCR1A = B00000000; // clear all
      TCCR1B = B11000010; // ICNC1 noise reduction + ICES1 start on rising edge + CS11 divide by 8
      TCCR1C = B00000000; // clear all
      TIMSK1 = B00100000; // ICIE1 enable the icp
      TCNT1 = 0; // clear timer1
    }

    void loop() {
      if (write_tc_out) {
        write_tc_out = false;
        if (drop_frame_flag)
          lcd.print("TC-[df] ");
        else
          lcd.print("TC-NO DROP FRAME");
        lcd.setCursor(0, 1);
        lcd.print((char*)timeCode);
        lcd.print("\r");
        lcd.setCursor(11, 1);
        lcd.print("......");
        delay (30);
        lcd.clear();
      }
    }
111

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

body:
The one_time_max, one_time_min, zero_time_max and zero_time_min are all defines at the top of the file. This will insert them as constant values at compile time. This makes changing the code to deal with them slightly awkward, but not impossible.

Oddly, the one_time_max value isn't used, but the others are. To allow you to switch between PAL and NTSC, I would do the following (this is marginally lazy, but quick):

 - change one_time_max to ONE_TIME_MAX_NTSC and ONE_TIME_MAX_PAL so that you have two defined constants for each part. Caps is convention for defines.
 - create a new global variable, a boolean, that is a flag to decide if PAL or NTSC is to be decoded.
 - every time that one of the constant is used, use a conditional statement based on the global variable to decided which constants are used.
 - use the input from a button to decided the value of the global variable.


body: I am in the process of implementing exactly the same thing. The simplest way around this problem is simply to do away with the one_time_max and one_time_min variables and simply implement a mid_point value, testing the bit_time against this for one and zero values. By simply testing for a mid_point value, it allows the routine to tune itself for integer/non-integer timecode values from 24fps thorough to 30fps.


body:
I am implementing a similar project, but my timecode reader is built into the clapperboard itself.

https://improduction.ru/tags/imslate-1/

The thing is that the bit length depends on the FPS. I just "listened" to the signal from my Zoom F8 recorder and then started the reference data. While receiving data from the cable, I simply compare them and determine the frequency. That's all.

https://improduction.ru/all/elektronnaya-hlopushka-imslate-1-pro-chtenie-taymkoda/

[![enter image description here][1]][1]
[![enter image description here][2]][2]

  [1]: https://i.stack.imgur.com/5DAib.jpg
  [2]: https://i.stack.imgur.com/vjUbr.jpg


message:
Logging multiple gigabytes of data with Arduino

I have Arduino Uno with SD card shield. I'm planning to log a huge amount of data from various sensors - including accelerometers and 3D compass - to the SD card.

However, I have understood that Arduino, 64GB SD, FAT and large amount of data are not working too well.

Does Arduino work well with this amount of data on FAT? There's no need to read any data from SD on Arduino. If not, is there a better approach? Writing directly to SD without FAT?

This data logger will be on the environment where no computer or network connection is available. Performance is not an issue - around 8kB/s (over three months) is already enough.

body:
I'm not sure where you have the impression it won't work. I haven't used 64GB cards, but have used 32GB cards and they work fine in terms of FAT32 and writing files.

As you have already worked out, reading or searching the file system can get very slow as size increases.

That said, I have found that larger capacity cards are more likely to have problems with the SPI interface being poor quality. Consumer devices do not use the SPI interface, and it seems that some manufacturers are willing to skimp on this side of it. The SPI interface can be buggy or unstable as a result. Genuine name-brand cards should work fine though.


body: You should consider using [sdfatlib](http://code.google.com/p/sdfatlib/). This is currently supported version. Where an early version of this was the predecessor the IDE's stock SD library. SdFat better supports newer and larger SdCards, along with more features.


message:
Why do sketches take up so much space and memory?

When I compile this sketch for the Yún:

    int led = 7;

    void setup() {
      pinMode(led, OUTPUT);
    }

    void loop() {
      digitalWrite(led, HIGH);
    }

I get:

> Sketch uses 5,098 bytes (17%) of program storage space.
>
>Maximum is
> 28,672 bytes. Global variables use 153 bytes (5%) of dynamic memory,
> leaving 2,407 bytes for local variables. Maximum is 2,560 bytes.

Even when I compile the BareMinimum sketch:

    void setup() {
      // setup
    }

    void loop() {
      // loop
    }

I get:
> Sketch uses 4,548 bytes (15%) of program storage space.
>
> Maximum is
> 28,672 bytes. Global variables use 151 bytes (5%) of dynamic memory,
> leaving 2,409 bytes for local variables. Maximum is 2,560 bytes.

Why does a bare minimum sketch take up 15% of the program storage space allocated? And why does a very simple sketch take up 17% of the program storage space? According to [the Arduino website][1]:

> It's easy to use it all up by having lots of strings in your program.
> For example, a declaration like: `char message[] = "I support the Cape
> Wind project.";` puts 33 bytes into SRAM (each character takes a byte,
> plus the '\0' terminator).

However, there aren't any strings declared in either of these sketches.

It seems as if they might import or use other libraries/classes that I don't specify. Maybe it imports a system default library? Or is it something else?

  [1]: http://arduino.cc/en/Tutorial/Memory#.UwfEavkiEw8

body:
Arduino compiles in a lot of standard libraries, interrupts, ... etc. For example the pinMode and digitalWrite functions use a lookup table to figure out at run time which GPIO registers to write data to. Another example is that Arduino keeps track of time, it defines some interrupts by default and all this functionality requires some space. You'll notice that if you extend the program, the foot print will only change slightly.

I personally like to program controllers with bare minimum, without "bloat", but you'll quickly enter the world of EE.SE and SO because several easy to use functions will no longer work out of the box. There are some alternative libraries for pinMode and digitalWrite that compile into a smaller footprint, but come with other disadvantages like for example static compiled pins (where `led` cannot be a variable, but is a constant).


body:
The YUN is a combo. Part Arduino and Part OpenWRT(Linux). Your question is in reference to the Arduino. Where this is actually a ATmega32u4 similar to a Leonardo and not an UNO(ATmega328p). The 32u4(Leo) communicates via Virtual Serial Ports over the USB *(short answer: this needs to be supported)* , where the UNO has a real Serial Port (aka UART). Below are builds statistics of the different boards types for the AVR processors.

Note on the UNO there is an external chip that converts USB to the Serial port's DTR pin which toggles the ATmega328's reset pin when connected causing a reboot to the bootloader. In contrast the Leo/Yun's USB to Serial is in implemented in the firmware of the 32u4. Hence in order to remotely reboot the Leo or YUN's 32u4 chip the firmware loaded must always support the USB client side driver. Which consumes approximately 4K.

If the USB was NOT needed and no other library resources were called as in the case of BareMinimum.ino on an UNO, only approximately 466 bytes are needed for the core Arduino Library.

compile stats of BareMinimum.ino on a UNO(ATmega328p)

    Sketch uses 466 bytes (1%) of program storage space. Maximum is 32,256 bytes.
    Global variables use 9 bytes (0%) of dynamic memory, leaving 2,039 bytes for local variables. Maximum is 2,048 bytes.

compile stats of BareMinimum.ino on a Leonardo(ATmega32u4)

    Sketch uses 4,554 bytes (15%) of program storage space. Maximum is 28,672 bytes.
    Global variables use 151 bytes (5%) of dynamic memory, leaving 2,409 bytes for local variables. Maximum is 2,560 bytes.

compile stats of BareMinimum.ino on a Yun(ATmega32u4)

    Sketch uses 4,548 bytes (15%) of program storage space. Maximum is 28,672 bytes.
    Global variables use 151 bytes (5%) of dynamic memory, leaving 2,409 bytes for local variables. Maximum is 2,560 bytes.


body:
I wrote a post about [Why does it take 1000 bytes to blink one LED?](http://www.gammon.com.au/forum/?id=12173).

The brief answer is: "It doesn't take 2000 bytes to blink **two** LEDs!"

The longer answer is that the standard Arduino libraries (which you don't have to use if you don't want to) have some nice functionality to simplify your life. For example, you can address pins by number at runtime, where the library converts (say) pin 8 to the correct port and correct bit number. If you hard-code port access you can save that overhead.

Even if you don't use them, the standard libraries include code to count "ticks" so you can find out the current "time" (by calling `millis()`). To do this it has to add the overhead of some interrupt service routines.

If you simplify down (on the Arduino Uno) to this sketch you get the program memory usage down to 178 bytes (on IDE 1.0.6):

    int main ()
      {
      DDRB = bit (5);
      while (true)
        PINB = bit (5);
      }

OK, 178 bytes isn't that much, and of that the first 104 bytes are the hardware interrupt vectors (4 bytes each, for 26 vectors).

So arguably, there are only 74 bytes required to blink an LED. And of that 74 bytes most are really the code generated by the compiler to initialize global memory. If you add enough code to blink two LEDs:

    int main ()
      {
      DDRB = bit (5);  // pin 13
      DDRB |= bit (4);  // pin 12

      while (true)
        {
        PINB = bit (5); // pin 13
        PINB = bit (4); // pin 12
        }
      }

Then the code size increases to 186 bytes. So therefore you could argue that it only takes `186 - 178 = 8` bytes to blink an LED.

So, 8 bytes to blink an LED. Sounds pretty efficient to me.

---

In case you are tempted to try this at home, I should point out that whilst the posted code above blinks two LEDs, it does so very rapidly indeed. In fact, they blink at 2 MHz - see screenshot. Channel 1 (yellow) is pin 12, channel 2 (cyan) is pin 13.

![Rapid blinking of pins 12 and 13][1]

As you can see, the output pins have a square wave with a frequency of 2 MHz. Pin 13 changes state 62.5 ns (one clock cycle) before pin 12, due to the order of the toggling of the pins in the code.

So unless you have much better eyes than mine, you won't actually see any blinking effect.

---

As an amusing extra, you can actually toggle **two** pins in the *same* amount of program space as toggling one pin.

    int main ()
      {
      DDRB = bit (4) | bit (5);  // set pins 12 and 13 to output

      while (true)
        PINB =  bit (4) | bit (5); // toggle pins 12 and 13
      } // end of main

That compiles into 178 bytes.

This gives you a higher frequency:

![Very rapid blinking of pins 12 and 13][2]

Now we are up to 2.66 MHz.

  [1]: https://i.stack.imgur.com/mPd81.png
  [2]: https://i.stack.imgur.com/VdQde.png


body:
You already have some perfectly good answers. I am posting this only to
share some stats I did one day I asked myself the same sort of
questions: What is taking so much space on a minimal sketch? What is the
minimum needed to achieve the same functionality?

Below are three versions of a minimal blinky program that toggles the
LED on pin 13 every second. All three versions have been compiled for an
Uno (no USB involved) using avr-gcc 4.8.2, avr-libc 1.8.0 and
arduino-core 1.0.5 (I do not use the Arduino IDE).

First, the standard Arduino way:

<!-- language: lang-c++ -->

    const uint8_t ledPin = 13;

    void setup() {
        pinMode(ledPin, OUTPUT);
    }

    void loop() {
        digitalWrite(ledPin, HIGH);
        delay(1000);
        digitalWrite(ledPin, LOW);
        delay(1000);
    }

This compiles to 1018 bytes. [Using both `avr-nm` and
disassembly](https://arduino.stackexchange.com/a/12684),
I broke down that size into individual functions. From
largest to smallest:

     148 A ISR(TIMER0_OVF_vect)
     118 A init
     114 A pinMode
     108 A digitalWrite
     104 C vector table
      82 A turnOffPWM
      76 A delay
      70 A micros
      40 U loop
      26 A main
      20 A digital_pin_to_timer_PGM
      20 A digital_pin_to_port_PGM
      20 A digital_pin_to_bit_mask_PGM
      16 C __do_clear_bss
      12 C __init
      10 A port_to_output_PGM
      10 A port_to_mode_PGM
       8 U setup
       8 C .init9 (call main, jmp exit)
       4 C __bad_interrupt
       4 C _exit
    -----------------------------------
    1018   TOTAL

In the list above, the first column is the size in bytes, and the second
column tells whether the code comes from the Arduino core library (A,
822 bytes total), the C runtime (C, 148 bytes) or the user (U, 48
bytes).

As can be seen in this list, the largest function is the routine
servicing the timer 0 overflow interrupt. This routine is responsible of
tracking time, and is needed by `millis()`, `micros()` and `delay()`.
The second largest function is `init()`, which sets the hardware timers
for PWM, enables TIMER0\_OVF interrupt and disconnects the USART (that
was used by the bootloader). Both this and the previous function are
defined in
`<Arduino directory>/hardware/arduino/cores/arduino/wiring.c`.

Next is the C + avr-libc version:

<!-- language: lang-c -->

    #include <avr/io.h>
    #include <util/delay.h>

    int main(void)
    {
        DDRB |= _BV(PB5);     /* set pin PB5 as output */
        for (;;) {
            PINB = _BV(PB5);  /* toggle PB5 */
            _delay_ms(1000);
        }
    }

The break-down of the individual sizes:

    104 C vector table
     26 U main
     12 C __init
      8 C .init9 (call main, jmp exit)
      4 C __bad_interrupt
      4 C _exit
    ----------------------------------
    158   TOTAL

This is 132 bytes for the C runtime and 26 bytes of user code, including
the inlined function `_delay_ms()`.

It could be noted that, since this program does not use interrupts,
the interrupt vector table is not needed, and regular user code
could be put in its place. The following assembly version does exactly
that:

    #include <avr/io.h>
    #define io(reg) _SFR_IO_ADDR(reg)

        sbi io(DDRB), 5  ; set PB5 as output
    loop:
        sbi io(PINB), 5  ; toggle PB5
        ldi r26, 49      ; delay for 49 * 2^16 * 5 cycles
    delay:
        sbiw r24, 1
        sbci r26, 0
        brne delay
        rjmp loop

This is assembled (with `avr-gcc -nostdlib`) into only 14 bytes,
most of which are used to delay the toggles so that the blink is
visible. If you remove that delay loop, you end up with a 6-byte
program that blinks too fast to be seen (at 2 MHz):

        sbi io(DDRB), 5  ; set PB5 as output
    loop:
        sbi io(PINB), 5  ; toggle PB5
        rjmp loop


message:
How to organize my Arduino projects' structure for easy source control?

It's been a long time I've been looking for a good answer to this question.

Typically, any Arduino project but the simplest one will include:

- The main source code file `MyProject.ino`
- Libraries specific to the project (`MyProjectLibrary1.h`, `MyProjectLibrary1.cpp`...)
- Third-party libraries (generally free open source, added manually to Arduino libraries directory)
- Schematics, PCB diagrams
- Documentation
- ...

All this makes it hard to keep the whole code and doc of one project under Source Code Management (e.g. on Subversion, Git or GitHub).

Managing source control of your project means managing the version of all files used by the project including 3rd-party libraries.

Now for a single project, I need to define a directory structure that:

- Includes all project files as described above
- I can entirely commit to a Source Code Management tool (including 3rd-party dependencies)
- I can checkout anywhere on my hard drive and build the project from there (does it have to be a single location as imposed by Arduino IDE)
- I can zip into a self-contained archive that I can send to a friend for him to build as easily as possible (no extra manual download)

What I find particularly tricky with Arduino projects is the management of external libraries dependencies. Java projects developers have [maven][1] repositories for that and that helps a lot in managing all external deps. But we don't have an equivalent system for Arduino libraries.

I would be interested to know how other Arduino project makers deal with these aspects in their own projects.

Also note that I am open to changing my development process, including my IDE (currently I use Eclipse with the Arduino plugin most of the time, and then I ensure my projects can also work directly with the Arduino IDE).

  [1]: http://maven.apache.org

body:
The simplest way to do this is to copy the header and code files of the library into your source directory and include them.

    myproject/
        myproject.ino
        somelib.h
        somelib.cpp

In your code, you can do `include "somelib.h"`

The down side to this is that the libraries must be in the same folder, not sub folders, so it makes your directory look messy.

---

Regarding the directory structure of my entire project, including schematics and documentation, mine usually looks like this:

    myproject/
      schematics/ - eagle files or whatever you may have
      docs/       - include relevant datasheets here
      test/       - any test cases or other code to test parts of the system.
      myproject/  - since Arduino code must be in a directory of the same name
        myproject.ino
        ...


body:
My way of organizing an arduino project is quite simple, all my project are git repositories so that there is at least the following:

 * project/
   * project.ino
   * [Makefile](https://github.com/guyzmo/Arduino-Tools/blob/master/Makefile)

I have a preference using my [favorite editor](http://vim.org) and a [Makefile](https://github.com/guyzmo/Arduino-Tools/blob/master/Makefile) which I have crafted to work against most use cases (and I even improved on that one that I'm going to share soon).

For the libraries, I prefer to keep them as their own repositories and use git submodule to include them to the project. As many libraries written by the community are shared as git repositories, that's a good generic solution. Then, within the Makefile, I just have to add the libraries path I want to include in the [LOCALLIBS](https://github.com/guyzmo/Arduino-Tools/blob/master/Makefile#L63) variable.

Though, for some projects, it makes sense to encapsulate the libraries into a hardware abstraction layer library crafted for the project, then I prefer to use a path such as:

  * `project`
     * `project.ino`
     * `Makefile`
     * `project_hal_lib`
        * `library1`
        * `library2`
        * `library3`
        * …

Though, with arduino 1.5.x a new [way to specify libraries](https://arduino.github.io/arduino-cli/library-specification/) is offered, that will offer a way to create and build arduino projects the same way we already do with pipy and virtualenv in python, i.e. you define the set of libraries you need and they get downloaded.


body:
[Git submodules][1] are extremely powerful when it comes to organizing multiple nested repositories. Handling multiple libraries from different sources, and even handling parts of your own project which may be stored at different sources becomes easy with git submodules.

##Directory Structure

A way to organize your projects would be:

- **projectA** - Parent Directory

 - **projectA** - Source code directory containing Arduino code
      1. projectA.ino
      2. header.h
      3. implementation.cpp

 - **docs** - Your main documentation directory

 - **schematics** - these may be maintained separately on a separate Git repo or part of the same repo

 - **libs** - This will contain your third party libraries.
     1. libA - These may be maintained as third party repositories
     2. libC - ...

 - **license**

 - **README**

 - **Makefile** - Necessary to handle dependencies across directories

##Workflow

You would follow your normal cycle of make changes, add and commit as far as the main repository is concerned. Things get interesting with the sub-repositories.

You have the option of adding a repository into the parent directory of your main repository. This means that any part of you directory structure, i.e. docs, schematics, etc. can be maintained as a separate repository and continuously updated from.

You can do this using the `git submodule add <repo.git>` command. To keep it up to date, you can use `git submodule update <path>`.

When it comes to maintaining multiple third party libraries within your repository such that each can be version controlled in itself or each can be kept up to date if need be, git submodule again saves your day!

To add a third party repo to **libs**, use the command `git submodule add <lib1.git> libs/lib1`. Then, to maintain the library at a fixed point in the release cycle, checkout the library and make a commit. To keep the library up to date, use the command `git submodule update <path>`.

Now, you can maintain multiple repositories within a main repository as well as multiple third party libraries in their independent stages of release.

#Versus Single Directory Approach

While the [single directory approach][2] is the simplest, it is not possible to version control parts of a directory without a lot of pain. Hence, the simple approach fails to accomodate different repositories with varying states in the project.

This approach allows maintaining multiple repositories but brings in the need for a Makefile to handle the compilation and linking process.

Depending on the complexity of your project, the optimal approach can be selected.

  [1]: http://git-scm.com/book/en/Git-Tools-Submodules
  [2]: https://arduino.stackexchange.com/a/351/65


body:
You could use the makefile
https://github.com/sudar/Arduino-Makefile
for compiling Arduino codes. You don't necessarily need the IDE.


body:
Here is the way I finally decided to follow for my projects.

# Arduino-CMake
The first important decision I made was the choice of a build tool that could work for my environment (Windows) but was not limited to it (I want my projects easily reusable by other people).

I have tested various open source Arduino make tools:

 - **[Guyzmo Makefile][1]** (suggested by @zmo answer): this is just a standard Makefile handcrafted for Arduino builds; this is a Unix Makefile but there  is a [good port][2] of **Unix make for Windows**; still, unfortunately this Makefile works only for Unix, of course it could be adapted for Windows, but I wanted a tool that works "out of the box".
 - **[Arduino-Makefile][3]** (suggested by @adnues answer): this a more advanced project, based on Unix Makefile, that aims to be easily reusable by all Arduino projects; it is documented as working on Mac, Linux and Windows, but Windows support proved wrong in my first experiments (many dependencies on Unix shell).
 - **[Graduino][4]** (not suggested by any answer): this build tool is based on well-known [gradle][5] build tool from the [groovy][6] world; the tool seems quite well done but requires some (little) groovy/gradle knowlegde, and has only little documentation; I decided not to go with it due to the burden of installing groovy and gradle just for it (I'd like to avoid too many pre-requisites to people who want to build my projects on their environments).
 - **[Arduino-CMake][7]** (not suggested by any answer): this seems the best of all, it has a long history, has many supporters and maintainers, is very well documented, comes with simple examples and also has a few good tutorial blog posts on the Web, e.g. [here][8] and [there][9]. It is based on [CMake][10], a "Cross-Platform Make".

I have also found **[ArduinoDevel][11]**, another Arduino build tool -which I have not experimented- that can generate **Unix Makefiles** or [ant][12] `build.xml` files; that one seemed interesting but a bit limited in terms of functionality.

Finally I decided to go with **Arduino-CMake**:

 - it was easy to setup: just install **CMake** on your machine and copy Arduino-CMake in some directory that is easily accessible (through relative paths) from your projects directories.
 - the examples worked out of the box for me (just followed the comments in `CMakeLists.txt` configuration file to adapt properties that needed to for my environment, e.g. Arduino type, serial port)
 - you can organize your projects any way you want
 - it can generate configuration files for various build tools out there (I have only tested **Unix Makefiles** though), including [Eclipse][13] projects.
 - in the generated make, several targets get created to support:

   - libraries build
   - programs build
   - program upload to boards
   - serial monitor launch
   - and a few others I have not tested yet

# Project Structure
Since Arduono-CMake does not impose any directory structure for your project, you can choose the one that fits you best.

Here is what I've done personnaly (that still requires further refinement, but I'm happy with it now):

![enter image description here][14]

I have decided to put all my projects under a common `arduino-stuff` directory (which I commit to github as a whole, I know I could use ***git submodules*** for a better organisation on github, but had no time to check that yet).

`arduino-stuff` has the following content:

 - `build`: that's a directory where cmake and make will generate all their stuff (makefiles, cache, object files...); this one does ot get committed to github
 - `cmake`: that one is just a copy (unmodified) of [Arduino-CMake cmake][15] directory. This one gets on github so that it's easier for someone who wants to build my projects
 - `CMakeLists.txt`: that's the "global" CMake configuration that declares all defaults for my environment (board, serial port) and the list of build target subdirectories
 - `TaskManager`: this is my first project based on Arduino-CMake, this one is a library with examples; this idrectory also contains a `CMakeLists.txt` that states the targets for the project

# Points to improve
The current solution is not perfect though.
Among improvements I see (that's rather for Arduino-CMake project to include these improvements if they see fit):

 - Feature to copy a library directory from the current project to the Arduino libraries directory
 - Feature to upload a library to github
 - Feature to download a library from github

  [1]: https://github.com/guyzmo/Arduino-Tools
  [2]: http://gnuwin32.sourceforge.net/packages/make.htm
  [3]: https://github.com/sudar/Arduino-Makefile
  [4]: https://bitbucket.org/magnomp/graduino/
  [5]: http://www.gradle.org/
  [6]: http://groovy.codehaus.org/
  [7]: https://github.com/queezythegreat/arduino-cmake
  [8]: http://www.pascalspoerri.ch/posts/2013/12/29/using-arduino-with-cmake/
  [9]: http://duinoworks.bakketti.com/?p=11
  [10]: http://www.cmake.org/
  [11]: https://github.com/arons/ArduinoDevel
  [12]: http://ant.apache.org/
  [13]: https://www.eclipse.org/
  [14]: https://i.stack.imgur.com/gV76h.png
  [15]: https://github.com/queezythegreat/arduino-cmake/tree/master/cmake


body:
Probably really late to the game but it's a popular enough question to answer using slightly different methods than those posted already.

If you need to maintain compatibility with Arduino IDE directly you could use something like the one I outlined here:

https://gitlab.com/mikealger/ExampleArduinoProjectStructure/tree/master/ExampleSketchBook

I based most of this off the notes of [Arduino -- Project structure and build process][1], and some tips I have picked up over the years.

I really don't know why this is so hard to find via Arduino pages directly, it seems silly coming from a semi professional background that the build process is so obtuse.

best of luck out there

----edited link to the project structure notes i used as they have been erased
[they are now here][1]

  [1]: https://web.archive.org/web/20180729070130/https://grahamwideman.wikispaces.com/Arduino -- Project structure and build process


body:
<!-- language: lang-none -->

    MyProject
    |_MyProject
      |_MyProject.ino
      |_data
      |  |_documentation
      |  |_PCB
      |  |_schematics
      |_src
         |_MyProjectLibrary1
         |_ThirdPartyLibrary

##MyProject folder (repository root)

The reason I suggest the seemingly redundant `MyProject` root folder is that you mentioned using GitHub. When you download (rather than clone) the contents of a GitHub repository the branch or tag name is appended to the repository name (e.g. `MyProject-master`). The Arduino IDE requires that the sketch folder name match the sketch file name. If you open an .ino file that is in a folder that does not match the sketch name the Arduino IDE prompts you create an appropriately named sketch folder and move the sketch to that folder. In addition to this not being a very good initial experience for the user, the greater problem is that the Arduino IDE may not copy all the other associated files to the newly created folder, which could cause the program to no longer compile. By putting the sketch in a subfolder you avoid GitHub altering the name of the sketch folder.

If the GitHub file name thing is not an issue for you then the redundant root folder is not necessary.

##data folder

I recommend using the `data` subfolder for your non-code files because the Arduino IDE has a special treatment of subfolders of that name. They are copied to the new location when you do a **File > Save As...**. Subfolders of any other name are not.

##src folder

The `src` subfolder has the special property of allowing [recursive compilation](https://github.com/arduino/arduino-builder/pull/148). This means that you can leave the libraries in that folder and include them from your sketch like this:

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

    #include "src/MyProjectLibrary1/MyProjectLibrary1.h"
    #include "src/ThirdPartyLibrary/ThirdPartyLibrary.h"
The [Arduino 1.5 Library format folder structure](https://github.com/arduino/Arduino/wiki/Arduino-IDE-1.5:-Library-specification#layout-of-folders-and-files) is also supported, you only need to adjust your `#include` statements accordingly.

Note that only Arduino IDE 1.6.10 (arduino-builder 1.3.19) and newer support recursive sketch compilation.

Unfortunately some libraries use the incorrect `#include` syntax for local file includes (e.g. `#include <ThirdPartyLibrary.h>` instead of `#include "ThirdPartyLibrary.h"`). This still works when the library is installed to one of the Arduino `libraries` folders but does not work when the library is bundled with the sketch. So some libraries may require minor edits to use this way.

I greatly prefer this to the alternative of dumping all the library files in the root of the sketch folder because that is messy and every library file will be shown in the Arduino IDE as tabs when you open the sketch (Of course any source files you do want to be editable from the Arduino IDE should be placed in the sketch root folder).

Being able to use bundled libraries in place is also in line with another of your goals:
>send to a friend for him to build as easily as possible

Removing the requirement to manually install libraries makes the project much easier to use.

This will also avoid any chances of conflict with other versions of library files of the same name that may be previously installed.


message:
How can I rename how my Arduino shows up on the computer?

I have a clone of a Mega 2560, and the Chinese manufacture apparently had a broken shift key. To my annoyance, whenever I connect it to my computer it reads, `arduino compatible mega 2560`. With my extreme *annoyance* with *slightly* misspelled or incorrectly capitalised English, it has been very distracting to me.

However, the reason that I'm asking this question is for more than how to rename it to be capitalised. Think of how many projects could be simplified by this! Or for many Arduinos, you can label they physically and then rename them `Arduino #1`, etc. so you can tell which port it is on using device manager. If you designed a product with Arduino, then you can even rename it to your product name.

**I would imagine that there would be an easy way to do this by reburning the firmware to the [Insert USB chip model #### here].** I've seen it done for keyboards on the Uno, so I would imagine that you could modify it somehow.

body:
This string is contained in the FT232 USB to UART interface chip and the manufacturer has released [the FT_PROG tool](http://www.ftdichip.com/Support/Utilities.htm) to reprogram it. But do take note of the warning on their website: "**PLEASE NOTE - The use of some of these utilities by an end user may result in a device being rendered useless**". Another word of warning is to **ensure there is only one device connected with an FTDI-chip**.

Here is a screenshot of the MProg tool:

![enter image description here][1]

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


message:
How much can I recurse? How much can I recurse? How much ca!@#QFSD@$RFW

The Arduino Uno board has limited RAM which means it has a limited call stack available. Sometimes, recursion is the only quick option to implement a certain algorithm. So, given that the call stack is severely limited, what would be a way to find out that given a certain program running on the board, exactly how many recursive calls can you afford before there is a stack overflow (and bad things happen)?

body: Recursion is bad practice on a microcontroller as you already stated yourself and you probably want to avoid it whenever possible. On [the Arduino site there are some examples and libraries available for checking free RAM size](http://playground.arduino.cc/Code/AvailableMemory). You can for example use this to figure out when to break recursion or a bit trickier/riskier to profile your sketch and hard code the limit in it. This profile would be required for every change in your program and for every change in Arduino tool chain.


body:
It depends on the function.

Every time a function is called, a new frame is pushed onto the stack. It will usually contain various critical items, potentially including:

 * Return address (the point in the code from which the function was called).
 * The local instance pointer (`this`) if calling a member function.
 * Parameters passed into the function.
 * Register values which need to be restored when the function ends.
 * Space for local variables inside the called function.

As you can see, the stack space required for a given call depends on the function. For example, if you write a recursive function which only takes an `int` parameter and uses no local variables, it won't need much more than a few bytes on the stack. That means you can recursively call it far more than a function which takes several parameters and uses a lot of local variables (which will eat up the stack much quicker).

Obviously the state of the stack depends on what else is going on in the code. If you start a recursion directly within the standard `loop()` function, then there probably won't be a lot on the stack already. However, if you start it nested several levels deep in other functions, then there won't be as much room. That will affect how many times you can recurse without exhausting the stack.

It's worth noting that tail recursion optimisation exists on some compilers (although I'm not sure if avr-gcc supports it). If the recursive call is the very last thing in a function, it means it is sometimes possible to avoid altering the stack frame at all. The compiler can just re-use the existing frame, since the 'parent' call (so to speak) is finished using it. That will mean you can theoretically keep recursing as much as you like, so long as your function doesn't call anything else.


body:
If you really want to recurse (and as @jippie said it is a bad idea; subliminal message:  **don't do it**) and want to know how much you can recurse, then you will have to perform some calculation and experiments; also you generally will have only an approximation of it as it depends a lot on the memory state at the time your recursive function will be called.

For this, you should first know how SRAM is organized inside AVR-based Arduino (it won't apply to e.g. the Arduino Galileo by Intel). The following diagram [from Adafruit](https://learn.adafruit.com/memories-of-an-arduino?view=all) shows it clearly:

![SRAM organization][1]

Then you need to know the total size of your SRAM (depends on Atmel MCU, hence what kind of Arduino board you have).

On this diagram, it is easy to find out ths size of **Static Data** block as it is known at compile-time and won't change later on.

The **Heap** size can be more difficult to know as it can vary at runtime, depending on dynamic memory allocations (`malloc` or `new`) performed by your sketch or the libraries it uses. Using dynamic memory is quite rare on Arduino, but some standard functions do it (type `String` uses it, I think).

For the **Stack** size, it will also vary during runtime, based on the current depth of function calls (each function call takes 2 bytes on the Stack to store the address of the caller) and the number and size of local variables including passed arguments (that are also stored on the **Stack**) for all the functions called until now.

So let's suppose your `recurse()` function uses 12 bytes for its local variables and arguments, then each call to this function (the first one from an external caller and the recursive ones) will use `12+2` bytes.

If we suppose that:

 - you are on Arduino UNO (SRAM = 2K)
 - your sketch does not use dynamic memory allocation (no **Heap**)
 - you know the size of your **Static Data** (let's say 132 bytes)
 - when your `recurse()` function is called from your sketch, the current **Stack** is 128 bytes long

Then you are left with `2048 - 132 - 128 = 1788` available bytes on the **Stack**. The number of recursive calls to your function is thus `1788 / 14 = 127`, including the initial call (which is not a recursive one).

As you can see, this is very difficult, but not impossible to find what you want.

A simpler way to get the stack size available before `recurse()` is called would be to use the following function (found on Adafruit learning center; I have not tested it myself):

    int freeRam ()
    {
      extern int __heap_start, *__brkval;
      int v;
      return (int) &v - (__brkval == 0 ? (int) &__heap_start : (int) __brkval);
    }

I strongly encourage you to read [this article][2] at Adafruit learning center.

  [1]: https://i.stack.imgur.com/kosMi.gif
  [2]: http://learn.adafruit.com/memories-of-an-arduino/you-know-you-have-a-memory-problem-when-dot-dot-dot


body:
I wrote this simple test program:

    void setup() {
      // put your setup code here, to run once:
      Serial.begin(115200);
      recurse(1);
    }

    void loop() {
      // put your main code here, to run repeatedly:

    }

    void recurse(long i) {
      Serial.println(i);
      recurse(i+1);
    }

I compiled it for the Uno, and as i write it has recursed over 1 million times! I don't know, but the compiler may have optimized this program


body:
I had this exact same question as I was reading [Jumping into C++ by Alex Allain][1], Ch 16: Recursion, p.230, so I ran some tests.

# TLDR;
**My Arduino Nano (ATmega328 mcu) can do 211 recursive function calls (for the code given below) before it has a stack overflow and crashes.**

# First off, let me address this claim:
> Sometimes, recursion is the only quick option to implement a certain algorithm.

[Update: ah, I skimmed the word "quick". In that case you have some validity. Nevertheless, I think it's worth saying the following.]

No, I don't think that is a true statement. I'm pretty certain **all** algorithms have both a recursive and a non-recursive solution, without exception. It's just that sometimes it is significantly *easier* to use a recursive algorithm. Having said that, recursion is very much frowned upon for use on microcontrollers and would probably never be allowed in safety-critical code. Nevertheless, it is possible of course to do it on microcontrollers. To know how "deep" you can go into any given recursive function, just test it! Run it in your real-life application in a real-life test case, and remove your base condition so that it will infinitely recurse. Print out a counter and see for yourself how "deep" you can go so you know whether or not your recursive algorithm is pushing the limits of your RAM too close to be used practially. Here's an example below to force stack overflow on an Arduino.

# Now, a few notes:
How many recursive calls, or "stack frames" you can get is determined by a number of factors, including:

 * The size of your RAM
 * How much stuff is already on your stack or taken up in your heap (ie: your free RAM matters; `free_RAM = total_RAM - stack_used - heap_used`, or you might say `free_RAM = stack_size_allocated - stack_size_used`)
 * The size of each new "stack frame" which will be placed onto the stack for every new recursive function call. This will depend upon the function being called and its variables and memory requirements, etc.

# My results:

- 20171106-2054hrs - Toshiba Satellite w/16 GB RAM; quad-core, Windows 8.1: final value printed before crash: **43166**
  - took several seconds to crash--maybe 5~10?
- 20180306-1913hrs Dell high-end laptop w/64 GB RAM; 8-core, Linux Ubuntu 14.04 LTS: final value printed before crash: **261752**
  - followed by the phrase `Segmentation fault (core dumped)`
  - took only ~4~5 sec or so to crash
- 20180306-1930hrs Arduino Nano: TBD---is at ~250000 and still counting---the Arduino optimization settings must have caused it
  to optimize out the recursion...??? Yes, that is the case.
  - Add `#pragma GCC optimize ("-O0")` to the top of the file and redo:
- 20180307-0910hrs Arduino Nano: 32 kB flash, 2 kB SRAM, 16 MHz processsor: final value printed before crash: **211**
```
  Here are the final print results:
  209
  210
  211  ⸮ 9⸮   3⸮
```
  - took only a fraction of a second once it started printing at 115200 serial baud-rate--maybe 1/10 sec
  - 2 kiB = 2048 bytes / 211 stack frames = 9.7 bytes/frame (assuming ALL of your RAM is being used by the stack--which actually isn't the case) --but this seems very reasonable nonetheless.

# The code:

## The PC application:

    /*
    stack_overflow
     - a quick program to force a stack overflow in order to see how many stack frames in a small function can be loaded onto the stack before the overflow occurs

    By Gabriel Staples
    www.ElectricRCAircraftGuy.com
    Written: 6 Nov 2017
    Updated: 6 Nov 2017

    References:
     - Jumping into C++, by Alex Allain, pg. 230 - sample code here in the chapter on recursion

    To compile and run:
    Compile: g++ -Wall -std=c++11 stack_overflow_1.cpp -o stack_overflow_1
    Run in Linux: ./stack_overflow_1
    */

    #include <iostream>

    void recurse(int count)
    {
      std::cout << count << "\n";
      recurse(count + 1);
    }

    int main()
    {
      recurse(1);
    }

## The Arduino "Sketch" program:
    /*
    recursion_until_stack_overflow
    - do a quick recursion test to see how many times I can make the call before the stack overflows

    Gabriel Staples
    Written: 6 Mar. 2018
    Updated: 7 Mar. 2018

    References:
    - Jumping Into C++, by Alex Allain, Ch. 16: Recursion, p.230
    */

    // Force the compiler to NOT optimize! Otherwise this recursive function below just gets optimized into a count++ type
    // incrementer instead of doing actual recursion with new frames on the stack each time. This is required since we are
    // trying to force stack overflow.
    // - See here for all optimization levels: https://gcc.gnu.org/onlinedocs/gcc/Optimize-Options.html
    //   - They include: -O1, -O2, -O3, -O0, -Os (Arduino's default I believe), -Ofast, & -Og.

    // I mention `#pragma GCC optimize` in my article here: http://www.electricrcaircraftguy.com/2014/01/the-power-of-arduino.html
    #pragma GCC optimize ("-O0")

    void recurse(unsigned long count) // each call gets its own "count" variable in a new stack frame
    {
      // delay(1000);
      Serial.println(count);

      // It is not necessary to increment count since each function's variables are separate (so the count in each stack
      // frame will be initialized one greater than the last count)
      recurse (count + 1);

      // GS: notice that there is no base condition; ie: this recursive function, once called, will never finish and return!
    }

    void setup()
    {
      Serial.begin(115200);
      Serial.println(F("\nbegin"));
      // First function call, so it starts at 1
      recurse (1);
    }

    void loop()
    {
    }

# References:
 1. [Jumping into C++ by Alex Allain][1], Ch 16: Recursion, p.230
 2. http://www.electricrcaircraftguy.com/2014/01/the-power-of-arduino.html - literally: I referenced my own website during this "project" to remind myself how to change Arduino compiler optimization levels for a given file with the `#pragma GCC optimize` command since I knew I had it documented there.

  [1]: https://www.cprogramming.com/c++book/


message:
How can I use Python from a sketch?

I'd like to be able to use Python from a sketch. According to [the Arduino playground][1], one can use PySerial from a computer to talk with an Arduino via Python.

It looks like from that page you can also use various API's to use Python with an Arduino from a computer. However, I'd like to know if you can execute Python directly from a sketch. It would be nice because then you could execute Python directly from a sketch, and not all of it would have to be written in Python.

If this is not possible, is there an easy way to execute Python on an Arduino? Looking at the various API's it was hard to determine exactly what they did, and if you could execute a `.py` script from a computer or from anything on the Arduino.

  [1]: http://playground.arduino.cc/interfacing/python#.Uwl-r6go6aw

body:
> It looks like from that page you can also use various API's to execute
> Python directly on the Arduino.

I don't see that, at all. All those links show you how to communicate with the Arduino over serial using Python on the host side.

You'd need a python interpreter to be able to run python on the Arduino. There is the [Python On A Chip][1] project and it seems like they have support for the Mega.

> 2010/09/01 (1bdb8d31f27b) New platform: Arduino Mega.

Some more info from the [PyMite page][2]:

> any device in the AtMega family which meets these requirements: 20KiB
> Flash and 4K RAM, will run today

I doubt you'll find anything that'll let you mix Arduino and Python code in the same sketch.

  [1]: https://code.google.com/p/python-on-a-chip/
  [2]: https://wiki.python.org/moin/PyMite


message:
Where can I find a central repository of all available Arduino libraries?

Currently; when I start a new Arduino project with some new hardware, the first thing I do is to look for 3rd-party libraries that bring Arduino support for this hardware.

The first places I look are:

- [The Arduino Playground][1]
- [GitHub][2]
- [Google][3]

Generally I find either no support library or several different libraries (it's quite rare to find only one) in different locations with different levels of documentation, different levels of testing...

Once I have found the library I need (sometimes I need to try several), I download it to my Arduino libraries folder, I use it and I forget it.

I find this process cumbersome:

- manual search with different possible options, not always well documented
- manual download and install to Arduino libraries
- no version control in the process (all versions of a library have the same name and thus cannot coexist in the Arduino library folder).

I wish there was a central repository with all available libraries for arduino, with:

- description (supported hardware, supported boards)
- source code
- documentation
- versions

And a tool (Arduino IDE or external) to access this repository at project build time.

A kind of [maven][4] for Arduino in fact.

I have seen several discussions once took place on Arduino forum, but it seems they led nowhere:

- [Arduino Libraries Census and Repository][5]
- [Arduino Library downloader][6]
- [Arduino Library downloader (2)][7]

Are there other options, that are made it to something usable (from the community or individuals, why not)?

  [1]: http://playground.arduino.cc/
  [2]: https://github.com/
  [3]: http://www.google.com
  [4]: http://maven.apache.org
  [5]: http://forum.arduino.cc/index.php?topic=73531.0
  [6]: http://forum.arduino.cc/index.php/topic,1460.0.html
  [7]: http://forum.arduino.cc/index.php/topic,63215.0.html

body:
There is none. Unfortunately, you will have to manually search for each library you are interested in.

If you are interested in creating such a central repository, while it would be awesome, this is not the correct forum in which to do it.


body:
The [Arduino Playground LibraryList][1] and the [standard library list][2] appear to be the official pages for that.

  [1]: http://playground.arduino.cc/Main/LibraryList
  [2]: http://arduino.cc/en/Reference/Libraries


body:
Arduino IDE and associated libraries are included as installable software in most OS repositories.  Unfortunately the versions in these repositories is usually several months or even years out-of-date.  This would seem that the real problem is in getting OS repository managers to incorporate new releases as they become available.

This problem is compounded when your OS version has not been updated to the latest release, because this forces you to use an outdated software repository.

While not a perfect answer, you should probably insure that you are using the latest release of your OS, and then encourage the repository managers for that OS to incorporate the latest version of Arduino IDE.

An alternative would be to go to the Arduino.org homepage and follow instructions to download and install the latest IDE and associated libraries.  This will probably be in the form of a .tar.gz file so you  will need to know how to unzip, untar, and build the necessary software.


body:
If you want to create such a registry yourself, you may want to take a
look at [npm][], the package manager of [Node.js][], which is
open-source and very similar in scope to want you describe. Npm is both:

1. a central registry with metadata about each library:
    * name, description, keywords, homepage, author, contributors
    * version number, in principle complying with [semantic versioning][]
    * URL of source repository (svn, git, github, gitlab, bitbucket...)
    * compatibility information (in this case it's about the versions of Node)
    * license
    * dependencies
2. a command-line tool for:
    * searching the registry
    * downloading and installing packages, recursively following their
      dependencies
    * publishing and updating your own packages on the registry.

See for example the page of a [popular library][express], and the [JSON
file][package.json] holding its metadata.

[npm]: https://www.npmjs.com/
[Node.js]: https://nodejs.org/en/
[semantic versioning]: http://semver.org/

[express]: https://www.npmjs.com/package/express
[package.json]: https://github.com/expressjs/express/blob/master/package.json


body:
Since this question was first asked, there is now the Arduino Library Manager, built into the Arduino IDE. There you can search for and install libraries.

There is information about how the library manager works here:
https://github.com/arduino/Arduino/wiki/Library-Manager-FAQ

There isn't however an official website listing the libraries, so I recently created this unofficial site, based on the same data in the Arduino Library Manager:

http://www.arduinolibraries.info/


body:
I think, that your wish will not come true. I hope for it, because having only one place for all Arduino libriaries, with no libraries allowed not be there and all those libraries would be forced to stand all commercial standards of quality, testing and documentation (+code quality, effectivity and readability) would mean, that only professionals and similary qualified teams would be allowed to publish some Arduino library and it all would be governed by one single entity, which would enforce removing functionally duplicate or similar libraries. And such entity would soner or later became evil.

I like the Arduino for being free and that also means, that I am free to write library for support of some features (which I want to use) of some hardware (which I have, plan to buy or want to make myself - even highly experimental and maybe unstable, but fun for me).

With your Big Central Authority being effective, I would just choose another free platform, rather then be sued for lesser than perfect and commercially certified outcome of my hobby playing with electronics and forced to work for their, NOT my goals on MY free time.

And if your Big Central Athority would not force me to forced free labor work for them, then what would you do about my library enabling one special use of some common hardware, and about me sharing it to anyone want it, even if it does not solve all the HW functionality fully in proffesional matter and documented only so much as I would be comfortabe to spend my own free time with documentation. And what if there would arise another library for the same HW, which would enable another part of functionality or would use another API and another approach to the whole problematic?

Namely I bought some multi 7-segment module and there was "official library" for it from its manufacturer. I made another library for the same module. What now? Should be my library be in the Central Repository as "the only one library for this HW" or should be there the "official one from manufacturer"?
Note, that if there were both of them, than it would break your requested "one and only one" library point.
If you disallow the manufacturer one, then "the only one" would be missing a lot of features, as integrated buffer for numbers, simple object interface, simple example, how to use it and there would be hard dependency on one specific timer and generic non-object, just functional API, which would require user to break integers to single digits somehow - does not sound too good.
If you disallow my library, then user would have the above, but his display would refresh only 10x per second with blinking and leaving ghosts of other digits all over place, while fully utilise processor and the documentation would be mainly in chinese. And the user would miss refresh rate 100x per second with nearly no usage of processor, nice clean digits AND characters (potetially also user defined). - Also not good.

In current state of chaos user (maybe you or anyone else) can use the library, that is better fit for his needs (be it simplicity and native integer support, or be it clean fast refresh and low CPU usage) or combine both together, making third with fast refresh AND simple integer manipulation AND user defined charset, WITH nice object API and rich documentation. It only needs one person with some time and dedication make it easy for beginers and some english skills and basic knowledge of objects and how are "official Arduino libraries" packed, so the IDE can easily import them. (And such person should do it and contribute it to Arduino library packager).

I would not do it - for my needs is functional API far better and simpler to use, take less bytes from memory and less CPU cycles and I have no urge to improve the library in ways I would not use. Also I do not use Arduino IDE, I use simple Makefile to build and upload the programs, so I can easily use good text editor (vim in my case) and have not to fight with IDE-Notepad-parody.

Under Big Central Authority enforsing your model I would not care about using Arduino at all and you will be stuck with the chinese version, if any at all (as it would not make it there for lack of good english documentation and proper package format too).


body:
http://downloads.arduino.cc/libraries/library_index.json provides a list of all libraries available in Arduino Library Manager.

I used this file to create https://github.com/scls19fr/arduino_libraries_search It's a Python Pandas script to search for Arduino libraries matching some keywords and to output to Excel file

You can also find Arduino libraries using:

- https://platformio.org/lib/search?query=keyword%3A%22arduino%22
- or https://www.arduinolibraries.info/


message:
How can higher current devices (motors, solenoids, lights, etc.) be controlled by an Arduino?

I'm looking for a broadly applicable solution, one that can be adapted to a variety of projects.

I'm currently working on several projects that each require controlling devices ranging from 800mA to 2A from an Arduino Uno. One controls stepper motors, one controls 12vdc solenoid actuators, and one controls 12vdc pneumatic valves.

For example:

The Arduino monitors a button, and each time the button is pressed it triggers the solenoid actuator. Because the Arduino is unable to source the current required by the solenoid, a seperate power supply is required with the Arduino controlling a switch (relay, transistor, etc.) that allows the higher current to pass. For the stepper motor, the layout is more complex as there would need to be four pins controlling four separate switches (to maintain interoperability of the circuit). The relay controls an air valve and requires 12vdc as well.

I'm trying to figure out how to use a single circuit that can be used in each of these applications (and any future projects) that involve controlling higher current devices than the Arduino pins can handle.

Prototyping speed, standardized components, and low cost are the driving factors. Switching speed, useful life, and noise are also important.

Is there a breakout board, circuit, or component that can be connected to an Arduino pin and used to control a high current device? Ideally with a software controlled potentiometer so that the resistance for different projects could be set in the sketch itself.

body:
To drive such high currents, you may have to cascade several transistors (you can also use a [Darlington transistor][1]). There are arrays of Darlingtons mounted in a chip (e.g. the ULN2803A has 8 darlington transistors, but is limited to 500mA).

You probably will have to deal with higher power transistors; as an example I have found STMicroelectronics [TIP110][2] which can support switching a 2A current (4A peak), but it would probably need a heatsink to dissipate heat.

Note that I wonder if your steppers really need 2A current (are they that big?). For steppers, you can generally find IC that can drive them easily, e.g. the L293D but this one can drive "only" 600mA).

As a conclusion, I am afraid you will not find a "one size fits all" solution, as all your devices are different and should be driven by the appropriate circuit.

**Edit:**

Since oversizing is not an issue in your prototyping case, then you could go with a **MOSFET** instead of usual bipolar transistors. A MOSFET will be able to drive higher currents and voltages than standard transistors.

The downside is you can use it as a switch only (like e.g. a relay) and thus can't really **drive** the exact power for your devices. I guess that does not matter for a Stepper motor, or a Solenoid, but that may be important for driving lights for instance.

However, the good point is that you can still use PWM for that as the MOSFET switching speed is good enough for such purposes.

Regarding price, there are many diferent kinds of MOSFET out there, but I guess you can find one that fits yours needs (12V, 2A) for less than $1.

I advise you to take a look at [this great article][3] about this topic.

  [1]: http://en.wikipedia.org/wiki/Darlington_transistor
  [2]: http://www.st.com/web/en/resource/technical/document/datasheet/CD00000909.pdf
  [3]: http://bildr.org/2012/03/rfp30n06le-arduino/


body:
There are lots of ways to switch higher loads, and jfpoilpret has described some good options. I'll summarise a couple of relay-based solutions, which are mainly appropriate for comparatively slow switching speeds (i.e. not usually suitable for PWM).

**Solid State Relays**
Solid State Relays (SSRs) are effectively semiconductor-based switches. They come in a wide variety of configurations, depending on your requirements, but the key factor is that they have no moving parts. This means they can be very reliable in the long run if used properly.

Internally, they are usually comprised of MOSFETs and thyristors or similar. This can let them achieve fairly high switching speeds in theory. In practice though, the more power it's designed for, the harder it is to switch quickly. That means high speed + high power can get quite expensive.

A critical factor to bear in mind is that you'll usually need a different type of SSR if you intended to switch AC instead of DC. It's also good to note that some will come with a built-in opto-isolator or similar to keep your power supplies separate.

**Electro Mechanical Relays**
This is the more 'traditional' approach. An Electro Mechanical Relay (EMR) is a fairly simple component, containing a mechanical switch, controlled by a electromagnetic coil. If the switch is normally open, the coil pulls it closed when a control current is applied. In contrast, a normally-closed switch would be pulled open when a control current is applied.

There are a number of advantages of EMRs over things like SSRs. The most obvious is cost -- their simplicity makes them quite cheap, and the cost doesn't rise so sharply for higher-power versions. Additionally, the control and load are inherently isolated, and they don't care whether you're switching AC or DC.

There are several disadvantages though. The mechanical aspect means that EMRs are usually much slower than non-mechanical switching solutions, and can suffer from contact bounce. Additionally, they can physically wear out, and they can be affected by things like shocks, vibrations, and (potentially) other magnetic fields.

When designing a circuit to use an EMR, it's essential to be aware of back-EMF (electromotive force). When a control current is applied, the coil acts as an inductor, storing charge electromagnetically. When the control current is stopped, the stored charge can surge back through the control circuit, creating a large negative voltage spike (potentially much larger than what was originally applied).

This spike can unfortunately damage/destroy any attached components or microcontroller pins. It is typically prevented/mitigated by putting a diode *in reverse* across the relay's control contacts. In this context, it's sometimes known as a flyback diode, and it allows the EMF to dissipate safely.


body:
As jfpoilpret already said, a power MOSFET is great for turning ON and OFF the 12 VDC power to devices that pull up to 44 A. There are dozens of such power MOSFETs for under $1 each. More expensive MOSFETs are available that can handle much higher current and voltage.

In principle it is possible to drive a stepper motor with a microcontroller and a handful of transistors and a few other little parts.
However, many people prefer to use a "stepper driver chip", so it is impossible for a software bug to accidentally turn on transistors in such a way as to short the power supply to ground (typically destroying at least 2 transistors).
Many recent stepper driver chips also handle microstepping, current limiting, thermal overload protection, and other nice features.

All the stepper driver chips that I've ever heard of, and a few off-the-shelf breakout boards using those chips, are listed at
http://reprap.org/wiki/stepper_motor_driver .

In particular, many of the RepRap 3D printers I've seen connect an Arduino to four [Pololu stepper drivers][1] (under $15 each) to drive five stepper motors.

  [1]: http://www.pololu.com/category/120/stepper-motor-drivers


body: I made an Arduino( Arduino Nano) circuit to power a 12V Peltier(which is also a high power source.) using a MTP3055V MOSFET 60V 12A transistor. And the circuit is operating very well.