message:
Why does my sketch report too many button presses?

I've been using a button to interact with a sketch (on my Uno), and it's mostly working fine. However, sometimes it seems to be detecting multiple presses when it's only pressed once.

It's a small circuit-mounted momentary button, which is normally open. It's connected from +5V directly to an input pin. I've also added a 10K pull-down resistor on the pin to make sure the input isn't left floating.

Here's a test sketch I've been using, which reports the number of presses to the serial monitor:
```c++
    int oldState = LOW;
    int numPresses = 0;

    void setup()
    {
        pinMode(5, INPUT);
        Serial.begin(9600);
    }

    void loop()
    {
        const int newState = digitalRead(5);

        if (newState != oldState) {
            if (newState == HIGH) Serial.println(++numPresses);
            oldState = newState;
        }
    }
```

Sometimes when I press the button once, the serial monitor shows two presses in a row. It sometimes even reports a press when I *release* the button.

Is it possible to fix this? Or do I just have a faulty button or pin or something?

body:
The button contacts themselves are probably bouncing in and out of contact, which is causing the circuit to open and close multiple times, even though the button position isn't changing.

It's a common problem with buttons and would be the first thing I would check. In order to fix this, you need to de-bounce the button. There are various ways in which to accomplish this, some of which can be done in the sketch itself.

A good solution is code that measures the duration of each button state and only registers a change in state if the current duration is greater than the desired duration. That option should be used for more complex projects. The code for it will be project specific and likely use sketch defined variables, but an example of what needs to be done can be found [here][1].

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

If the sketch is very basic or you just want to make sure that bounce is the problem, you can add a short delay after the button state changes. For example:

    void loop()
    {
        const int newState = digitalRead(5);

        if (newState != oldState) {
            if (newState == HIGH) Serial.println(++numPresses);
            oldState = newState;
            delay(10) //Adjust the delay length to be as short as possible without triggering errors
        }
    }


sender: user

sender: assistant

body:
This is your button **bouncing** which is quite usual behavior; it has nothing to do with button quality.

There are 2 ways to "debounce" a button: by hardware or by software.

Personally, I prefer by hardware; just google for `button debouncing circuit` and you should find many examples.

If you don't have the necessary components available, you can use software debouncing.

By software, you have an example [here][1] on Arduino web site.

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


body:
# Contact Bounce
This is known as contact bounce and happens when the metal contacts in the button or switch bounce against each other when you push it. The microcontroller is fast enough to pick up these bounces and, as far as it's concerned, you're toggling the switch many times in as much as 10 milliseconds of time.

Different switches and buttons will have a different amount of contact bounce, and even one switch will behave differently between two presses.

Here's a button press captured on a scope (image from [Maxim][1]):

![enter image description here][2]

At 2ms/div we don't see a stable signal until 6ms after initial contact!

# Solutions

## Add a delay

The absolute simplest solution is to introduce a short delay after you read the button input. This will prevent the code from picking up any bounces and when it resumes, the signal should be stable.

    if (digitalRead(A3) == 0) {
        // do something here
        delay(500);
    }

In the example above, I delay 500ms after reading the state of the pin. The button is normally high so when I press it down, the state of the pin goes to logic 0. I pick that up in the code and do something and then wait at least 500ms before continuing.

Obviously, this code will just halt for half a second every time you push a button, which may or may not be acceptable in your application. You can decrease the amount of delay depending on the contact bounce time of your switch, too, but I play it safe here.

# Ignore button presses too close to each other

Similar to the solution above but instead of adding a hard delay, you use the `millis()` function to keep track of when the last time the switch was triggered. Every time you see a switch trigger, you compare against the time and, if not enough time has elapsed (say like 500ms in my previous example), you ignore it.

This solves the problem of having to use `delay()` in your code.

# Switch debouncer IC

There are things like the [MAX6816][3] which is an IC that you put in between your switch and microcontroller input. It will denounce the signal for you. At a price of $1.62 @1k you'll probably never use this.

## Other

There are many solutions to this problem... I always do it in software, but some others include using a [latch or capacitor][4].

[Debounce Code – one post to rule them all][5]

  [1]: http://www.maximintegrated.com/app-notes/index.mvp/id/159
  [2]: https://i.stack.imgur.com/ZrNMs.gif
  [3]: http://www.maximintegrated.com/datasheet/index.mvp/id/1896
  [4]: http://tech.thetonegod.com/debounce/debounce.html
  [5]: http://hackaday.com/2010/11/09/debounce-code-one-post-to-rule-them-all/


message:
How can an Arduino output a specific (i.e. 56 kHz) carrier frequency?

I'm working on a free space optics project to send data wirelessly between two points. To accomplish this I'm using an IR LED connected to an Arduino Uno that pulses with a 56 kHz carrier frequency for the transmitter and a second Arduino with a 56 kHz IR detector module for the receiver.

I tried using delayMicroseconds() between pin high and pin low commands in order to create the carrier frequency. This kind of works, but the frequency isn't always the same and any additional delays for pulsing the signal (i.e. the time required to call the function and decrementing) can change it.

Reading the datasheet for the ATmega328 it appears that there is a way to set a more accurate pulse using the chip's timers. Is that possible, and if so, how do you create a 56 kHz pulse using the timers?

body:
I've found [`tone()`][1] useful for generating high frequency pulses on any pin. It should be able to handle 56 KHz. *(Edit: As noted by jfpoilpret, the closest you could actually get on a 16 MHz Arduino is about 55.944 KHz)*

The difficulty will obviously be combining it with your data signal. I don't think you could do that in software without resorting to low level code. It should be pretty easy in hardware though, since it's digital.

All you'd need to do is output your data signal on a different pin, and then combine it with the carrier using an AND gate. The combined signal can go straight to your IR transmitter.

If you don't have an AND gate handy then it's quite simple to make your own using a pair of transistors. Just search online for "transistor and gate".

  [1]: http://arduino.cc/en/Reference/Tone#.UwsyD2J_t8E


body:
It is indeed possible to generate a 56 kHz signal with an Arduino **timer**.

A timer actually can be seen as a special register, in the MCU, that holds a value (starting at 0) that gets incremented at a frequency that is the MCU clock frequency (16 MHz on Arduino Uno), possibility divided by a factor called *prescaler*. When that value reaches a limit, called **Compare Match**, that you specify, then two things happen:

- The timer register value is reset to 0.
- One **ISR** (interrupt service routine) callback function gets called (you can define it to point to your own code).

The idea is to use that ISR to change the output of a logical pin every time it is called (`HIGH`, then `LOW`, then `HIGH`...).

Now, in order to generate a 56 kHz square wave, you'll need your ISR to be called `56000 * 2` times per second (`* 2` because you need to change the output value twice per period).

You can choose the prescaler value you want for a timer among the following list:

- 1 (clock frequency is not divided, hence 16 MHz)
- 8 (clock frequency is divided by 8, hence 2 MHz)
- 64
- 256
- 1024

There are two sizes of timers/counters on Arduino Uno (they are called *timer/counter* actually): 8 bits and 16 bits.

On Arduino Uno (ATmega328P), you have three timers overall, but some may be used by the Arduino core library or other libraries used in your sketches (you'll have to check that by yourself):

- timer0 (8-bit)
- timer1 (16-bit)
- timer2 (8-bit): this one has more prescaling options (1, 8, 32, 64, 128, 256, and 1024)

Now you need to generate a 56 kHz wave from 16 MHz, hence, without prescaling, you would need to count to:

`16000000 / (56000 * 2) - 1 = 141.857` (`- 1` because a timer counts from 0 to this value and resets only **after** it has been reached)

From this calculation, we can draw two observations:

 1. `141.857` is not an integer and thus you won't be able to generate a wave of exactly 56 kHz.
 2. Without prescaling, you need a 16-bit timer as 285 is not representable as an 8-bit unsigned integer.

From now you have two options:

 1. Use a 16-bit timer (**timer1**), use prescaler = 1, and select `142` as the Compare Match; that will give you the following frequency: `16000000 / (2 * (142 + 1)) = 55944 Hz`
 2. Use an 8-bit timer (**timer0**), use prescaler = 8, and select `17` as the Compare Match; that will give less precision with the following frequency: `16000000 / (8 * 2 * (17 + 1)) = 55555 Hz` which is still within the required range.

Now, regarding how to write your sketch for that, I advise you to check out [this instructable][1] which is very complete and very interesting to read.

Of course, the [ATmega328P complete datasheet][2] is also important if you want to understand, in the slightest details, what you are doing.

Some important notes:

- An ISR is executed with disabled interrupts and must thus be as short as possible. In particular, there are several functions from the Arduino library that shall not be called from an ISR.
- Arduino Uno clock is not very accurate (it uses a ceramic resonator instead of a quartz, which would have been much more accurate), so this means the output frequency will shift further.

  [1]: http://www.instructables.com/id/Arduino-Timer-Interrupts/?ALLSTEPS
  [2]: http://www.atmel.ch/Images/Atmel-8271-8-bit-AVR-Microcontroller-ATmega48A-48PA-88A-88PA-168A-168PA-328-328P_datasheet.pdf


body: You can turn the carrier on and off simply by toggling the carrier pin mode between output and input. I have used this to control a heat pump through the 37KHz infrared (remote control) port.


body:
The accepted answer of jfpoilpret is very well written, perfectly valid and in 99% of the cases I will do exactly what he explains. His solutions are well within your defined parameters, so they should work very well. But what is better than "*very well*"? **Perfection!** After all, the question is about generating a exact value. As said close enough is good in most cases (arguably all), and even when dealing with something as a clocks when 1 second need to be 1 second, you still have to suffer inherited parts imperfections.

What I will suggest is not always possible. In some cases, it's possible, but with much more hassle and effort than this case. Is it worthy depend on a case-by-case basis. My goal is mostly to show a alternative for future references that is better in somewhat fringe cases. This is written with novice Arduino users in mind that don't have extensive experience in electronics.

For more advanced people this probably will look too verbose and dumbed down. But I believe that, those same people probably already know it and don't need this answer. This is also applicable to every microcontroller and every manufacturer and architecture. But for other microcontrollers you will need to consult the correct datasheet to find out proper registers and prescale names and values.

In your case, you need a specific frequency and the nice thing about it, is that exactly 56 kHz actually can be achieved very easy (not counting practical imperfections of the parts). So this is also a perfect example case.

Generating a signal depends on the timers and clock source of the microcontroller, as explained well by jfpoilpret. His answer deals with the problem of one point of view only and that is fiddling with timers. But you can fiddle with the clock source too, or even better with both for synergy and awesome results. By changing the parameters of the environment, in this case hacking the system and replacing the clock source, we can deal with a specific problem with much, much more ease and simplicity.

First to remind, because of toggling the pin state, you need to execute the ISR two times more than the signal frequency. This is 112,000 times per second. 56,000 and 16,000,000 don't add up very nicely as pointed out already. We need to change either the signal frequency or tact frequency. Let's deal for now with an immutable signal frequency and find a better clock speed.

It would be most straightforward to choose a clock with some order of magnitude bigger than 56 kHz (or 112 kHz, but it is practically the same), as you only add zeros and this kind of math is simplest for most people. Unfortunately everything in this world is some kind of compromise with something. Not every value will work.

The first example is with a too low tact generator speed.

If you choose a 56,000 Hz clock you won't be able to do anything as you will need to call the ISR every cycle and can't do anything else. It is utterly useless. If you choose 10 times faster speed (560 kHz), you will have 9 (10 cycles for the timer to reach its max value - one cycle to call ISR function) microcontroller cycles to do your work and this quite possible can be not enough. You simply often need more computational power.

If you choose a value far too great at other hand, as 56 MHz the microcontroller simply can't work with it. It is way too fast. So, simply choosing the biggest value in the shop won't cut it either.

Original Arduino Uno R3 have a stock clock at 16 MHz, so anything slower that that is guaranteed to work. The next value that is an order of magnitude bigger than 56 and lower than 16 MHz is 5.6 MHz. This will lead to be able to call the ISR every 50 cycles and will create the perfect 112,000 Hz timer frequency. And your signal will be exactly 56 kHz. You will have 49 MCU cycles to execute your program between ISR calls, but it is still around 1/3 of the speed of the original clock. One can use 112 as base and use a 11.2 MHz clock and this will give a about 2/3 of the stock 16 MHz resonator. The ISR function will be called every 100 cycles and still generating a perfect 56 kHz signal.

However two major problems exist with these values.

 - The first problem severely depends on your needs: You sacrifice about 1/3 (with 11.2 MHz) of your maximum computational power to get the exact signal frequency that use an easy-to-find register value (OCR *iirc*). You may be fine with it or you may not.

 - The second problem is a **hard showstopper**: It is very easy to find values, but very often they simply do not exist as a manufactured clock source. This is [**Farnell's resonator web page**][1] that simply lack both 5.6 MHz and 11.2 MHz.

To circumvent this we can look at available resonator values and find out something else that can be used to generate exactly desired values. If we divide 56 by 4 we get 14 and luckily there is a 14 MHz resonator. This provides us with much higher speed and more power and with equally easy to find register value. To call the ISR 112,000 times per second we need to put value of decimal 124 or hexadecimal 0x7C in the OCR register, so with counting 124 cycles + 1 for calling the ISR, we get our desired perfect value.

# N.B.

1. ISR - interrupt service routine (this is the code that is executed only on generated interrupts)
2. How big your program can be depends on the memory size! It has nothing to do with the clock speed and has nothing to do with how often you call the ISR.
3. When the microcontroller starts with program command a counter is incremented. If an interrupt is generated, the ISR is called and this value is stored in a special register. When the ISR code completes, the value of the program counter is restored from this special register and the program continues from where it was interrupted as if it had never happened.

    I will give an extremely dumbed-down example. If you are a purist, I warn you: Nose and eye bleeding can occur.

    Imagine you have to walk from somewhere to somewhere. The step-by-step route instructions are your main program and its commands. How fast you walk or run, depends on your "clock speed", but not on the route instructions (30 steps forward, 1 turn 90 grad. left, 10 steps forward, 45 grad. right, etc.) They are always the same. Now imagine a little kid or a greedy corrupt local politician untie your shoes now and then. This is the event that generates an interrupt. Then you halt after your last step, kneel and tie your shoe again. This is your ISR program.

    Then you continue from the place you have stopped; you do not start from beginning. When you walk without a care in the world and with all the time, you don't care even if you have to tie your shoe every other step. If you however do it with time constrains, like running in 100 meters on the Olympics (or running from a hungry flesh-eating predator), stopping and tieing your shoes can have dire consequences. The same is with microcontrollers. Even if you execute only one line of code your program will continue, albeit slow. If you don't care about speed at all, it won't be a problem. If you have to do some time related, like using other timer dependent actions, interference can be very unwanted and problematic.

4. Less is more! A faster clock is not always better. Slower clocked devices use considerably less power. This can be a crucial point in a battery-operated device.

5. The needed cycles are derived from this formulae:

(clock speed / (prescaler value * needed ISR calling frequency)) - 1

  [1]: http://bg.farnell.com/crystals


body: There is no need to use an ISR to create the carrier. Just set up a timer to produce a 50% PWM output at the required carrier frequency. The ISR is then just in charge of modulating the carrier - typically at 0.5 or 1ms intervals - a far more comfortable rate. In my experience a 5% error in carrier frequency is tolerated by most IR receivers. I used a Freetronics EtherMega 2560 (which has plenty of timers) but I'm sure other CPUs will do just as well.


message:
Could someone explain this weird looking code, used to setup timers?

While looking at sketches other people have written, I occasionally come across code that looks somewhat like this:

    TCCR1A = 0;
    TCCR1B = 0;

    TCNT1 = 34286;
    TCCR1B |= (1 << CS12);
    TIMSK1 |= (1 << TOIE1);

All I know is that is has something to with timing/timers (I think). How can I decipher—and create—code like this? What are `TCCR1A`, `TCCR1B`, `TCNT1`, `CS12`, `TIMSK1`, and `TOIE1`?

body:
`TCCR1A` is timer/counter 1 control register A

`TCCR1B` is timer/counter 1 control register B

`TCNT1` is timer/counter 1's counter value

`CS12` is the 3rd clock select bit for timer/counter 1

`TIMSK1` is timer/counter 1's interrupt mask register

`TOIE1` is the timer/counter 1 overflow interrupt enable

So, the code enables timer/counter 1 at 62.5 kHz and sets the value to 34286. Then it enable the overflow interrupt so when it reaches 65535, it will trigger the interrupt function, most likely labelled as `ISR(timer0_overflow_vect)`


body:
This isn't weird looking. It's what normal MCU code actually looks like.

What you have here is an example of the concept of *memory-mapped peripherals*. Basically, the MCU hardware has special locations in the SRAM address space of the MCU assigned to it. If you write to these addresses, the bits of the byte written to address *n* control the behaviour of peripheral *m*.

Basically, certain banks of memory literally have little wires running from the SRAM cell to the hardware. If you write a "1" to this bit in that byte, it sets this SRAM cell to a logical high, which then turns on some portion of the hardware.

If you look into the headers for the MCU, there are great big tables of keyword<->address mappings. This is how things like `TCCR1B` etc... are resolved at compile time.

This memory-mapping mechanism is extremely broadly used in MCUs. The ATmega MCU in the arduino use it, as do PIC, ARM, MSP430, STM32 and STM8 MCU series, as well as lots of MCUs I'm not immediately familiar with.

---

*Arduino* code is the weird stuff, with functions that access the MCU control registers indirectly. While this is somewhat "nicer" looking, it's also much slower, and uses a lot more program space.

The mysterious constants are all described in great detail in the [ATmega328P datasheet][1], which you really should read if you're interested in doing anything more then occationally toggling pins on an arduino.

Select excerpts from the datasheet linked above:

![enter image description here][2]
![enter image description here][3]
![enter image description here][4]

So, for example, `TIMSK1 |= (1 << TOIE1);` sets the bit `TOIE1` in `TIMSK1`. This is achieved by shifting binary 1 (`0b00000001`) to the left by `TOIE1` bits, with `TOIE1` being defined in a header file as 0. This is then bitwise ORed into the current value of `TIMSK1`, which effectively set this one bit high.

Looking at the documentation for bit 0 of `TIMSK1`, we can see it is described as

> When this bit is written to one, and the I-flag in the Status Register
> is set (interrupts globally enabled), the Timer/Counter1 Overflow
> interrupt is enabled. The corresponding Interrupt Vector (See
> ”Interrupts” on page 57) is executed when the TOV1 Flag, located in
> TIFR1, is set.

All the other lines should be interpreted in the same manner.

---

Some notes:

You may also see things like `TIMSK1 |= _BV(TOIE1);`. `_BV()` is a [commonly used macro][5] originally from the [AVR libc implementation][6]. `_BV(TOIE1)` is functionally identical to `(1 << TOIE1)`, with the benefit of better readability.

Also, you may also see lines such as: `TIMSK1 &= ~(1 << TOIE1);` or `TIMSK1 &= ~_BV(TOIE1);`. This has the opposite function of `TIMSK1 |= _BV(TOIE1);`, in that it *unsets* the bit `TOIE1` in `TIMSK1`. This is achieved by taking the bit-mask produced by `_BV(TOIE1)`, performing a bitwise NOT operation on it (`~`), and then ANDing `TIMSK1` by this NOTed value (which is 0b11111110).

Note that in all these cases, the value of things like `(1 << TOIE1)` or `_BV(TOIE1)` are fully resolved at *compile time*, so they functionally reduce to a simple constant, and therefore take no execution time to compute at runtime.

---

Properly written code will *generally* have comments inline with the code that detail what the registers being assigned to do. Here is a fairly simple soft-SPI routine I wrote recently:

    uint8_t transactByteADC(uint8_t outByte)
    {
     // Transfers one byte to the ADC, and receives one byte at the same time
     // does nothing with the chip-select
     // MSB first, data clocked on the rising edge

     uint8_t loopCnt;
     uint8_t retDat = 0;

     for (loopCnt = 0; loopCnt < 8; loopCnt++)
     {
      if (outByte & 0x80)   // if current bit is high
       PORTC |= _BV(ADC_MOSI);  // set data line
      else
       PORTC &= ~(_BV(ADC_MOSI)); // else unset it

      outByte <<= 1;    // and shift the output data over for the next iteration
      retDat <<= 1;    // shift over the data read back

      PORTC |= _BV(ADC_SCK);   // Set the clock high

      if (PINC & _BV(ADC_MISO))  // sample the input line
       retDat |= 0x01;   // and set the bit in the retval if the input is high

      PORTC &= ~(_BV(ADC_SCK));  // set clock low
     }
     return retDat;
    }

`PORTC` is the register that controls the value of output pins within `PORTC` of the ATmega328P. `PINC` is the register where the *input* values of `PORTC` are available. Fundamentally, things like this are what happen internally when you use the `digitalWrite` or `digitalRead` functions. However, there is a look-up operation that converts the arduino "pin numbers" into actual hardware pin numbers, which takes somewhere in the realm of 50 clock cycles. As you can probably guess, if you're trying to go fast, wasting 50 clock cycles on an operation that should only require 1 is a bit ridiculous.

The above function probably takes somewhere in the realm of 100-200 clock cycles to transfer 8 bits. This entails 24 pin-writes, and 8 reads. This is many, many times faster then using the `digital{stuff}` functions.

  [1]: http://www.atmel.com/Images/Atmel-8271-8-bit-AVR-Microcontroller-ATmega48A-48PA-88A-88PA-168A-168PA-328-328P_datasheet.pdf
  [2]: https://i.stack.imgur.com/przAI.png
  [3]: https://i.stack.imgur.com/P3Yu2.png
  [4]: https://i.stack.imgur.com/faCfk.png
  [5]: http://www.nongnu.org/avr-libc/user-manual/FAQ.html#faq_use_bv
  [6]: http://www.nongnu.org/avr-libc/user-manual/index.html


body:
CS12 has a value of 2 since it represents bit 2 of the TCCR1B register.

(1 << CS12) takes the value 1 (0b00000001) and shifts it left 2 times to get (0b00000100).
The order of operations dictates that things in () happen first, so this is done before the "|=" is evaluated.

(1 << CS10) takes the value 1 (0b00000001) and shifts it left 0 times to get (0b00000001).
The order of operations dictates that things in () happen first, so this is done before the "|=" is evaluated.

So now we get TCCR1B |= 0b00000101, which is the same as TCCR1B = TCCR1B | 0b00000101.

Since "|" is "OR", all the bits other than CS12 in TCCR1B are unaffected.


message:
How can a 5v Uno talk to a 3.3v Due?

I currently have an Uno (which operates at 5v), and I'm looking at buying a Due (which only operates at 3.3v). I'd like to make them communicate via Serial or SPI or similar, but presumably connecting them directly isn't an option (I guess the Due's pins would get damaged).

Is there any way to make the connection safe? Or is there an alternative form of communication I could safely use between them instead?

body:
- For a 5V logic output to a 3V3 logic input, you can use a resistive divider to lower the voltage.
- When unloaded, a 3V3 logic output is just enough to drive a 5V logic input. Check the AVR datasheet for the exact voltages (0.6 × Vcc = 3V, found under DC Characteristics in the datasheet).

In other words, with a little bit of special care it may just work.

To construct a more reliable and bidirectional solution, use a level shifter. There are several listed on [this page](http://www.nxp.com/products/logic/level_shifters_translators/#products) but other manufacturers make similar devices.

[This document](http://www.nxp.com/documents/application_note/AN10441.pdf) describes how a MOSFET can be used to bidirectionally convert logic levels between different supply voltages.


message:
Generating PWM signal 1-2 ms @ 333 Hz

I'm currently working with the `Talon SR Speed Controller` and it requires a specific Input PWM Signal of `1-2 ms @ 333 Hz` and an input resolution of `10-bit (1024 steps)`. Currently I use the `Servo` library to handle these requirements, but was having some issues of the motors jumping their dead-band from forwards to backwards really fast causing the motors to rock back and forwards a few millimeters. If the `servo1.write(pwmValue);` isn't my issues please let me know?

If there is a way to specifically achieve the 333Hz PWM signal for 4 motors of the same Uno or Due (most likely will transfer to a Due in a few days) I would like to implement that.

From my understand I can modify the timers registers for the arduino specifically, but don't know exactly how to do that or to achieve 333Hz. If someone could please help me understand this I would greatly appreciate it.

**Speed SR  Speed Controller Information:**

    Input voltage 6-28 VDC
    Continuous current 60 A
    Peak current 100 A
    Input PWM signal 1-2 ms @ 333 Hz
    Input resolution 10-bit (1024 steps)
    Output resolution 10-bit (1024 steps)
    Output switching frequency 15 kHz
    4% neutral dead band

body:
I am playing on a Arduino UNO, you would have to compare the datasheets to determine differences.

For my research on this answer I am looking at:

- [Code/PwmFrequency (for a quick rundown)][1]
- [Tutorial/PWM][2]
- [TimerPWMCheatsheet (explains the prescaller and resulting frequencies)][3]
- [varying the pwm frequency of timer0 and timer2][4]
- [feature request: adjustable pwm frequencies][5]
- [pwm frequency library (this is the one you REALLY want)][6]
- and the datasheet for the [ATMega328][7]

Also:

- we know PWM pins are D3, D5, D6, D9, D10, D11
- I am using D11 for this since I can attach my oscilloscope to the MOSI pin of the ISCP
- D11 maps to PB3 (MOSI/OC2A/PCINT3) (see datasheet or [this cool gfx][8])

----------

## Normal usage ##
First, let's see what happens when we set an arbitrary PWM on pin 11

    int DUTY = 25;
    analogWrite(11, DUTY * 256 / 100);

results in:

1. Freq: ~487Hz
2. Duty: ~25%
3. Time: ~2.05ms

This first point I will make is that with the given 490Hz the PWM duration is actually 2ms which seems to be close to what you want (you said between 1-2ms), maybe my misunderstanding there.

----------

## Playing with pre-scalers ##
From several of the links posted above, you will see that you have different pre-scalers available depending on which timer you are using: eg.

**Pins 5 and 6: controlled by Timer 0 in fast PWM mode (cycle length = 256)**

    Setting     Divisor     Frequency
    0x01        1           62500
    0x02        8           7812.5
    0x03        64          976.5625
    0x04        256         244.140625
    0x05        1024        61.03515625

    TCCR0B = TCCR0B & 0b11111000 | <setting>;

**Pins 9 and 10: controlled by timer 1 in phase-correct PWM mode (cycle length = 510)**

    Setting     Divisor     Frequency
    0x01        1           31372.55
    0x02        8           3921.16
    0x03        64          490.20
    0x04        256         122.55
    0x05        1024        30.64

    TCCR1B = TCCR1B & 0b11111000 | <setting>;

**Pins 11 and 3: controlled by timer 2 in phase-correct PWM mode (cycle length = 510)**

    Setting     Divisor     Frequency
    0x01        1           31372.55
    0x02        8           3921.16
    0x03        32          980.39
    0x04        64          490.20
    0x05        128         245.10
    0x06        256         122.55
    0x07        1024        30.64

    TCCR2B = TCCR2B & 0b11111000 | <setting>;

    (All frequencies are in Hz and assume a 16000000 Hz system clock.)

These are relatively simple to setup and use (the setting is at the bottom of each of the above code blocks), but you have to be mindful of playing with the pre-scaler of timer0 (which controls `millis()` and `delay()`). So if you have a choice, steer clear of timer0, or pwm pins 5 and 6.

Example of using just the inbuilt pre-scalers without any additional libraries:

    #define PIN 11
    void setup(){
        pinMode(PIN,OUTPUT);  // not absolutely required
        int DUTY = 20;
        TCCR2B = TCCR2B & 0b11111000 | 6;
    }

    void loop() {
      static long counter = 0;
      if(millis()==0){
          counter++;
          analogWrite(PIN, counter%5);
      }
    }

I know you can manipulate the frequency better than that, and I have been playing with this for hours and then I finally stumbled upon the final link (which believe it or not, I found via YouTube!).

----------
## Using an External Library ##

To use the PWM library you will need to download it from [Google Code][9], save/import/get it into your library folder, and restart the IDE. Once you do that, you can explicitly set the frequency (within limits, 333Hz is within those limits), and you should be set.

Code example:

    #include <PWM.h>
    int32_t frequency = 333;

    #define PIN 10

    void setup(){
        pinMode(PIN,OUTPUT);
        int DUTY = 20;
        InitTimersSafe();                    // won't touch timer0
        SetPinFrequencySafe(PIN,frequency);  // again, not timer0
        pwmWrite(PIN, DUTY * 256 / 100);
    }

There is even a `pwmWriteHR` which allows for higher resolution, but that does not work with timer2 (which is only an 8-bit timer).

The matching, non-safe (ie initialises and uses timer0 as well) functions are:

    InitTimer();  // and
    SetPinFrequency(PIN,frequency);

The only limitation I have found so far is that it doesn't work with PWM pin D11. I have tested D3, D9 and D10 (they all worked fine), but I did not get around to testing D5 or D6.

Good luck, I hope this helps.

  [1]: http://playground.arduino.cc/Code/PwmFrequency#.Uw7UNfSSxfg
  [2]: http://arduino.cc/en/Tutorial/PWM#.Uw7P6fSSxfh
  [3]: http://playground.arduino.cc/Main/TimerPWMCheatsheet#.Uw8UafSSxfg
  [4]: http://forum.arduino.cc/index.php/topic,16612.0.html
  [5]: http://forum.arduino.cc/index.php/topic,46949.0.html
  [6]: http://forum.arduino.cc/index.php?topic=117425.30
  [7]: http://www.atmel.com/ru/ru/Images/Atmel-8271-8-bit-AVR-Microcontroller-ATmega48A-48PA-88A-88PA-168A-168PA-328-328P_datasheet.pdf
  [8]: http://arduino.cc/en/Hacking/PinMapping168#.Uw7gxfSSxfg
  [9]: http://code.google.com/p/arduino-pwm-frequency-library/downloads/list


body:
This will command a Talon SR from an Arduino.  I used an Uno and had the Talon hooked up to a CIM motor & gearbox and it ran fine.  I don't understand the code well enough to know if it's generating the 1-2ms PWM signal you asked about and your control resolution will definitely be limited to roughly 1% of range - all I know is that it works.

First, make sure your wiring is set up:

Black PWM wire goes to GND
Red PWM wire goes to 5V (right next to GND on the Arduino)
White PWM wire goes to pin 3 (or some other Arduino PWM pin)

Then try this code:

    #include <Servo.h>  //This comes with the Arduino

    int talon_pin = 3;

    Servo talon;

    /* The 'Servo.h' library allows you to control motors and servos by passing any value between
    0 and 180 into the "write" method (talon.write() in this program).
    For a motor:   0 is full power in one direction,
                 180 is full direction in the opposite direction,
                  90 is stop.
    For a servo:   0 is all the way one direction,
                 180 is all the way in the opposite direction,
                  90 is the middle.
    */

    int talon_max_forward = 180;  //this might not actually be forward
    int talon_max_reverse = 00;    //this might not actually be reverse
    int talon_stop = 90;          //this is definitely stop (if the Talon is calibrated right)

    void setup() {
      talon.attach(talon_pin);  //This tells the arduino to control this pin like it's a servo/motor
    }

    void loop() {
      talon.write(talon_max_forward);   //full power one way
      delay(2000);                      //wait 2 seconds
      talon.write(talon_stop);          //full power the other way
      delay(2000);                      //wait 2 seconds
      talon.write(talon_max_reverse);   //full power one way
      delay(2000);                      //wait 2 seconds
      talon.write(talon_stop);          //full power the other way
      delay(2000);                      //wait 2 seconds
    }

The Talon I used was fresh out of the box and had never been calibrated before, so the "stop" didn't actually stop - it just moved slowly.

To calibrate it, use a paper clip or pen / pencil to press and release the CAL button on the Talon (next to the LED).  You have to press AND release when commanded to stop (after going full + and full - in between), but the motor doesn't turn when the button is pressed.  I calibrated by running the program above with the motor attached, waiting for the motor to "stop", then pressing and holding for 8 seconds.  If you have trouble hitting it, increase one of the delays after a talon_stop command.


body:
You'll need to edit the library file, Servo.h.

Find the line...

`#define REFRESH_INTERVAL    20000     // minumim time to refresh servos in microseconds`

And change the refresh interval - 20000us (20ms) is the standard 50Hz rate.

Change it to 3003 to get 333Hz rate.

This will permanently change the Servo library to 333Hz.  If you need 50Hz servos, it would be best to duplicate the Servo library to Servo333 or something.

You will not be able to run both at the same time as they use the same timers.

(This is based on the standard Servo library in arduino 1.06)


message:
Last element of a struct disappearing on write/read

I'm building a weather station with two UNOs, using NRF24l01+ radios. Communications are fine. I'm sending a struct from one to the other. The struct has three elements:

        struct weather {
          float tempData;
          float humData;
          float pressData;
        };
        weather wData = {0, 0, 0};

I then populate the struct with values from my DHT22 Temperature Sensor and my BMP085 pressure sensor.

        float c = dht.readTemperature();
        wData.tempData = (c * 9/5) + 32;
        wData.humData = dht.readHumidity();

        sensors_event_t event;
        bmp.getEvent(&event);
        wData.pressData = (0.0295 * event.pressure);

Now I send it via the NRF24L01+.

        radio.write(&wData, sizeof(wData);

On the receiving Uno I have this.

        struct weather {
          float tempData;
          float humData;
          float pressData;
        };

        weather wData = {0, 0, 0};

        radio.read( &wData, sizeof(wData) );
        Serial.println(wData.tempData);
        Serial.println(wData.humData);
        Serial.println(wData.pressData);

I get results similar to this:

        Temp = 75.43
        Hum = 35.76
        Press = 0.00

The first two are correct. The final one is not. I can change the order and the first two will always be correct, but the last element is always 0.00. For example:

       Hum = 35.76
       Press = 30.14
       Temp = 0.00

I know I'm missing something here with my code but I can't find it. Anyone have some suggestions?

body:
Modified my `struct` by changing the first two elements from `float` to `int`.

    struct weather {
      int tempData;
      int humData;
      float pressData;
    }
    weather wData;

**Everything transmits fine now.** I don't really need the precision of a `float` for temperature and humidity. However, I would still like to find the problem. Could there be some problem with the size of three `floats` versus two `ints` and a `float`? `Serial.print(sizeof(wData))` is `12` when all elements are `floats` and `8` when using two `int` and a `float`. My understanding is the NRF24L01+ has a transmit and receive buffer of 32 bytes.


message:
What will happen if I give my Arduino Uno more or less than 5 volts?

Will it still run on less than 5 volts? Will it break?

body:
Will it break at < 5V? Not likely.
=

- Check the datasheet for the IC's on the board and find the minimum power supply voltage the device works at.
- At typical ATmega328 Safe Operating Area (under "Speed grades" in the datasheet) specifies approximately 4.1V for 16MHz.
- If you require to use the USB interface, you'll have to check the datasheet for that chip too.

Will it run at < 5V? Maybe.
=
- If the supply voltage gets below the minimum operational voltage, the controller may behave erratically. That means it can do anything (un)expected. This value is in the datasheet and probably somewhere around 2.7V.
- If the Brown Out circuit is configured (in fuses), then the controller will switch itself off when supply voltage gets too low to prevent undefined situations. Once the supply voltage returns, it restarts.

Will it break at > 5V? Depends on where you apply it.
=
- V(IN) should work fine for 7-20VDC as it is fed through an on board regulator. Notice though that the regulator has to dissipate the excess voltage and can get pretty hot when you draw a fair bit of current. The regulator will fail if the voltage goes over 20V or gets too hot too often;
- +5V should work fine up to 5V, and I personally wouldn't worry if an external supply delivers up to 5.5V unloaded. Above that 5.5V you will probably release the magic blue smoke.


message:
How can I connect to an Arduino using WiFi?

I'm working on building a solar powered, Arduino based weather station. The weather station consists of a temperature sensor and a photoresistor, and I plan to add an anemometer in the future. I would like to connect the weather station to my wireless network so that I can retrieve the sensor data from my computer without having to run wires (I live in a rental).

What are the different options for connecting the Arduino to WiFi? I've looked at ethernet shields, WiFi shields, and something called Xbee, but I don't understand what each of them are for.

I also have a wireless home router that I could use. Is it possible to connect my Arduino Uno to the router via the routers ethernet or USB port and then receive data from and send commands to the Arduino wirelessly over my home network? If so, how would this be accomplished?

I currently have a bare Arduino Uno.

body:
You have a few options for connecting your Arduino to the network/Internet.

## Ethernet

Something like the [Arduino Ethernet Shield][1] allows you to plug in an Ethernet cable from the wall or router into your Arduino. Obviously, the main limitation is that your device is now tethered by the cable. For outdoor use, I wouldn't do this.

## WiFi

The [Arduino WiFi Shield][2] allows you to connect to your home WiFi network. This is just like the Ethernet except its now wireless.

The [ESP8266][6] is a cheaper alternative that, with the default firmware, has the same functionality as the WiFi Shield. Be careful that you power it with 3.3V and not 5V as the rest of the Arduino. It also uses 3.3V logic levels so don't connect the Arduino's TX pin directly to the ESP's RX pin; use a voltage divider.

## RF

If you have a lot of sensors or other devices that need to communicate with each other, the best option is usually an RF module. You have many options here, XBee being one of them. Check out the [Sparkfun XBee Buying Guide][3] to look at all the options available. And that's just XBee. There are many other wireless options available, at all sorts of prices.

The thing with RF is that none of these will connect to the Internet. You will have all your devices communicate with each other or a base station, which will then be connected to the network by either a WiFi or Ethernet module.

## Wireless Router Serial

Depending on what kind of wireless router you use, you can have the Arduino communicate directly with it and use that as your connection to a network.

* [Arduino - Cheap wifi connectivity][4]
* [Converting your Ethernet Shield to a wireless shield][5]

  [1]: http://arduino.cc/en/Main/ArduinoEthernetShield
  [2]: http://arduino.cc/en/Main/ArduinoWiFiShield
  [3]: https://www.sparkfun.com/pages/xbee_guide
  [4]: http://www.thebmwz3.co.uk/article.php?story=20120611144749730
  [5]: http://hackanerd.wordpress.com/2013/07/06/how-to-make-a-simple-arduino-wireless-shield/
  [6]: https://www.sparkfun.com/products/13678


body:
I've been working with xbee on the arduino and raspberry pi for a few months now. Whilst it does have it's issues and quirks, it is a great tool in the communication chain. It's not perfect but given the mesh side of it, for me it reaches further than my wifi and can even be more reliable (my raspberry pi with wifi occasionally drops out, however the connected xbee continues to function in the background.

Specifically in my case it allows for a serial connection between my devices (being several arduinos, a raspberry pi (coordinator) and my mac (used primarily for monitoring but also occasionally injecting serial data)). In this case it's perfect. It doesn't allow internet access or access beyond the xbee framework, but that suits me perfectly since implementation is as simple as Serial.print and Serial.read with no Ethernet overhead.


body: I use Spark Core which is a very easy to use Arduino programming platform. This platform was built on the primus that WiFi should be easy to use and cheap. Can even program the Spark Core from anywhere, any time.


body:
You could try a Arduino Yun, it is like a Uno but it has a WiFi directly on the board.

There is a part in the ["Guide to the Arduino Yún" called "Configuring the onboard WiFi"][1], that describes how to configure the WiFi.

  [1]: http://arduino.cc/en/Guide/ArduinoYun#toc13


body:
# Marry OpenWrt and your Arduino

Get a small OpenWrt-capable router like "TP-Link TL-WR703N", flash it with the current stable version of OpenWrt and connect your Arduino to the router's USB port.

This solution ist half or less of the cost of WiFi-shields and has far more power.

...and cheaper as a YÙN.

[Smart home automation webserver on OpenWRT router WR703N interfaced to Arduino, compared to Raspberry Pi and Ubuntu][1] may be a starting point to read about this and your favorite search engine will find many more links about marrying WR703N and Arduinos...

  [1]: http://www.instructables.com/id/How-to-set-up-OpenWRT-on-a-pocket-router-WR703N/

(!) Please see https://arduino.stackexchange.com/a/1754/653 too....


body:
What you want is pretty easy to do, and the code exists already.  But the way I invision it, you won't connect the sensor Arduino to your wifi.  Instead, you'll use another Arduino as your gateway like this:

Sensor Arduino:  Located outside, connected to temperature sensor, wind speed, rain gauge?

Gateway Arduino: Located inside, w/ Wiznet 5001 ethernet shield

The Sensor Arduino and Gateway Arduino talks to each other using a VERY easy to use wireless transceiver, nRF24L01+.  The wireless modules are $3 each, and the library for use is very mature.  All the sensor data is easily communicated to the Gateway using this library.

The Gateway Arduino w/ the ethernet acts as a webserver, enabling any computer in your local network to open up a page and view current conditions.  Look at this page for the Arduino code:
http://arduino.cc/en/Tutorial/WebServer

You want to also save historical temperature/wind speed information right?  This is the best part! The Gateway Arduino can push data to a service like Xively, a free web-based data collection service that also gives you a nifty way to visualize/graph your data.  There is a little hiccup with using the Wiznet along with the nRF24L01 module.  The wireless module and ethernet shield both use the same bus to communicate, so take a look at this blog to see how you can use both at the same time:

http://www.heald.ca/content/arduino-ethernet-nrf24l01-and-pachubecosmxively

Xively also lets you make that data public or private, so you can chose to contribute your weather station data to the community.

Some other notes:
I like nRF24L01+ modules because they're dirt cheap.  Xbee modules cost more than the Arduinos themselves.  You can keep adding nRF24L01+ modules around the house once you establish a gateway.  The same cost problem exists with wifi shield - expensive.


body: ESP8266 is a cheap 5$ wifi module with UART, SPI connectivity. This can be integrated with Arduino seamlessly either through the stock firmware using AT commands, or by writing custom firmware using the SDK provided and GIPO available. For more reference http://www.esp8266.com/


body: Check ESP8266 wifi module , it's a cheap module and can be controlled using any microcontroller by AT commands , also it's Soc so you can use it standalone .


body:
Using the ESP8266 AT cmd set is difficult and error prone.
Suggest you reflash the ESP8266-01 as a UART-WiFi bridge as described here
[ESP8266 Wifi Add on for Arduino Made Simple][1]

Note that setup also lets you re-configure your wifi settings without re-programming the ESP8266-01

  [1]: http://www.forward.com.au/pfod/ESP8266/simpleWiFiAddon.html


body:
If you want a cheaper alternative to add WiFi capabilities to Arduino look at [ESP WiFi shield][1].

It works great with [WiFiEsp library][2].
Programming model is exactly the same as Arduino WiFi Shield

  [1]: http://www.instructables.com/id/Cheap-Arduino-WiFi-Shield-With-ESP8266/
  [2]: http://yaab-arduino.blogspot.it/p/wifiesp.html


body:
Using the ESP8266 sield is error prone, requires an update that needs to be flashed, some soldering required, and it's not appropriate for a production environment. Also, there are issues with the power supply because you need to have a *separate* 3.3V power supply.  It's 2016 (!) and there are a bunch more options available now.

"The UNO WiFi board is the Arduino UNO with integrated WiFi." http://www.arduino.org/products/boards/arduino-uno-wifi

and

"The Star Otto is the first Arduino board featuring the STM32F469 processor with WiFi." http://www.arduino.org/products/boards/arduino-star-otto (Actually, as of October, it's still not available, "Coming Soon").

Please note these two boards are from the **OTHER** Arduino organization.


body:
After several trials & errors in my IoT project, I would recommend working on ESP32 over ESP8266(and also Arduino Uno & Nano), **except if you know very well the scope of your project.**

Advantages of ESP32 over ESP8266:

 1. Bigger RAM, ESP8266: 32KB instruction & 80 KB user data, ESP32: 520 KB

I'm working on an IoT project and trying to authenticate the device on GCP using a certificate. The root certificate of GCP is already about 120 KB, so it does not fit into ESP8266. There are alternatives but that complicates things.

 2. ESP32 has bluetooth & ESP8266 not

Well at some point of your IoT project you might want bluetooth to connect your device with your phone ...

 3. Some versions of ESP32 has integrated ports for the camera (search ESP32 CAM)

With ESP8266 you can surely use a camera but that will involve more coding & wiring and potentially worse performance.

And at last, I tried to wire a wifi chip with Arduino Uno & Nano but I encountered some bugs and problems with the AT commands. Thus now I'm quite happy with ESP32 because everything is integrated.


message:
Extracting data from Arduino MultiWii Flight Controller

I am new to the world of Arduinos but have a new project going with a MultiWii Flight controller. With the MultiWii comes a software for showing all data that is measured from the sensors (acceleration, velocity, roll, pitch, etc) which is nice but I would like to have/extract this data (call raw data or something) from all sensors (i.e. the data plotting everything, in numbers). Maybe it is the simplest thing to do, and I guess I have to set up some serial connection between the controller and tell it to send this data somehow but I do not know where to start so any guidance and help is appreciated.

body:
Since you're new to Arduino, I'd suggest beginning with a basic interfacing arduino activity. Once you understand reading and writing digital and analog signals it's pretty much plain sailing from there. You may want to invest some time and a bit of cash in a beginners course on Udemy (try PEter Dalmaris' course [https://www.udemy.com/arduino-sbs/][1]) it's a good start. From there, talking to the MultiWii should be a piece of cake. Also, check out [http://www.multiwii.com/connecting-elements][2]

  [1]: https://www.udemy.com/arduino-sbs/
  [2]: http://www.multiwii.com/connecting-elements


message:
How does this code line detect if a serial interface is connected?

I am working with some code for remote temperature sensor nodes. They turn the debug interface on and off depending on if anything is conneced to the serial port or not.

The code is on Github [here][1]. Line [111][2] is the line of interest:

    if (Serial) debug = 1; else debug=0; //if serial UART to USB is connected show debug O/P.

So, a simple question: On a hardware and software level, how does this work? I can't see anything in HardwareSerial or Stream that would return true/false if anything was connected or not.

Note that I am not confident that it actually works. This simple test indicates it doesn't work as the LED flashes regardless of the presence of a serial adapter or connection:

    boolean debug;

    const int toggle = 6;

    void setup()
    {
      if (Serial) debug = 1; else debug = 0;

      pinMode(toggle, OUTPUT);
      digitalWrite(toggle, LOW);

      if (debug)
      {
        Serial.begin(9600);
        Serial.println("Setup");
        digitalWrite(toggle, HIGH);
        delay(1000);
        digitalWrite(toggle, LOW);
      }
    }

    void loop()
    {
      if (debug)
      {
        Serial.println("Loop");
        digitalWrite(toggle, HIGH);
        delay(1000);
        digitalWrite(toggle, LOW);
        delay(1000);
      }
    }

  [1]: https://github.com/openenergymonitor/emonTH/blob/master/emonTH_DHT22_DS18B20/emonTH_DHT22_DS18B20.ino
  [2]: https://github.com/openenergymonitor/emonTH/blob/40b8d4d42ad301b7877c1f5f18d492cc0e4317a9/emonTH_DHT22_DS18B20/emonTH_DHT22_DS18B20.ino#L111

body:
You're right -- it doesn't work in most cases, and will almost always return true. The one board where it's actually functional is the Leonardo. According to the [official documentation][1]:

> On the Leonardo, **if (Serial)** indicates wether or not the USB CDC serial connection is open. For all other instances, including **if (Serial1)** on the Leonardo, this will always returns true.

Basic serial connections (used by most Arduinos) usually don't care if anything is actually listening. It's not uncommon for embedded devices to send debug info by serial even when nothing is receiving it. This has the advantage that the code's timing and behaviour won't change when debugging, which could cause all sorts of problems if you're trying to diagnose a problem reported in the field.

  [1]: https://www.arduino.cc/reference/en/language/functions/communication/serial/ifserial/


body:
While it may not be possible to detect whether a device is connected to the Arduino serial connection or not, it is possible to *enable the debug messages over the serial connection* based on the presence of a device on the serial connection.

Considering that you will be using the debug interface of your sketch only when connected to a computer capable of serial communication, it is possible to incorporate a simple test into the sketch based on which debug mode is enabled or not.

When the sketch starts, you can check to see if any data is available on the Serial connection or not. If there is, then a device is present and debugging can be enabled. On the computer side, everytime you want to start the debugging mode on the Arduino, simply send a byte over the serial connection during the `setup` phase and sit back.

Here is a sample sketch showing the same:

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

    int debug = 0;

    void setup()
    {
      pinMode(13, OUTPUT);
      Serial.begin(9600);

      //Wait for four seconds or till data is available on serial,
      //whichever occurs first.
      while(Serial.available()==0 && millis()<4000);

      //On timeout or availability of data, we come here.
      if(Serial.available()>0)
      {
        //If data is available, we enter here.
        int test = Serial.read(); //We then clear the input buffer

        Serial.println("DEBUG"); //Give feedback indicating mode

        debug = 1; //Enable debug
      }
    }

    void loop()
    {
      if(debug==1) Serial.println("ON");
      digitalWrite(13,HIGH);
      delay(1000);
      if(debug==0) Serial.println("OFF");
      //Turn off if serial is not available
      digitalWrite(13,LOW);
      delay(1000);
    }


message:
Why does starting the serial monitor restart the sketch?

If I upload any sketch that sends serial data, I immediately see the TX/RX LEDs flash once the sketch is uploaded. If I then start the serial monitor, the sketch appears to restart.

A bare minimum sketch that shows this behaviour:
```cpp
    void setup()
    {
        Serial.begin(9600);
        Serial.println("Setup");
    }

    void loop()
    {
      Serial.println("Loop");
      delay(1000);
    }
```
Tested with several boards and Mac and Windows versions of the IDE.

Example output - it goes back to "Setup" when I open the serial monitor:

![Restart][1]

Why is this?

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

body:
The Arduino uses the [RTS (Request To Send)][1] (and I think [DTR (Data Terminal Ready)][2]) signals to auto-reset. If you get a serial terminal that allows you to change the flow control settings you can change this functionality.

The Arduino terminal doesn't give you a lot of options and that's the default. Others will allow you to configure a lot more. Setting the flow control to none will allow you to connect/disconnect from the serial without resetting your board. it's quite useful for debugging when you want to be able to just plug in the connector and see the output without having to start the sketch over.

Another way to disable the auto reset is to put a pull up resistor on the reset pin.

[Disabling Auto Reset On Serial Connection][3]

  [1]: http://en.wikipedia.org/wiki/RS-232_RTS/CTS#RTS.2FCTS_handshaking
  [2]: http://en.wikipedia.org/wiki/Data_Terminal_Ready
  [3]: http://playground.arduino.cc/Main/DisablingAutoResetOnSerialConnection


body:
The truth is always in the datasheets, the schematics and the code:

The Arduino UNO actually uses the `/DTR` line to trigger a reset, as you can see on the following datasheet:

[![reset schematic][1]][1]

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


body:
This fixes the problem

    import os
    import sys
    import termios
    import fcntl

            self.fd = sys.stdin.fileno()

            # Stop resetting the arduino on serial connect

            self.newattr = termios.tcgetattr(self.fd)
            self.newattr[2] = self.newattr[2] & ~termios.HUPCL
            termios.tcsetattr(self.fd, termios.TCSANOW, self.newattr)


body:
Arduino uses the **DTR line** (data terminal ready)

So, with the Arduino Serial Monitor it is not possible to change the restart when established the rs232 connection.

But I'm using for example the freeware "HTerm" (under Windows). By default, it does not use the DTR signal.
Meanwhile I changed to the freeware "**CoolTerm**" (a bit more comfortable...): You have to deactivate "DTR Off" unter "Connection Options".
In Linux I'm using the "moserial". Under "PortSetup" you must deactivate the "handshake" ;-)

This way is more comfortable for me then adjusting the RESET pin. Also, its a nice benefit saving all the data in a log file for later analyzing…


message:
Why does my Arduino IDE hang/crash so often?

I've traditionally used a text editor with avr-gcc and makefiles for working with Arduino boards. I'm now trying to develop projects for the wider Arduino user-base, so I am trying to use the Arduino libraries and common IDEs for ease of use.

I started using Stino, but then found out that the Arduino IDE has some toolchain "quirks" that mean I will need to test everything in Arduino IDE expressly.

Since starting to use it more, I have found it frequently hangs or crashes. The triggers for this are:

 - Creating a new sketch takes about 15s, and shows me the OS X beach
   ball.
 - Saving a sketch takes about 15s.
 - Going to File->Examples frequently crashes the IDE - I need to force quit.
 - Going to
   File->Sketchbook always crashes the IDE.
 - It sometimes randomly hangs.

I don't have any other stability issues and other Java based IDEs like Pycharm work flawlessly.

I have installed numerous libraries, including the entire Teensyduino suite (which is a lot of libraries!). Outside of that, no changes have been made.

Is this a common issue? Is there any logging or anyway I can try and work out what is causing this issue?

This is happening with:
 - Arduino 1.05
 - Arduino 1.55

I have tried uninstalling and reinstalling.

body:
## Just [report it to Arduino](https://github.com/arduino/Arduino/issues).
You don't really have any other option. I've been waiting to answer this question until I was sure that no one here knew the answer. You don't really have any other option.

This seems like a bug. **We're not Arduino developers or a bug tracking site.** We can only do so much here. Even if it was confirmed a bug and we fixed it, there's only so much that can be done without submitting a report.
****
**BEFORE YOU SUBMIT A REPORT:**

 - I'd try copying out the libraries from Arduino. So many libraries
   might make Arduino IDE somewhat heavier. I don't know if it'll really
   affect the sluggishness but it's worth a shot.
 - The only other thing that I can think of, besides RAM (which you
   already said wasn't an issue) and the libraries, is some sort of
   cache/temporary file. Try reinstalling Arduino, even if you haven't,
   and also I'd try using the [beta 1.5.6-r2
   version](http://arduino.cc/en/main/software). It has to be pretty
   stable for it to be the only version that supports the YUN and DUE.
   Both have been out for a considerable amount of time with this
   software, so I'd imagine that it's pretty stable minus a few issues.

> Many things are said to have been improved compared to the previous 1.0.5-r2 version.

It'd be stupid not to try the newer version.

![GitHub Screenshot][1]

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


body: For debug and logging you can use the Mac Console app, it will show any errors that come up from the App. You might need to filter for Arduino App related messages though.


message:
Why does opening the Tools menu take so long?

Every time I open the `Tools` menu, the IDE freezes for a few seconds. Why is that? It happens on both of my computers, and nothing I do makes a difference in how long it takes. I've tried restarting the IDE, unplugging my Uno, and many other things, but nothing helps.

I'm on windows, running IDE version 1.0.2.

body:
It's an RXTX issue. RXTX is the native serial library used to make the IDE talk to the boards.

On some Windows installation, with some Bluetooth things (both dongles or integrated), when enumerating serial devices, these dongles scan the air for remote serial devices. Hence, the IDE stays stuck, waiting for RXTX serial device enumeration to end. This issue has been acknowledged a lot of times, see for example [#1375][1], [#532][2], [#200][3] and [#143][4]

As far as I understand, this issue does not affect linux or mac because of the different way the scan occurs. On linux it's a plain filtered file listing of `/dev`. Similarly it's on mac. On windows, it uses native API calls.

Some fixes are available in the 1.5 series but I suggest switching to the latest [1.5.6 release][5] as RXTX was replaced by [JSSC][6], a more modern and simpler library.

  [1]: https://github.com/arduino/Arduino/issues/1375
  [2]: https://github.com/arduino/Arduino/issues/532
  [3]: https://github.com/arduino/Arduino/issues/200
  [4]: https://github.com/arduino/Arduino/issues/143
  [5]: http://arduino.cc/en/Main/Software#toc3
  [6]: https://code.google.com/p/java-simple-serial-connector/


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

Quote from the official [troubleshooting guide][1]:

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

  [1]: http://arduino.cc/de/Guide/Troubleshooting#toc14


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


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


message:
How do I erase the memory of the Arduino Uno?

I'm just a tinkerer learning Arduino with my son and I was surprised that when I plugged the USB cord back in to the Arduino the program was still running and I thought to myself, "it's a good thing I didn't just blow anything up."

So, what's the normal way people call it a day with these things?  Do you usually load up the bare-bones do nothing sketch or just unplug everything?

body:
When booted, the Arduino will run whatever program was put on it last. Solution: Don't turn it on if you don't want it to run.

When out of the box, the Arduino usually runs the Blink program. So you can just load that and call it a day if you want to "reset" it.

Or have a loop program with a sleep command.

If you've been messing with the USB bootloader via the icsp pins, this isn't enough though, you'll need to reinstall the bootloader. But if you've been uploading programs via usb or directly using a programmer, there is no issue with uploading Blink or some other dummy program to reset it.


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

- Upload the Bare Minimum sketch found in File ->  Examples -> Basic in the [tag:Arduino-IDE]
- Upload a sketch with a large delay in loop.

    #include <limits.h>

    void setup()
    {}

    void loop()
    {
      delay(ULONG_MAX);
    }

- Upload a sketch with a [call to `exit()` from `setup()`](https://arduino.stackexchange.com/q/188/65) (*Thanks @Peter!*)

    void setup()
    {
       exit(0);
    }

    void loop()
    {}

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


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


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

---

### Solution 1. Load the new code first.

A simple and safe technique is to load the new code that you are working on today **before** you plug any hardware in. Now you know what the code does, what pins it uses, and you then plug the hardware in afterwards (preferably turning the Arduino off first by unplugging it).

Then when you reconnect power, it runs the sketch you uploaded, you have your hardware connected and all should be well.

---

### Solution 2. Load a "do nothing" sketch.

You can upload this short sketch:

    int main () { }

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

---

### Safety first

A good rule is to not plug or unplug hardware (eg. LEDs, switches, motors) with the power applied. If you get distracted and plug into the wrong socket on the board you might immediately damage either what you are connected, or the Arduino, or both.

With the power off, you can then do a last-minute check that everything is connected to the right place, you have your polarities correct, and so on.

Also make sure you don't have static electricity on your body, particularly if you are wearing a jumper or something fluffy, or are sitting on carpet.

Personally I always reach over and touch some metal part nearby to "ground" myself, before reaching for the Arduino. An example is the metal case of a PC, a headphone socket, or something like that.

If, after connecting power to the Arduino (eg. by the USB cable) you do not immediately see the power LED come on, disconnect the power immediately! You may have shorted something out, and the less time you do that for, the better.


body:
In the Arduino IDE, go to examples, select Eeprom, select eeprom clear and then upload the sketch.

When it is the LED on pin 13 will turn on, you are done.

NB. This may take some time depending on the size of the EEPROM in the Arduino.


body:
My biggest concern when this happens is I've usually wired the Arduino for my new project and I'm plugging in the USB for the initial download of the new sketch. I worry, having no idea what the previous program is going to try, being connected to totally different hardware.

So far nothing bad has happened and I don't think I'll adopt burning BLINK each time I put one of my Arduinos back in the bin. It's probably just a matter of time though.


message:
Can you fry an arduino with nothing plugged in to it?

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

body:
Arduinos are far from bulletproof but with nothing connected (apart from a power source of course) I doubt it will come to harm. If in doubt, upload Blink to it.

There are rugged Arduino-compatibles. One of them has a rather [obvious name](http://ruggedcircuits.com/html/ruggeduino.html)


body:
It's generally a good idea not to try to take input from a pin configured as `pinMode(OUTPUT)` and vice versa. In addition, I prefer not to take input from tristated pins. Both of these cases are harmless, but it's good practice not to do so, especially since they _can_ cause issues when coupled with some hardware.

In general, Arduinos are protected from software issues. You can't burnout an Arduino with just faulty software.

There are, however, [many ways to fry an Arduino via hardware.][1]

  [1]: https://electronics.stackexchange.com/a/67151/8144


body:
**100% certain? No. 99.9999[Repeating]%? Yes**

Here's a couple problems you could run into:

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

The second to last one is the one you really have to worry about. I have seen previous discussions about destroying a board with a sketch, but nothing has been suggested.

Lastly, there a chance you can damage it with setting the fuses on the chip(s) on the board.


body:
Although the controllers on an Arduino are pretty well protected, they can still be damaged by ESD (Electro Static Discharge). The same effect that makes a crispy sound when you pull off your woolen sweater in the winter, or after walking with rubber shoes on a carpet and you touch someone else or a metal and grounded object and you feel a pick. Static electricity can damage the controller. It may get completely broken, or it may function 'most of the time' or lifetime may be shortened.

An Arduino is also easily killed with an piezo gas lighter, just make the spark near the copper traces that feed directly in the controller. This is largely the same effect as above.

Again, the controllers themselves are pretty well protected, don't worry too much about them. But with kids running around (on their rubber shoes) better make sure they don't accidentally draw a spark from their little finger to your Arduino. The protective metallic bag is best, but putting it away in a cupboard or box should do the trick equally well.

As a general rule of thumb, the faster the electronics, the more sensitive it is for ESD. A Due is probably more sensitive than a UNO or a MEGA. But with normal, avoiding static electricity, use you should be OK.


message:
How can I transmit data to/from arduino from up to ~750 ft away?

I am working on a design project for school (non-capstone non-electrical engineering project) where we are building a system to remotely control a winch on a boat that will lower an [independently operating meter][1] to specified depths using a pressure transducer (controlled from the shore).

My current idea is to have an arduino collecting data from the pressure transducer while being connected to the winch (adjusting it up/down as needed, based on the desired inputted depth). The arduino would then be connected to the a Raspberry Pi B via USB. The Raspberry Pi would then communicate via wifi USB adapter to a router @ 2.5 GHz 802.11n on the shore, which would then communicate with the laptop on the shore. The important thing is that the laptop on the shore will be recording data as well as changing the input depth for the arduino.

Arduino <==> Raspberry Pi <==> Router <==> Laptop on shore

I saw [this information][2] talking about connecting to an arduino via wifi, but I was unable to determine the potential range.

A [related project][3] using a boat that uses the Xbee shield.

Once concern is that we will not be able to specifically point any antenna on the boat back to shore, so we are looking for a non-direction-oriented solution.

I was wondering what potential ways I could communicate back to the shore to control the winch depth (output display on shore showing depth, then being able to change the depth from shore). Furthermore, I was wondering if my setup would be feasible and what your suggestions might be.

Thanks!

  [1]: http://www.hydroscientificwest.com/cms/upload_pic/resize_1348258228.jpg
  [3]: http://abersailbot.co.uk/about-the-boat/

body:
There are a number of considerations that need to be made when considering any wireless communication solution over long distances and over water.

WiFi is capable of working over long distances especially with higher power cards ([1W ones are now readily available][1]) and directional antenna (anything from [3dBi][2] to [30dBi][3] of gain). There are advantages and disadvantages to using WiFi like this for your purposes:

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

If you do want to go with WiFi, Ubiquiti make some neat products like the [Nanostation][4] that allow long range connections to be set-up over long ranges.

Personally I would stay away from 2.4GHz near water, and go with one of the other ISM bands. Depending on your location, this could mean 315MHz 433MHz, 868MHz, or 915MHz. It depends which region of the world you are in which ones you are allowed to use.

These lower frequencies are suited to longer ranges and penetrating object and water. There are a lot of different solutions in this space, all of which have ups and downs.

The [Hope RFM12B][5] is a very popular small RF board that has several easy to use libraries available - I use [Jeelib][6] personally. These are just capable of the 750ft range you require. They are available in all most ISM bands, and personally I have found the 868MHz best outdoors, whilst the 434MHz is better indoors.

The newer [Hope RFM69W][7] is a similar board but with more functionality and more power. It has 13dBm (20mW) of power vs 0dBm (1mW) of power on the RFM12B. I have been seeing an increase in range of ~50-100% with these boards.

The [RFM69HW][8] is a high power version has 20dBm (100mW) of power. I haven't range tested this, but would expect up to 3-4 times the range of an RFM12B.

Ciseco, a UK company, also make a series of boards that use CC1110 chips as transceivers. These are in an XBee like form. One of their boards, [the ARF][9], has a power amplifier. These have 26dBm output power (400mW) and in a brief test in a built up area, I have seen a range of about 2km.

It's important to note that these are transceivers so that they can send and receive, which means you can acknowledge if packets have been received.

There are boards like the [nRF2401L][10] which use 2.4GHz, but use a much lighter weight protocol than WiFi so work better on marginal ranges. They are dirt cheap (~£2). They have the same disadvantage of water impacting range.

I don't like Xbee at all. The boards are overpriced and I find the range isn't great even with the higher powered modules.

You could also "roll your own" and use simple 434/868/915MHz on-off-keyed (OOK) [transmitter][11]/[receivers][12]. Protocol design isn't easy though, and you lose a lot of hidden functionality that the more advanced boards have.

  [1]: https://www.google.co.uk/search?client=safari&rls=en&q=Alfa AWUS036H 1000mW&ie=UTF-8&oe=UTF-8&gws_rd=cr&ei=lf0OU_ubJsGM0AW_1oGACw
  [2]: http://uk.tp-link.com/products/details/?categoryid=2473&model=TL-ANT2403N
  [3]: http://uk.tp-link.com/products/details/?categoryid=2474&model=TL-ANT5830B
  [4]: http://www.ubnt.com/nanostation
  [5]: https://www.sparkfun.com/products/9582
  [6]: https://github.com/jcw/jeelib
  [7]: http://www.hoperf.com/rf/fsk_module/RFM69W.htm
  [8]: http://www.hoperf.com/rf/fsk_module/RFM69HW.htm
  [9]: http://shop.ciseco.co.uk/arf-high-power-radio-transceiver/
  [10]: http://playground.arduino.cc/InterfacingWithHardware/Nrf2401
  [11]: http://www.coolcomponents.co.uk/rf-link-transmitter-434mhz-781.html
  [12]: http://www.coolcomponents.co.uk/rf-link-receiver-4800bps-434mhz.html


message:
How do I burn the bootloader?

I was instructed to "burn the bootloader" to my Arduino to fix an error I was getting. How can I do this? (And what exactly is the bootloader?)

body:
The bootloader is a small program that is (almost) always on an Arduino. It manages uploading and starting the sketches you make, and blinks the pin 13 LED whenever the board resets.

----------

To burn the bootloader:

 1. Obtain an AVR ISP, [USBtinyISP][2], [ParallelProgrammer][3], or similar; or use [another Arduino board][4]. This will be your ISP.
 2. Unless otherwise instructed, connect the ISP to the ICSP pins on your board.
 3. Power your board with either a USB cable or an external power supply.
 4. Open up the Arduino IDE.
 5. Make sure you selected the correct board that you are burning to at `Tools ► Board ►` in the IDE. Double-check this even if you could upload programs correctly; uploading doesn't always require the right board.
 6. Select the appropriate programmer at `Tools ► Programmer ►`.
 7. Click `Tools ► Burn Bootloader`, and wait. It shouldn't take more than a minute, and often takes only a few seconds.

----------

Sources:

 - http://arduino.cc/en/Hacking/Bootloader
 - http://arduino.cc/en/Guide/Environment

  [1]: http://www.atmel.com/tools/MATUREAVRISP.aspx
  [2]: http://learn.adafruit.com/usbtinyisp
  [3]: http://arduino.cc/en/Hacking/ParallelProgrammer
  [4]: http://arduino.cc/en/Tutorial/ArduinoISP


body:
### What is a bootloader?

> And what exactly is the bootloader?

The bootloader is a small piece of code residing in the "high" part of program memory. Normally it is not erased when you upload new sketches. Its purpose it to be activated immediately after a reset (the fuses are configured to commence code at the bootloader address rather than address 0x0000). The bootloader will wait a short time (such as one second) to see if "programming" data is arriving on the serial port.

* If so, it reads that data, and decodes it to reprogram the rest of the flash memory. Working in conjunction with the uploading program (normally avrdude) the new sketch is sent via the serial port. The bootloader erases pages of flash memory, and replaces them with the new code. Once done, it executes the new code.

* If no instructions arrive, the bootloader jumps to address 0x0000 to execute the existing sketch on the board.

---

### How to replace the bootloader

An alternative method to program a bootloader is to use a sketch I wrote a while ago which runs on a:

* Uno (or similar, such as Duemilanove)
* Leonardo
* Mega2560

The "programming" board runs the sketch which has bootloaders for a number of boards hard-coded into it. You connect the programming board to the target board (the board wanting the bootloader) with 6 hook-up wires as shown.

![Bootloader programmer for Uno][1]

That particular photo illustrates one Uno programming another one.

You run the sketch (operating via the Serial Monitor to give it commands). First it identifies the target chip:

    Atmega chip programmer.
    Written by Nick Gammon.
    Entered programming mode OK.
    Signature = 0x1E 0x95 0x0F
    Processor = ATmega328P
    Flash memory size = 32768 bytes.
    LFuse = 0xFF
    HFuse = 0xDE
    EFuse = 0xFD
    Lock byte = 0xCF
    Bootloader address = 0x7E00
    Bootloader length = 512 bytes.
    Type 'L' to use Lilypad (8 MHz) loader, or 'U' for Uno (16 MHz) loader ...
    Type 'G' to program the chip with the bootloader ...

The you  press **G** to program it.

    Erasing chip ...
    Writing bootloader ...
    Committing page starting at 0x7E00
    Committing page starting at 0x7E80
    Committing page starting at 0x7F00
    Committing page starting at 0x7F80
    Written.
    Verifying ...
    No errors found.
    Writing fuses ...
    LFuse = 0xFF
    HFuse = 0xDE
    EFuse = 0xFD
    Lock byte = 0xCF
    Done.
    Type 'C' when ready to continue with another chip ...

For a Uno this takes one second. To program a Mega2560 takes 3 seconds.

Detailed instructions at [Atmega bootloader programmer](http://www.gammon.com.au/bootloader)

Code can be downloaded from [Github: nickgammon/arduino_sketches
](https://github.com/nickgammon/arduino_sketches)

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


message:
How do I debug on-chip with Arduino?

Though an emulator is quite useful for debugging code that has no side effects, most real-world applications include some circuitry besides the Arduino. If a microcontroller on an Arduino had a JTAG interface, it would be pretty straight-forward, but what if it's e.g. an Arduino Uno?

body:
The Arduino Uno uses the Atmel Atmega328p microcontroller, which only has one debug option, DebugWire.  There are a few tools that can work with it, but the least expensive and most commonly available is the [AVR Dragon][1].

You can use AVR Studio 6 for this.  You can use the `.elf` file file produced during the Arduino build process directly, but setting up the debugger is a little easier if you port the Arduino program to the AVR Studio.  It's not difficult, but there are a lot of little pieces to deal with.  There are guides online to help you through this.

  [1]: http://www.atmel.com/tools/AVRDRAGON.aspx


body:
This might not be right for you, but the [Visual Micro][1] plugin for Atmel Studio and Visual Studio has a [USB debugger][2] which only uses Arduino code.

In the background the debugger uses Serial which might affect some time-sensitive applications.

![Enter image description here][3]

  [1]: http://www.visualmicro.com/
  [2]: http://www.visualmicro.com/page/Debugging-for-Arduino.aspx
  [3]: https://i.stack.imgur.com/6Mqkn.png


message:
Arduino as USB HID

Is it possible to build a HID device (like a keyboard) using an Arduino uno?

At the time being, I have button inputs on the Arduino giving outputs on the serial line. So, how can I transform my current firmware into something that can behave like a HID keyboard?

 - Shall I write a new window device driver?
 - Shall I create a software layer that could take my serial data and have windows read it as HID input?
 - Is there any better way to achieve this, if it is possible at all?

body:
> Is it possible to build a HID device (like a keyboard) using an Arduino uno?

yes it is! And there's a great tutorial on how to do that over [here][1]

> At the time being, I have button inputs on the Arduino giving outputs on the
> serial line. So, how can I transform my current firmware into something that
> can behave like a HID keyboard?

As the tutorial shows you, you need to transform your firmware code so instead of
printing the events, you actually trigger events. What you need to do, is add to your
code:

    void triggerKey(uint8_t mod, uint8_t chr) {
        uint8_t buf[8] = {mod, chr, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
        // press key
        Serial.write(buf, 8);
        // emulate key press delay
        delay(10);
        buf[1] = 0x00;
        // release key
        Serial.write(buf, 8);
    }

What you're doing here, is send from your main Arduino microcontroller events over
the serial line to the smaller microcontroller that handles USB communication. That
microcontroller will take those key "buffers" and transfer them as USB HID Keyboard
key presses over USB.

Beware that the key character (`chr` in the code here), is actually a keycode sent
over USB that gets interpreted by your USB HID driver, which then translates it into
a real character using the current layout you've setup for your keyboard.

The `mod` character is one of the modifier keys you have on the keyboard (shift,
control, alt...), `0x00` being no modifier.

>  - Shall I write a new window device driver?

No, you don't need! With the DFU upgrade, your arduino will be seen as a USB keyboard
by windows.

>  - Shall I create a software layer that could take my serial data and have windows read it as HID input?

You neither need to do that, and it's actually a very bad idea for many reasons:

 - your solution would not be portable, and thus you'd need to hack something for every platform you may use,
 - your solution would imply a lot of new code ; the more code one write, the more bugs is likely to be in your system,
 - your solution would be really hackish, as it would behave as a device driver (i.e. *kernel land*) taking input from
   a user program (i.e. *user land*) and is likely to not work, be a hell to debug, and prone for security issues...
   If that's even possible to do!

> I'm using an Uno, but I'll look at what you posted because last time we considered the DFU update but we're kinda scared of bricking stuff

Finally you're having concerns, in a comment, about bricking your arduino. Please
believe me and the author of the [article][1] that you **cannot** brick your arduino
doing a firmware flash:

*NOTE: There is no chance of ‘bricking’ the device using this method. The Arduino bootloader firmware can always be updated using the DFU protocol!*

In case something gets really badly wrong, and you get a bootloader corruption in the
little AVR (atmega8u2), you still can reflash it [using another arduino][2] or an
[atmel programmer][3] using the 6 pins next to the USB plug.

In the end, know that the **only** way to brick an AVR, thus an Arduino as well, is
to play with the fuses and reset the programming fuses. And even then, you may use
[HVSP][4] to save your device, though it's often less trouble to just take a new chip.

[1]:http://mitchtech.net/arduino-usb-hid-keyboard
[2]:http://arduino.cc/en/Tutorial/ArduinoISP
[3]:http://www.atmel.com/tools/avrispmkii.aspx
[4]:http://microtherion.github.io/ScratchMonkey/HVSP.html


body: I created a project that fully replaces the Arduino Bootloader. You are able to upload sketches and use it as HID. See Project HID on Github: https://github.com/NicoHood/HID


message:
Combining Strings into a datestamp

I'm creating a weather station / environmental datalogger and am saving my data to a SD card Breakout. The SD card works fine but I would like to name the files I am saving on it after the date when the readings were taken.I've tryed multiple things but I can't work out how to combine the date from my RTC and put them in a file name. I've tryed this:

    dataFile = SD.open(String(now.day()) + "-" + String(now.month()) + "-" + String(now.year()) + ".csv",FILE_WRITE);
But this gives me an error -

    char dateName[13] = {String(now.day()) + "-" + String(now.month()) + "-" + String(now.year()) + ".csv"};
    dataFile = SD.open(dateName,FILE_WRITE);

But this gives me this error:

     cannot convert 'StringSumHelper' to 'char' in initialization

Help! How do I do this?

body:
*EDIT: As noted by Klaus Warzecha, the SD library may only support 8.3 format filenames (i.e. 8 characters for the name, 3 characters for the extension). The solution may in fact be to ensure that the years is only 2 digits, resulting in names like: `20-12-14.csv`*

---

From what I can see in the SD library code, the `open()` method isn't designed to accept a `String` object as a parameter. It only wants a plain old [C-style string][1] (which means a `char` array). That explains why your first example doesn't work -- it's trying to pass a `String` object.

The second example unfortunately is invalid C++. You simply can't initialise an array like that. What you want to do instead is to build the `String` object, then extract the characters out using `String::toCharArray()`.

Something like this should work:

    String filename = String(now.day()) + "-" + String(now.month()) + "-" + String(now.year()) + ".csv";
    char str[16] = {0};
    filename.toCharArray(str, 16);
    dataFile = SD.open(str, FILE_WRITE);

I'm not sure what your `now.year()` returns; i.e. if that's a 2 digit or 4 digit year. I've assumed 4 digits, so I've made the `char` array big enough for 15 characters in total, plus an extra null terminator (which is essential for C-style strings).

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


body:
In your second case, you need to break the initialization into two lines and use [toCharArray()][1] as shown:

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

    char dateName[13];
    String(String(now.day()) + "-" + String(now.month()) + "-" + String(now.year()) + ".csv").toCharArray(dateName, 13);

Then, you can move ahead with opening the file.

The problem you are seeing is quite literally what the error message says. An initialization of a character array requires a character array. It cannot be initialised with a string object.

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


body:
Is this based on the [SDFat][1] library?

Then you have to live with short 8.3 filenames for the moment.

[1]:http://code.google.com/p/sdfatlib/


body:
  //////////////////////////////////////////////////////////////

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

    char str[16] = {0};

    filename.toCharArray(str, 16);

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

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


body:
Well:

      char buffer[15];
      snprintf(buffer, sizeof(buffer), "d-d-d.csv", now.day(), now.month(), now.year());

After `snprintf` call, `buffer` contains the name of the file.

This solution use constant fixed space in RAM (just 15 bytes for buffer), while all others solutions demands tons of RAM for creating multiple String objects.

And it's faster, because it only do the format part, minus all creations, conversions, and deletion using String.

Finally, generated names are always the same length, from 1-1-2018 thru 31-12-2018.

Don't use String with Arduino.


message:
Best way to determine if a 5 gallon water jug is getting empty

I have an espresso machine that gets its water from one of those 5 gallon blue water bottles (I would plumb it, but our water here is WAAAAY too hard).

If I ever accidentally let the bottle run out of water, the rotary pump in the espresso machine will be ruined, which would be a costly mistake.

I know that I can install some sort of magnetic float sensor inside the water bottle, but since I have to change it out once every few weeks, having another thing inside the bottle would make changing it out harder, and microbial contamination more likely.  The pump that pumps water out of the bottle forms a tight seal at the lid, and anything running under it or through it would compromise that seal.

Is there something I could use to detect if the water level is low from the outside of the bottle?  Like a laser sensor?

body:
I think you want a ["liquid level switch"][2], possibly also known as a "fluid switch" ... I realize this may not satisfy your requirements, but this is one way to solve the problem for >$10. I would probably hack something together that would put this sensor inline to the bottle. it's probably too hacky, but you could have a disc of plywood the same diameter as the water bottle, with a pipe fitting in the middle where you could mount the switch, so that the water bottle routes water through it so that when it runs low, it would trigger the switch before it runs to the pump.

![inline liquid level switch][1]

  [1]: https://i.stack.imgur.com/Y2s79.png
  [2]: http://www.mouser.com/ProductDetail/Hamlin/59630-1-T-02-A/?qs=sGAEpiMZZMun2xR%2b%2bFUzeBXr8YNXGDFf8m4HoboDx0M=


body: It seems to me that if you have pumped out 4.9 gallons you know the jug is close to empty. If an inline flow meter between the pump and the espessso maker is out due to water contact, then maybe you know that an espresso shot takes x amount of water, and once one has called for y shots (and calculated x times y) one is in the danger zone of running out of water?


body:
**Using a Force Sensor to Measure a Quantity of Water**

To satisfy your requirement of having the sensor on the exterior of the water container, I would recommend using a force sensor to weigh the bottle at set intervals. A force sensor, such as the FlexiForce A401, is a type of resistor that changes resistance in response to the amount of force applied. While not as accurate as a scale, it should provide enough accuracy (+-3% according to the [datasheet][1]) for the application described.

The basic procedure would be to hook up the force sensor to the Arduino and first measure the resistance with an empty bottle, then measure again with a full bottle. This will give you an idea of the force that your specific platform is actually applying to the sensor, and you can then fine tune the voltage (as per the datasheet) for your installation.

A basic tutorial using a similar force sensor with an Arduino can be found [here][2].

**Other Possibilities**

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

  [1]: http://dlnmh9ip6v2uc.cloudfront.net/datasheets/Sensors/Pressure/A401-force-sensor.pdf
  [2]: http://bildr.org/2012/11/flexiforce-arduino/
  [3]: http://www.fluidswitch.com/pages/Optical-Liquid-Level-Sensors.htm
  [4]: http://www.cigrjournal.org/index.php/Ejounral/article/viewFile/2343/1823


body:
Another option is to measure the current going into the pump; when it runs dry, the current goes up, which generates the heat that fries the pump.

Or measure the temperature on the pump, but measuring the current will detect the beginning of the pump's meltdown, while the temperature may only detect the middle or end of the meltdown.  :-(

Or install a current limiter or breaker inline with the pump, just in case everything else fails.  :-)


body:
Honestly - you're overthinking this.

A dipstick or a float would be all you need.  Once the water level drops below your minimum, the float moves down with the water level and pulls a switch or allows a LDR to see through a hole.  Then do something like turn on a light.

Less is more.


body:
Whenever light follows a path that takes it from one material to the next, it makes a sharp turn. However, the angle of deviation is different based on the characteristics of the materials.

You can use this principle.

Set a LED on the level that you want to be your lowest. When the water is full, its light will follow a certain path across the container and reach its light sensor. When the water gets bellow the level, it will miss it (or you could set up a second sensor if you really wanted to).

Based on this info, you can know when the water gets too low. Just take appropriate action.

Watch out on the recommendation to measure the water used. This could be dangerous. You may have a leakage (either now or later) or somebody might tip the machine and spill some water. In either case your water level would be lower than the level you calculate, which would certainly result in your espresso machine be ruined.