sender: user

message:
Is an Arduino capable of running 24/7?

I'm making a simple Arduino web server and I want to keep it turned on all the time. So it must endure to stay working continuously.

I'm using an Arduino Uno with a Ethernet Shield.
It's powered with a simple outlet power supply 5V @ 1A.

My Questions:

 - Will I have any problems leaving the Arduino turned on all the time?
 - Is there some other Arduino board better recommended for this?
 - Are there any precautions that I need to heed regarding this?

sender: assistant

body:
You shouldn't have any issues keeping it on all the time, however, some thing to consider is any counters you may have, like the use of `millis()`.

From the [Arduino docs on millis][1]:

> This number will overflow (go back to zero), after approximately 50 days.

So for projects that are on for long periods of time, you may not see an issue immediately but something like this could pop up and cause errors down the road.

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


body:
A couple of things to keep in mind (outside of @Sachleen's mention of `millis()`):

- Like any electronics, heat can be disruptive. The micro-controller itself isn't likely going to be a huge issue from the perspective of heat, but other components like the power supply might cause issues.

- If your code uses [`EEPROM.write()`](http://arduino.cc/en/Reference/EEPROMWrite), be aware that the EEPROM in your Uno's ATmega328P is only rated for 100,000 writes.


body:
Running the Arduino 24/7 Shouldn't be a problem.

But be sure that you have a case that allows for ventilation and you keep it in a well ventilated area. Just like computers, if you do not keep them in an environment that can keep them cool, they will not stay cool.

Server load also should be a thing to consider, the more load there is on the server the more processing it has to do, and the more heat it will generate.


body:
Arduinos can run without issues for a really long time, though depending on local conditions and the intensity of computation you may have to attach heat sinks.

In addition, keep it well ventilated.

It depends on the program being used, too, if your server is serving a page every now and then, it shouldn't be an issue, but if you expect constant traffic then the Arduino may heat up quickly.

You'll also want to ensure stability of power supply, when running benchtop experiments with an Arduino this isn't a big issue, bit it can become an issue if transforming power from the mains for a permanent fixture.


body: Keep in mind that the flash and EEPROM have limited lifetimes (about 10,000 and 100,000 write cycles respectively) so if you're doing a lot of writing to those, they may become corrupted. In a test I did, an external EEPROM took about 3 days to start becoming corrupted.


body:
I've never ran an Arduino for that long, but there shouldn't be a problem. One thing to watch out for is the input voltage.

While an Arduino is capable of handling 7-20v as input anything over 12v can overheat after longer periods of time and cause board damage. As a quick recommendation to avoid any overheating of the Arduino I would keep the voltage as close to 7v as possible.


body: I'd like to mention an issue that doesn't come up very often but can cause long term issues. Memory Leaks and Heap Fragmentation. Almost nobody mallocs in embedded stuff, but if you do, do it right.


body:
I built a simple power monitor with my first Arduino. It is powered via USB from a web-server that in turn is powered via a quite substantial battery backup (which  does not have notification abilities).

It is also connected to a mobile phone charger plugged into a non-UPS power socket.

So if the power dies the Arduino sends a message to a little program running on the server. The server program in turn sends me an email notification.

It was installed in late September 2013, on the 23rd March 2014 - I got my first email!

So I have not seen a problem (it does not use millis() ) but it does sample the power every 5 seconds.


body: We've been running our Arduino-based RFID access system at Bloominglabs Hackerspace in Bloomington IN since late 2011 and aside from a couple power outages and software updates it runs around the clock, no problem. More recently we added a networked thermostat, same deal - it's running round the clock.


body:
Is an Arduino capable of running 24/7?

This is a reliability question. In reliability, there are a lots of things to consider.

 1. The software. There are more robust softwares. There are less
    robust softwares. For instance, for critical applications, dynamic
    memory allocation is discouraged, as it might lead to memory
    fragmentation. Unfortunately, Arduino heavily relies on dynamic
    memory allocation. This problem is exacerbated as most of the
    Arduino board have a very limited RAM.
 2. The libraries. Many Arduino libraries do have bugs (even those
    built-in in the Arduino package, as simple as WString!). In normal
    operation, such bugs may not appear at all. However, you can't hope
    that "everything will be fine" and that "the user" (or subsystem)
    will act as predicted. Libraries could also have their limits (i.e.
    not properly bugs). For instance, many users already cited the
    millis() function, which resets after 50 days. This, if not handled
    correctly, might lead to severe bugs.
 3. The reliability of the hardware (not even talking about cheap
    Arduino clones...).  Here a new class of subquestions opens. I will
    cite only a very limited subset.
    - Are the Arduino Boards designed for reliability? (e.g. what's the
    reliability of the used capacitors? and other components?)
    - Robustness against EMI ? I wouldn't rely on that: most of Arduino boards have just two layers, and lack of a proper ground/power plane.
    - EEPROM (this is both software and hardware). Is your software using the EEPROM? Is implementing some algorithm to prevent cycling (repeated write/erase on the same cells)?
    - Flash memory retention time. Retention time decreases with temperature, and also with the number of programming cycles.
    - Ionizing radiation. Yes, even if the probability is VERY low, at least at sea level, the probability of radiation-induced single-event upset is not zero, and it adequate countermeasures should be taken (especially taken into consideration that the RAM has no hardware error detection) in critical applications.
    - The quality of the power supply.
    - The operating environment. A 25-°C controlled environment, or in a black box over the roof (70°C under the sun in summer)? The higher the temperature, the faster all the degradation mechanisms.
   - ...

Still, you should not be surprised if your arduino will work flawlessy for many years. But this does not ensure that every arduino will.

Some countermeasures will increase the reliability:

 - Use the watchdog: it's better to reset a non responsive system, than
   having a stuck/misbehaving one.
 - Avoid using any library that uses memory allocation.
 - Implement (if you use the EEPROM) an algorithm to preserve it!
 - Good power supply.
 - Avoid harsh evironments (high temperature, high humidity, large and continuous thermal cycles, etc).


body:
It certainly can run 24/7. I either use 5V to the 5V pin, or a 7808 to the Vin pin to offload the vreg. Ideally it would be 6.5V, but I don’t have such supplies. You may want a decoupler cap on 5V though, to soak any minor spikes when powering up your supply.

Any hardware attached which runs at 5V, I feed with a 7805. You can use LM317s or LM350s in lieu of 78XXs, but you’ll need a few resistors for those, perhaps trimpots.


message:
How to get HTTPS on Arduino?

Put plainly: is there a way to get an HTTPS connection on the Arduino?

 I have been looking in to it, and I have found it is impossible with the standard library and the Ethernet shield, but is there a custom library that can do it?

What about a coprocessor, i.e. like the WiFi shield has? Anyone know if the Arduino yún has ssl?

body:
I don't think it is possible due to the size and complexity of the SSL Library, because the Arduino would most likely be under powered. That being said you could make the requests to a regular server and use some sort of PHP script to proxy the request to the HTTPS server. Not sure how well it would work though.

You may be interested into looking at [this][1].

  [1]: http://www.abdulqabiz.com/blog/archives/2007/05/31/php-proxy-script-for-cross-domain-requests/


body:
MCUs mounted on Arduinos don't have the horse power to handle https connections.

Yún does handle https **on the linux side**, with software like curl, wget or python. Your sketch can just delegate the task to the linux side.

While curl works fine, despite having python preinstalled, you need to manually install python-openssl, since it's not available out of the box (due to disk space constraints)


body:
As Federico Fissore says above, the Yún can only handle HTTPS (or SSL, whatever you want to call it) on the Linux side of the Yún.

The first way to do it is using Python with Python OpenSSL. The way you do this is by issuing the following commands via SSH or YunSerialTerminal:

    opkg update
    opkg install python-openssl

`opkg update` will make sure the package list is up-to-date, and then `opkg install` installs Python OpenSSL. And then you can talk to the Arduino using Python. [This page on the Arduino website][1] should help you in using Python with Arduino.

You could also use `curl` with the `-k` option in your sketch. For example:

    Process process;
    process.runShellCommand("curl -k http://example.net");
    while(p.running()); // this waits for the command to be done before continuing

Also, if you want to download a file, you could use `wget`. This would require you to upgrade `wget` by again issuing these commands via SSH or YunSerialTerminal:

    opkg update
    opkg upgrade wget

And then you can just do this in your sketch:

    Process process;
    process.runShellCommand("wget http://example.net");
    while(p.running()); // this waits for the command to be done before continuing

  [1]: http://playground.arduino.cc/interfacing/python#.Uwki4_kiEw8


body:
I list this as an answer for the sake of having it linked here. It is not full https yet but he is working on it and it may be doable in the future
http://evothings.com/is-it-possible-to-secure-micro-controllers-used-within-iot/

here is a benchmark he did encrypting a message using a 1024 bit public key

    Arduino UNO       16Mhz AVR               ==> 12596 ms*   8504 ms#
    Arduino Leonardo  16Mhz AVR               ==> 12682 ms*   8563 ms#
    Arduino Mega      16Mhz AVR               ==> 12596 ms*   8504 ms#
    Arduino Due       84Mhz ARM               ==>  1032 ms*
    Arduino Yún       16Mhz AVR + 400Mhz MIPS ==>   707 ms*
    Intel Galileo     400Mhz x86              ==>   192 ms*

This is as far as he has gone with it but is in the process of setting up a test server to work on seeing how close to a full ssl/https implementation he can pull off.


body:
<sup>(Disclaimer: I'm actually the author of the evothings.com article)</sup>
The Arduino UNO is more than capable at doing TLS. I've just finished up a blog post series on the topic. I have a working example of an Arduino UNO doing elliptic curve cryptography (sect163r2) to exchange an AES-128 key for continued communication.

http://ardiri.com/blog/utls_defining_lightweight_security_for_iot_part_1
...
http://ardiri.com/blog/utls_defining_lightweight_security_for_iot_part_8

I took an alternative approach to trying to make a true HTTPS connection - instead, this is using the same protocols under the hood but using an insecure communication channel to do so. Pretty much TLS on HTTP.


body:
Using of WiFi shield can be a solution - it supports HTTPS.

https://www.arduino.cc/en/Reference/WiFi101


message:
What are (or how do I use) the power saving options of the Arduino to extend battery life?

For solar & battery powered projects, decreasing power consumption is a necessity.

I know a little bit about using a timer and interrupt to put the microcontroller into sleep when it isn't doing anything.

I have also read that you can disable some peripherals to further save power.

Here is a page explaining these: [Power Saving Techniques][1]

My question:

* What other techniques are there to save power?
* Are there any libraries that make using these AVR features easier?

  [1]: http://arduino720.wikispaces.com/Power+Saving+Techniques

body:
You could read through the 200-page datasheet, and then mess with some confusing bit shifts and registers, but I recommend this library: http://playground.arduino.cc/Code/Enerlib

Also, if you're using an Uno or any one with a usb-to-serial chip, you could disable that or remove it.


body:
*Note: I wanted to point out that, even though my answer was accepted, the reader (you) should really read Anindo's answer first if you really want to save energy with any Arduino board. Once you address those items in your design, then you should read my answer and worry about how to set the MCU into low power mode.*

Having said that, there are several techniques to make an Arduino save power. I'll list a few and then point you to a page that explains them all in more detail.

1. While the controller isn't doing anything important (between one read of a sensor and the next, for example), you can put the controller into one of the sleep modes below, with the command `set_sleep_mode (SLEEP_MODE_PWR_DOWN)`. Next to each mode is the approximate power consumption of each mode.

* SLEEP_MODE_IDLE: 15 mA
* SLEEP_MODE_ADC: 6.5 mA
* SLEEP_MODE_PWR_SAVE: 1.62 mA
* SLEEP_MODE_EXT_STANDBY: 1.62 mA
* SLEEP_MODE_STANDBY : 0.84 mA
* SLEEP_MODE_PWR_DOWN : 0.36 mA

1. Disable **brown-out detection** (the circuitry that turns off the controller when low voltage is detected).

1. Turn off ADC (analog to digita conversion)

1. Use the internal clock

Then, when you put the controller to sleep, you need to use one or more mechanisms below to wake up the controller and do something with it:

* Wake up with a signal

* Wake up with a timer

This is a summary I made from -

* [Nick Gammon's article: Power saving techniques for microprocessors](http://www.gammon.com.au/forum/?id=11497).

That article applies mostly to ATmega328P, but the technique applies to other Arduino compatible controllers as well. As TheDoctor said well, you will need to check the datashet to make sure your controller suports any of those techniques and how to do it more precisely.


body:
Realistically, the biggest power waster on an Arduino board is the linear voltage regulator on it.

 1. As long as the microcontroller on the board, the LEDs, or any other peripherals, draw current, the linear regulator wastes power equal to `difference between supply and board voltage` x `current drawn`.

    So, a first fix would be to disconnect the power indicator LED on the board, and not use any of the other LEDs as far as possible.
    Second, supply the board with as low a voltage as possible that is just sufficient to power the on-board regulator.

 2. On the original designs, the voltage regulators used do not boast low quiescent current. This means even with nothing drawing power within the board, the regulator itself wastes a fair bit of power all the time it is on.

    An easy fix is to replace the on-board regulator with an LDO (low drop-out linear regulator) rated for extremely low quiescent current. Parametric searches on various vendor sites will yield likely substitutes.

 3. Even with the above steps, the Arduino board does not provide a mechanism to set the LDO into low-power mode, if the LDO chosen supports this. Power efficient designs typically use a "sleep mode" pin on voltage regulators to save a fair bit of energy - not an option here.

Even with all possible power saving modes and tricks applied at the microcontroller level, the Arduino simply is not designed to be an ultra-low-power device out of the box. Having experimented with several non-trivial applications, I have found that the best that is realistically achievable is some 10% to 30% power saving depending on application, since the voltage regulator and the LEDs are going to consume the rest anyway.


body:
Once your project is working and you need to deploy to "production" environment, you can opt to replace the Arduino with a bare meta ATMega328 or any of the ATTiny family chips. This will get rid of all the power eaters on the Arduino board you don't need.
I found:

 - Arduino board of 9V block battery - 56 mA
 - ATTiny85 bare on 8 MHz without sleep modes etc - 10 mA
 - ATTiny85 bare on 8 MHz in sleep mode - 0.03 mA

**Some more information**

[Program an ATtiny with Arduino][1]

[ATTiny files for Arduino IDE][2]

 [1]: http://www.instructables.com/id/Program-an-ATtiny-with-Arduino/
 [2]: https://code.google.com/p/arduino-tiny/


message:
Installing a different firmware on Arduino

Is it possible to upgrade the firmware on an Arduino so that it can do more things such as change undervolting/ overvolting in order to provide more processing power. To do this you would have to most likely re flash the chip itself, so how would that be accomplished?

body:
Note the below chart, in regard to your under/over volting the device for different F_CPU, indicates the relationship. As a result you find most Arduino's run at 5V and a clock rate of 16MHz. While there are some 3.3V variants that run at 8MHz.

![Freq vs Vcc][1]

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

However, the core library provided with the IDE typically has specific #if's for both 8 and 16 MHz F_CPU speeds, not using a formula in most places.

Hence it is possible to do what you ask. However, you will find the core library limitations affecting. Tipping the cost vs benefit ratio, to that of the very intent. And then likely one would leave the Stock IDE and core libraries to a more makefile method.


body:
To answer the aspect of your question regarding the "firmware" on the ATmega328p MCU used in most of the Arduino boards:

There is no firmware on the ATmega at all aside from the bootloader. The programs you write are running *directly* on the hardware.

There are certain "fuse" settings which are set with a [ISP programmer][1]. However, there are only 24 of them (three bytes), and they largely relate to low-level configuration, and are not what I think you're asking:
![enter image description here][2]

There is also the [Bootloader][3], which is a small program that sits in a separate segment of the MCU's program memory and allows it to update itself at startup (which is how all arduinos are programmed). However, it only runs for a short period of time at startup, and is completely removed from memory after the MCU has jumped to the main program.

Lastly, there are auxiliary MCUs (ATmega16U2/8U2) on most arduino boards that are used as USB-serial interfaces, that *can* be updated to behave differently (e.g. emulate a keyboard/mouse), but again, this isn't actually a change to the core processor, so whether it counts as "installing a different firmware" depends on how you define the arduino.

Really, I'd strongly reccomend reading the [ATmega328P datasheet][4]. This is the documentation for the MCU that basically forms the "Arduino". It should address what seems to be misconceptions.

  [1]: http://store.atmel.com/PartDetail.aspx?q=p:10500054
  [2]: https://i.stack.imgur.com/wEPF9.png
  [3]: http://code.google.com/p/optiboot/
  [4]: http://www.atmel.com/Images/Atmel-8271-8-bit-AVR-Microcontroller-ATmega48A-48PA-88A-88PA-168A-168PA-328-328P_datasheet.pdf


message:
What does it take to compile Linux on Arduino, if at all possible?

Is it possible to run Linux on Arduino? If yes, what steps and limitations need to be considered? If not, what are the limitations that prevent this?

body:
Linux is a very complex operating system, but it may be able to fit on an Arduino. Things to consider:

* There is no current AVR port of the source code.
* You would have no graphics, instead access the terminal over UART.
* The filesystem driver would have to be rewritten to access internal flash or an external SD card.
* It would be _extremely_ slow! The ATmega328 would run at 16 MHz, or about 20 MHz max (overclocked). Most Linux machines run at a minimum of 400 MHz, and more with graphics.
* You would probably need some extra RAM, probably a good idea to use an ATmega2650 (the one in the Mega), which has 16 times the RAM of the Uno. You could also use a Due (6x as fast as the Uno, more RAM).
* You may have to write special USB drivers for OTG (on the Due) or MAX3421EE (Mega ADK, USB host shield).

In short, it would take _a lot_ of time and effort, and probably would be too slow for everyday use. If you really want Arduino Linux, check out the Yún.


body:
It just doesn't have enough RAM. You'd also need to teach it to boot from flash memory, which would involve rewriting the bootloader.

You can instead use an [Arduino Yun][1] or a [PCDuino][2]; while not "standard" Arduinos these support Arduino shields and run Linux.

Or there's always the [Raspberry Pi][3].

  [1]: http://arduino.cc/en/Main/ArduinoBoardYun?from=Main.ArduinoYUN
  [2]: http://www.pcduino.com/
  [3]: http://www.raspberrypi.org/


body:
The short answer is no.

Basically, you would need LOTS more ram then even the biggest ATmega has natively.

It *is* theoretically possible to add external hardware, and program the ATmega to emulate a more powerful CPU, and run linux on that. However, on a plain arduino, it is not possible.

It would be much more realistic to run linux on a Arduino Due, which is basically a AT91SAM3X8E CPU. However, you'd still need to add some additional SRAM and storage.

There are things like the Arduino Yun, but that is really a entirely separate linux module on the same PCB as a ATmega32U4, so I don't know if you can really count it as an arduino.

---

Possibly relevant: [What does it take to run embedded linux?](https://stackoverflow.com/questions/1522146/minimum-configuration-to-run-embedded-linux-on-an-arm-processor)


body:
There is a board called the [pcDuino][1] that can run multiple variants of Linux such as Debian, Ubuntu, Open WRT, LEDE, Raspian PIXEL (just to mention a few). This board is not a native Arduino, rather [Arduino AtHeart][2], and is made by [LinkSprite][3].
[![pcDuino][4]][4]

Arduino have a couple of boards that support running a variant of Linux called [Linino][5]:

 - The [Arduino Yún][6] is a microcontroller board based on the ATmega32u4 and the Atheros AR9331. The Atheros processor supports a Linux distribution based on OpenWrt named Linino OS. The board has built-in Ethernet and WiFi support, a USB-A port, micro-SD card slot, 20 digital input/output pins (7 of them can be used as PWM outputs and 12 as analog inputs), a 16 MHz crystal oscillator, a micro USB connection, an ICSP header, and 3 reset buttons.
 - The new [Arduino Tian][7] board is powered by Atmel’s SAMD21 MCU, featuring a 32-bit ARM Cortex® M0+ core and a Qualcomm Atheros AR9342, which is an highly integrated MIPS processor operating at up to 533MHz and feature-rich IEEE802.11n 2x2 2.4/5 GHz dual-band WiFi module. Qualcomm Atheros MIPS supports a Linux distribution, based on OpenWRT named Linino. The Arduino Tian has also a build in 4GB eMMC memory that will can be helpful to build your projects. It is possible to Switch ON/OFF the Linux port from the MCU to reduce the power consumption.
 - [Arduino Industrial 101][8] is an Evaluation board for Arduino 101 LGA module. The ATmega32u4 microcontroller is integrated in the baseboard. The module supports a Linux distribution based on OpenWRT named LininoOS. The board has built-in WiFi (IEEE 802.11b/g/n operations up to 150Mbps 1x1 2.4 GHz), 3 GPIOs (of which 2 can be used as PWM Outputs), 4 Analog Inputs, 1 USB, 1 Ethernet signal on pin headers and a built-in DC/DC converter. Check out the assembling guide and simply connect your board to a computer with a micro USB cable to get started.

  [1]: http://www.linksprite.com/linksprite-pcduino/
  [2]: https://blog.arduino.cc/category/arduino/arduinoatheart/
  [3]: http://www.linksprite.com/
  [4]: https://i.stack.imgur.com/S30q6.jpg
  [5]: http://www.linino.org/
  [6]: https://www.arduino.cc/en/Main/ArduinoBoardYun
  [7]: https://www.arduino.cc/en/Main/ArduinoBoardTian
  [8]: https://www.arduino.cc/en/Main/ArduinoBoardIndustrial101


body: This is several years old, but maybe more pertinent as Arduinos get more RAM and 32 bit ATMega AVRs, etc. There's an obvious problem notably not in the most popular answer here. The Arduino uses an AVR ***MICROCONTROLLER***, not a MICROPROCESSOR. This is a major reason why there is no port of linux. Microcontrollers are designed to perform a specific task, applications where the relationship of input and output is well defined. Microprocessors are designed to run a variety of apps on operating systems. Remember, from the beginning, Linux needed a memory management unit and could not run on 8088 or 286 PCs. Then there was μClinux, which originally targeted the Motorola DragonBall family of embedded 68k processors, for Palm Pilots. It was never particularly successful. You might have more success porting FreeDOS or even Minix than Linux, maybe something in assembler, but compiling an OS on a microcontroller is very impractical. Perhaps it's a challenging academic problem, but specifically counter to the purpose of using a microcontroller instead of a microprocessor.


message:
Yún boot from SD card

I have an Arduino Yún, and it only has 16mb flash onboard for the Linux. I was wondering of it is possible to put a bootloader on the flash that uses the sd card as a rootfs? i want to be able to do more projects on it than those that can fit in 16 MB flash.

body:
I am using Yun as well for my projects. I don't boot from SD card, but I store a lot of Python code there and it works for me. I've also seen this article that might be interesting for you. I haven't tried to do it on my Yun but I think it should work... This is example how to install node.js on the Yun (SD card), so in theory you could use the same approach for all additional software you want to run.

[http://linino.org/doku.php?id=wiki:nodejs][1]

  [1]: http://linino.org/doku.php?id=wiki:nodejs


body:
And the Arduino team finally figured it out:

http://blog.arduino.cc/2014/05/06/time-to-expand-your-yun-disk-space-and-install-node-js/


message:
"avrdude: stk500_getsync(): not in sync: resp=0x00," aka Some Dude Named Avr Won't Let Me Upload My Program

I made an awesome program the other day, and I wanted to upload it to my Arduino. After clicking the upload button, some mean dude named avr came along and stopped me, saying:

> avrdude: stk500_getsync(): not in sync: resp=0x00

_All_ I want to do is just upload my program, but avr won't let me. He's even unintelligible, so can someone tell me what the heck he's trying to say and how to get rid of him?

---

i.e.:

Whenever I try to upload a program to my Arduino, I get this error message:
> avrdude: stk500_getsync(): not in sync: resp=0x00

What does this mean, and how can I fix it?

body:
This is caused by a generic connection error between your computer and the Arduino, and can result from many different specific problems.

Here are some easy things that can often fix this error:

 - Disconnect and reconnect the USB cable.
 - Press the reset button on the board.
 - Restart the Arduino IDE.
 - Make sure you select the right board in `Tools ► Board ►`, e.g. If you are using the Duemilanove 328, select that instead of Duemilanove 128. The board should say what version it is on the microchip.
 - Make sure you selected the right port in `Tools ► Serial Port ►`. One way to figure out which port it is on is by following these steps:
 1. Disconnect the USB cable.
 2. Go to `Tools ► Serial Port ►` and see which ports are listed (e.g. COM4 COM5 COM14).
 3. Reconnect the USB cable.
 4. Go back to `Tools ► Serial Port ►`, and see which port appeared that wasn't there before.
 - Make sure digital pins 0 and 1 do not have any parts connected, including any shields.

If none of those work, you will want to try to isolate the issue by replacing things: try a different computer on the same arduino, try a different arduino on the same computer, and try using a different USB cable.

If the issue is with the computer:

 - Double-check all computer-related issues in the "easy fixes" list above.
 - Reinstall the IDE.
 - Reinstall the drivers.

If the issue is with the Arduino:

 - Double-check all board-related issues in the "easy fixes" list above.
 - Make sure the microcontroller is seated correctly.
 - You may need to [burn the bootloader][1].
 - Replace the microcontroller if you have another one handy nearby.
 - You may have bricked your Arduino. Sorry :(

  [1]: https://arduino.stackexchange.com/a/474/37


body:
If none of the above steps work, try reinstalling Avrdude and the avr-gcc compiler. I had to do this after my Mega started suffering from this.

If you installed Avrdude and avr-gcc separately, simply uninstall them. if not, you may have to reinstall the Arduino IDE. These steps will depend on your operating system.


body: Unfortunately, it can also mean that you burned your microcontroller. Were you doing anything dangerous right before you tried to upload a new sketch? Is the microcontroller still working, with its previously loaded sketch?


body:
I had the exact same problem. I tried installing the IDE in another laptop and uploaded the program from that laptop. Problem solved. Then I came back to my laptop, uninstalled the IDE and re-install it.. it started working.

However, I wasn't satisfied because I couldn't find the source of the problem... so I tried running everything again the same exact way... I found the problem but not sure if that can be the actual cause of it.

In my project, I needed to carry out serial communication between arduino and MATLAB (GUI). In order to see/verify the output(type) of MATLAB (GUI) serial data, I used HYPERTERMINAL and also VIRTUAL SERIAL PORT EMULATOR. I noticed that every time when when hyperterminal is running or VSPE is running while my serial monitor is on it screws up the uploading feature of the program. I'm not sure if it's because of the VSPE or HYPERTERMINAL, but reinstalling the IDE worked for me.


body: I've had the same message. Every time it has been solved by selecting the right port ie USB under the menu Tools then Ports. Its a simple step but I always forget. I'll unplug the Arduino to stop the current program, plug it in again to my computer to upload the new program and get the error, panic, curse, and only then, remember.


body:
For people using Linux Mint I found that by selecting the "TTY SO" port instead of the one labeled "Arduino" it would work (I can't tell you exactly because I don't have that computer in front of me right now).

Then the next time I used the Arduino I again got the same message so I switched back to the "Arduino" port and it has worked that way ever since.

I am not as technically knowledgeable as the rest of you guys so I have no idea why this works or what the problem was, but it worked which is all I care about.  Maybe this will be useful to someone.


body:
In my case I hadn't wired the RTS pin of the FTDI chip to a capacitor which went to the RST pin of the Arduino Pro Mini.  Once I installed this connection, I no longer got the error and I was able to upload code.

Nick Gammon explains this [in his forum][1].
I've added a picture of where/how the capacitor should be placed.
[![enter image description here][2]][2]

  [1]: http://www.gammon.com.au/breadboard
  [2]: https://i.stack.imgur.com/hDu1t.jpg


body:
I uninstalled the IDE and drivers etc, installed it all again, then I ran the Arduino IDE as an administrator and set to run compatibility as windows 7 (I'm currently using 10).

I also changed the programmer to AVR ISP (I don't think this matters, but I changed it anyway).

All is working again... hopefully, this can help someone else out too.


body: An unusual one but I've been swapping out the microcontrollers a lot and i got this error when one wasn't seated correctly.. i was able to burn a few times but i guess it slipped back out - a little push on the back of the ATMega328 fixed it!


body:
There is also the possibility of the the controller itself being placed the wrong way in the socket on the Arduino. This can be dangerous for the controller (which may get zapped) but, in my case, it only gave the out of sync error, preventing me from uploading code.

So just check if the notch on the IC is in the right direction (you can cross check with images of board online). The notch on the Uno's controller should point towards edge of board.


body:
I had this error come up too. It was the first time using a new Arduino Nano board after I had soldered on headers. Just tyring the Blink Sketch, nothing was connected to the board.

I found a tiny short of solder between the GROUND and RESET pins. I picked it off and then I could upload ok.

I suppose this might happen if you had the same short on a circuit somewhere.


body:
Just had this same error with a brand new Mini Pro.  Since the default blink program that came preloaded with most Arduino is running, I know that the unit is probably OK.

So I inspected the headers I just soldered one more time, and found that there was not enough solder on the TX0 pins.  After re-soldering every works.


body:
Another fix:

Change `Tools->Processor->Atmega 328P` to `Atmega 328P (Old Bootloader)`. Remind that the `Processor` option is only available when you select some specific Boards at `Tools>Board`.

This worked for my Arduino Nano with CH340, using Arduino IDE 1.8.5 under Linux Ubuntu 17.10. Besides, this will probably happen if you use IDE 1.8.9 or newer and you get an old or cloned Nano.


body:
After lots of unplugging, checking ports, restarting IDE, etc. The ting which seemed to make a difference fixing this fault with Arduino Mega 2560 was to uninstall the windows USB arduino driver then reinstall it usig the driver here & select manually from the list>com ports>arduino
http://drivers.softpedia.com/get/Other-DRIVERS-TOOLS/Others/Arduino-Mega-2560-USB-Driver-1110-for-Windows-7-64-bit.shtml
I may have tested it on my uno then back to the mega so there's a small chance talking to the uno made AVRDUDE happy but unlikely.


body: I solved it by updating the boards (under "board manager")


body:
When I get a problem uploading to my boards I upload a different program like the blink example.  This seems to reset something and I am then able to upload my own program (which is quite large).

It might be worth trying this to see if it works in your case, although I have no idea why it works.


body:
I faced the same problem for some code today and I solved it as follows:

 1- First I ran  a basic LED blinking code. It gave the same error. It confirms that  the error is in uploading  and has nothing to do with compiling. I also checked my code was compiling fine.

2- I took another board, but it was working fine on this PC. That  means computer and the USB wire is OK.

3- I connected the faulty board to another PC, and surprisingly, there was no such error in uploading. That gave me hint about issues in driver in the first PC.

4- So I uninstalled the driver and re-installed it on the first PC by downloading from [here][1]

( make sure that while installing the driver from this link, you keep your board  connected to the PC)

 It worked fine now :-)

  [1]: https://drp.su/en/devices/chipset/arduino/arduino-mega-2560?os=windows-7-x64


body:
I had a similar issue with my Uno board

    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x90

Tried many methods

 - Press reset before sending packets
 - different IDE versions
 - Change cable
 - Change controller itself
 - Loopback test

but all of the above failed.

I use Ubuntu 16.04.4 LTS `4.15.0-33-generic` (while writing this comment). The CDC ACM module was not loaded, therefore no `/dev/ttyACM0` device was created to select in `Arduino IDE -> Tools -> Port`

Therefore,
Get the module name and load it

    $ lsusb
    Bus 002 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hub
    Bus 001 Device 005: ID 2341:0043 Arduino SA Uno R3 (CDC ACM)
    Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub

    $ sudo modprobe cdc-acm

The above command will insert the required module.
Now i'm able to select the right port and upload the code

Out of various solutions this worked for me, hope this helps someone too.


body:
I had this error in my Linux Mint 17.3 laptop with Arduino Nano
avrdude: stk500_getsync(): not in sync: resp=0x00

Solved:

- removed all that had 'arduino' or 'avr' in its name
- removed directories .arduino and .arduino15 (Note the dot in the name)
- removed ver 1.8.7 with uninstall of the packet
- apt-get install arduino (ver 1.1.0)
- tested with a simple sketch (everything OK)
- installed ver 1.8.7 with the install of the packet
- compiled.
- selected ATmega328p(Old bootloader) for processor, Arduino Nano for card and /dev/ttyUSB0 for port
=> IT WORKS !

It seems that the 'Old bootloader' was the trick in this case.
I have now both ver 1.1.0 an 1.8.7, who cares.


body: What I tried was to not connect one Ground of one board to the other ground on the other board. This stopped the problem for me.


body:
If you use `arduino-cli` and a Arduino Nano clone, you can change the bootloader to the old one, as said in other answers, by using the following command to upload to the Arduino:

```
arduino-cli upload -v -p /dev/ttyUSB0 --fqbn arduino:avr:nano:cpu=atmega328old program_name
```

Explanation:

|command|explanation|
|:---|---:|
|`arduino-cli`|call `arduino-cli`|
|`-v`|Use verbose output|
|`-p /dev/ttyUSB0`|The port, use `arduino-cli board list` to find the right port|
|`--fqbn arduino:avr:nano:cpu=atmega328old`|Use avr board library, nano board and the Atmega328 CPU with the old bootloader|
|`program_name`|Replace this with the name of the program you want to upload|


message:
Why Arduino Severino (S3V3) sometimes needs reseting when uploading a sketch?

I have an original Arduino UNO R3 that I bought and an [Arduino Severino (S3V3)](http://arduino.cc/en/Main/ArduinoBoardSerialSingleSided3) that I've built.

I have no problems uploading sketches to the UNO, but sometimes, when uploading to the Severino board, I have to hard reset it at a specific time during the upload process, when the IDE says something like this below:

 avrdude: Version 5.11, compiled on Sep  2 2011 at 19:38:36
    Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
    Copyright (c) 2007-2009 Joerg Wunsch

    System wide configuration file is "C:\arduino-1.0.3\hardware/tools/avr/etc/avrdude.conf"

    Using Port                    : \\.\COM1
    Using Programmer              : arduino
    Overriding Baud Rate          : 115200
 avrdude: Send: 0 [30]   [20]
 avrdude: Send: 0 [30]   [20]
 avrdude: Send: 0 [30]   [20]

If I don't reset it when one of the `Send` messages are being displayed, I get the `not in sync` message, as below:

 avrdude: Recv:
 avrdude: stk500_getsync(): not in sync: resp=0x00

Other times, if I'm lucky, I can upload to the Severino board without having to reset it.

So, my questions are:

1. **Why does that happen? Why Severino needs a hard reset during upload?**

1. **Why is the problem intermitent?** Why does it happen sometimes and others it doesn't?

1. **How can I fix that problem?** Is there a simple change to the Severino design that would fix that?

body:
**Why does that happen?**

When the serial port is opened by either monitor, avrdude or other it toggles the DTR pin of the serial port. Which in turn is AC coupled through C4 100nF. This toggling is converted to a up and down pulse on the ATmega(CPU)'s RESET pin. The subsequent reset starts initially with the boot loader, which typically in turn waits for a avrdude's semiphore (e.i. Send: 0 [30]   [20] ) and if seen then responds in turn and if not seen after a timeout period (typically 5s) it continues on with the application in flash space.

You behavior is describing either; not hearing the response. Or the reset is not getting triggered. Since it does work some times I suspect its prior, but the later.

**Why Severino needs a hard reset during upload?**

This statement further supports the later.

**Why is the problem intermitent?**

the pulse is almost long and strong enough, where the DTR toggle is in code and likely has some significant inconsistency.

**How can I fix that problem?**

Yes, change the value of C4 100nF and or R11 10K, to better pass the toggle. I could derive some EE explanation of what value to pick. But I would suggest some trial and error.

It should also have 5V clamping, as the RS232 levels can reach +/-12V (typically +/-9V) where the AC coupling prevents the DC and burn out. but the AC will stress it.


message:
Custom Arduino board beeps and process freezes while I'm uploading a sketch to it. Why?

The strangest thing is happening to a standalone Arduino board that I designed and built. The board (whose schematics are below) has the following features:

1. It has a ATmega328P with a 5V voltage regulator and usual circuitry when set up as a standalone controller.
1. It controls a scoreboard with several 7-display digits linked through the connectors on the right (JP1 through JP12).
1. It has cursor buttons decoded using a voltage ladder through ANALOG_0 (A0).
1. It has a Real Time Clock to keep time when it's turned off.
1. It has an RF receiver module.
1. It has a UART header (JP17) so I can program the board using a serial port.
1. It has a speaker attached to digital pin 3 (D3).

![Controller schematics][1]

I upload sketches to it using a RS232-to-TTL adapter that I've also built (schematics also below) and a Serial-to-USB cable. When programming it, the board behaves much like a [Severino board](http://arduino.cc/en/Main/ArduinoBoardSerialSingleSided3).

![enter image description here][2]

What's strange is that, when I upload a sketch, the process is paused in the middle and then the speaker starts to beep continually. It pauses with the following avrdude messages:

avrdude: Version 5.11, compiled on Sep  2 2011 at 19:38:36
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2009 Joerg Wunsch

         System wide configuration file is "C:\arduino-1.0.3\hardware/tools/avr/etc/avrdude.conf"

         Using Port                    : \\.\COM1
         Using Programmer              : arduino
         Overriding Baud Rate          : 115200

When I press reset on the board, avrdude continues outputting its messages (such as below), the beep stops, the upload continues and the sketch is uploaded successfully to the board.

    avrdude: Send: 0 [30]   [20]
    avrdude: Send: 0 [30]   [20]
    avrdude: Send: 0 [30]   [20]
    ... messages and upload continue and completes successfully.

I don't have the rest of the messages handy here, but I hope you get the idea.

So, my questions are:

1. **What is making the upload process pause?**
2. **Why is the buzzer beeping when the process pauses?**

  [1]: https://i.stack.imgur.com/21kgT.png
  [2]: https://i.stack.imgur.com/h3HJq.png

body:
>    What is making the upload process pause?

Well, given all the comments made under your question, this is definitely a tricky one. You might want to try to add a decoupling capacitor as suggested by @jfpoilpret, though your schematics look alright to me… (maybe ask a review of it on [EE SE](http://electronics.stackexchange.com)).

I'd also advice you to copy the `avrdude` command from Arduino IDE output (you'll find it at the top), and run it in the command shell with lower bitrate:

    avrdude -v -v -v -v -C "C:\arduino-1.0.3\hardware/tools/avr/etc/avrdude.conf" -P COM1 -patmega328 -U… -B3 -b115200

the higher the `-B` value is the lower your bitrate is. and `-b` to the correct baudrate for your bootloader (are you *sure* this is 115200? it's more common to see 57600).

Did you also set fuses correctly? You might as well want to check the values of the fuses to see if the clocks are correctly set up:

    avrdude -U lfuse:r:-:i -U hfuse:r:-:i -U efuse:r:-:i

which will output the values of the fuses. Then to make the values readable, put the values at the bottom of the form on the [fuse calculator site](http://www.engbedded.com/fusecalc/), after choosing the `Atmega328P` MCU from the dropdown list.

Double check that:

 * you have enough size for the bootloader (usually the more you give it the better it is) ;
 * you have correctly set up the cristals configuration for your design (which may not be compatible with default Uno settings as setup by the Arduino IDE), checking if you correctly set up the external crystal at 16MHz…

>    Why is the buzzer beeping when the process pauses?

It's because when the processor does not have the output set up, the values within the registers are in an undefined and unpredictable state. Which means that usually it keeps the last value it had before a reset, or changed state because of some electrostatic weirdness, or is giving some weird PWM output because of the influence of a clock nearby.

So basically, there's something wrong happening when you're uploading your code and that wrong thing has an indirect effect on the audio. I wouldn't worry much about that stuff, but more about the cause of the pausing.

Sadly, I don't have a direct answer for you, but at best a few paths you should investigate more. HTH


body:
I'm not sure but the problem may also be related to the auto-reset feature of the converter board.

I copied the converter board design from the [Arduino Severino](http://arduino.cc/en/Main/ArduinoBoardSerialSingleSided3) and according to [its manual](http://arduino.cc/en/uploads/Main/ArduinoSeverinoManual2.pdf), the serial communication must be set to 19,200 bps for the auto-reset feature to work.

> Be sure that computer COM Port speed is set to 19200bps otherwise
auto reset will not work properly.

Well, I'm using 115,200, so that must be a problem.


body:
I finally found what was causing the problem: the reset signal from pin 4 (DTR - Data Terminal Ready) on the DB9-Female connector was spiking up to 10V before going to 0V and was triggering high-voltage programming on the ATmega. Below is a scope shot showing the situation:

![Scope shot showing voltage spike to 10V][1]

The yellow trace is `DTR` signal while the green trace is the `RESET` signal on the ATmega.

According to Atmel's [Atmel AVR042: AVR Hardware Design Considerations application note](http://www.atmel.com/images/atmel-2521-avr-hardware-design-considerations_application-note_avr042.pdf), one should add an ESD diode between ATmega's `RESET` and `Vcc` to prevent the reset signal from triggering high-voltage programming mode, like so:

![Recommended RESET pin connection for ATmegas][2]

After adding such a small signal diode (1N4148) like the app note recommended, I got the issue fixed. See below the scope shot taken after the diode was added.

![Scope shot after fixing the board][3]

Now the 10V peak is gone.

That was a tricky one!! But I could never find what was wrong without research and the right tools. Money on a scope is money well spent!!

  [1]: https://i.stack.imgur.com/IM3RF.png
  [2]: https://i.stack.imgur.com/GJuGd.png
  [3]: https://i.stack.imgur.com/kwpzB.png


message:
How do I get an accurate time?

I've made a clock using an Arduino, but the time seems to drift.  I am aware of the [rollover](https://arduino.stackexchange.com/questions/1/is-an-arduino-capable-of-running-24-7/2#2) issue; the clock seems to drift by about 15 minutes over the course of a week.

I'm using a custom PCB with [this resonator](http://www.digikey.com/product-search/en/crystals-and-oscillators/resonators/852887?k=x908-nd) from Digi-key.  The code reads the millis() function at the beginning of each loop, and works from that value.

My question is:  How can I measure time with an Arduino, accurately enough to make a passable desk clock?

body:
*Note: although my answer was accepted and has a higher vote score, make sure you read [Edgar Bonet's great answer](https://arduino.stackexchange.com/a/9039/46) on how to make your Arduino keep time without an RTC.*

I've been quite successful in using the DS1307 Real Time Clock. Here's a link to its [datasheet][1].

Below are some of its features:

* It uses I<super></super>C interface for communication with Arduino, making it easy to program using the right libraries (available on the Net).

* It is connected to Arduino through the SCL and SDA pins (analog A4 and A5 respectively), thus only using 2 pins.

* It requires very little external components to run.

* IT can be connected to a coin cell battery so it will keep time even while the Arduino is turned off. In its low power mode, the coin cell battery lasts for years.

* It drifts very little (in my case it only drifts a few seconds per week).

* It's not very expensive.

If you don't intend to use an RTC, you can replace the crystal that is commonly used to provide clock to arduino for a **crystal oscillator module** like [this one from Farnel][1] or [this other one][2]. They come in 4 pin packages like in the images below. They will generate a much more precise clock for your arduino.

![Crystal oscillator image][3]
![Crystal oscillator image][4]
![Crystal oscillator image][5]

Both modules mentioned have tolerances of 50 ppm and operate at 5V.

Again, just to be clear, these crystal oscillator modules are not to be confused with regular 2 pin **crystal** like this below. Those are part of the circuitry of external clocks for MCUs, for example.

![Crystal oscillator][6]

  [1]: http://uk.farnell.com/epson/sg531p20mhz/crystal-oscillator-20mhz/dp/1216196
  [2]: http://www.digikey.com/product-detail/en/ECS-2200BX-200/XC1188-ND/827295
  [3]: https://i.stack.imgur.com/OjaoR.jpg
  [4]: https://i.stack.imgur.com/aTIAn.jpg
  [5]: https://i.stack.imgur.com/ay7KD.png
  [6]: https://i.stack.imgur.com/a52VR.png

  [1]: http://datasheets.maximintegrated.com/en/ds/DS1307.pdf


body:
The resonator you specified has a 0.3% stability, where the crystal or crystal oscillator (as mentioned by Ricardo) is 50ppm. Many times more stable. Not to even mention the temperature drift of resonator is horrible. Heating by sunlight will change it. Hence a resonator should not be used for keeping time over long periods.

Hence using either a crystal or crystal oscillator will get what you want. Either using it on the ATmega and set the fuses respectively or us one connected to an RTC.


body:
I understand a lot of the spirit with Arduino is being frugal and occasionally trudging through a problem. I use Arduino (and now chipKIT, since it's got 10x the RAM and 10x the clock speed) for my workplace and I need "peripheral functions" to be up to speed and working as quickly as possible.

I use the sparkfun real time clock in one of my projects and am very happy with it. They also have a ["Dead on" variant][1].

  [1]: https://www.sparkfun.com/products/10160


body: If you don't want to use extra hardware like an Real Time Clock (eg. DSDS1307), you can significantly improve timing accuracy by disabling all unused interrupts. By default Arduino sketches come with various interrupt routines enabled and often they are not used for actually your sketch. Quickest way to find out if you can do without it to try and disable them by issuing [`noInterrupts();`](http://arduino.cc/en/Reference/Interrupts)


body:
You do not need an RTC to build a clock: the ATmega chip has all the
hardware needed to perform the duties of the RTC itself. Here is how:

1. Get a 32768 Hz watch crystal: either buy it or disassemble an
   old clock. These crystals, specifically designed for time keeping,
   have an _extremely_ small temperature drift. You would also need one
   of those if you wanted to use an RTC chip.

2. Configure the fuses of your ATmega to run off the 8 MHz RC
   oscillator. This will make your `millis()` function horribly
   inaccurate, and also free the XTAL1 and XTAL2 pins.

3. Connect the watch crystal to the TOSC1 and TOSC2 pins. These are the
   same pins as XTAL1 and XTAL2 (9 and 10 on the 328P). The different
   names are used to mean different functions.

4. Configure the Timer/Counter 2 for asynchronous operation, normal
   counting mode, prescaler set to 128, and enable the timer overflow
   interrupt.

Now you will get a TIMER2\_OVF interrupt at a very steady rate of once
per second. You only need to advance the clock display by one second in
the ISR. In between the interrupts, you can put the MCU in very deep
sleep (power-save sleep mode: nothing runs but Timer/Counter 2) and run
for years on a couple of AA cells. Unless the display is power-hungry,
obviously.

I did exactly this to build my [24-hour one handed wall
clock](http://unsecure.logre.eu/wiki/Horloge_analogique_24h/en).
This link points now to the English translation of the original
documentation in French.

## Quartz calibration

If you do not calibrate your quartz, you can expect a significant drift,
typically **a few seconds per week**. The drift rate depends on the
stray capacitance of the traces that connect the crystal to the MCU. In
principle, it could be removed by adding some extra, finely tuned
capacitance. It is worth noting that you would have _the same drift
problem_ with an RTC.

If you are satisfied with this kind of accuracy, then live with it and
be happy. However, if you care to measure the drift, you will notice
that it is very stable. You can then easily compensate for it in
software, and achieve an accuracy of **a few seconds per year**.

The algorithm for correcting the drift is very simple. From the measured
drift, you figure out the precise delay between the interrupts, which
should be very close to 109 nanoseconds, then:

    #define ONE_SECOND    1000000000  // in nanoseconds
    #define ONE_INTERRUPT  999993482  // for example

    ISR(TIMER2_OVF_vect)
    {
        static uint32_t unaccounted_time;

        unaccounted_time += ONE_INTERRUPT;
        while (unaccounted_time >= ONE_SECOND) {
            advance_display_by_one_second();
            unaccounted_time -= ONE_SECOND;
        }
    }

In the above example, the quartz is slightly too fast, and the software
compensates by “missing” a tick every few days. If the quartz was too
slow, the same code would instead double-tick once every few days.

This kind of calibration could also be done for an RTC, but it would be
significantly more complex because the RTC reports the time in a
broken-down form that does not naturally lend itself to arithmetic
operations.


message:
How to pause Arduino for 1 millisecond through MATLAB?

I have been able to connect MATLAB to my Uno with this line of code: `a = arduino('COM4');` through this package: [Matlab support package for Arduino][1].

Right now, MATLAB is my main script that will synchronize all the components [like the Arduino].

I am able to send pulses to my stepper-motor just by using:

    void loop() {
        digitalWrite(2, HIGH);
        delay(1);
        digitalWrite(2, LOW);
        delay(1);
    }

This works fine, and will make the motor move about once every 2 milliseconds. My problem is that I cannot find a way to produce this same delay through MATLAB's interface. I do know that MATLAB has a `pause()` function, but when I set up a loop in MATLAB like this:

    a = arduino('COM4');
    for m = 1:400
        a.digitalWrite(2, 1);
        pause(0.001);
        a.digitalWrite(2, 0);
        pause(0.001);
    end

Each step takes WAY longer - about 200 milliseconds each.

What are other options for creating the pause between digital High / Low being sent to the Arduino? It would be nice if I could control the outcome from Matlab, through Arduino.

  [1]: http://www.mathworks.com/matlabcentral/fileexchange/32374-matlab-support-package-for-arduino-aka-arduinoio-package

body:
The increased in observed delay is due to the time it takes to send the command from MATLAB to the Arduino have its code execute the requested command. In your case the a.digitalWrite. So actual time between pulses using MATLAB's delay is 0.001 pause plus the time of baud rate times the packet size and decoding then execution.

I would recommend not pursuing this solution of the MATLAB controlling the timing of Step Motors, remotely. As this latent coupling will be a frustrating limitation. Noting that for step motors the timing can not afford such latent execution. Hence all the 3D printers and many CNC with Step Motors use Arduino's which get G-Code (motor move commands with destinations) and the Real-time firmware handles the stepping, within tolerances.

I would suggest using something like grbl firmware with step motor shield and then have the MATLAB send the needed G-code. Where there are others with much more features but tailored to 3d Printing. grbl is simpler and straight to the point of moving motors.


body: It's not clear from your question whether you are trying to get real-time execution without latency or simply want to adjust the motor delay time from MATLAB.  If the latter, a good way is to send delay data (e.g. a number that represents how long you want between pulses) vie serial, which your Arduino program will receive and update the motor delay as desired.  Or, bearing in mind RAM limitations, you can send a whole sequence of delays that can run one after another with precise timing.


message:
Post Data To a Web Service From Arduino

If you want to submit sensor data such as temperature to a remote server/database somewhere you need to use some kind of call to a web server since it isn't possible to connect directly to a database from the Arduino.

How do you post data to a JSON web service from an Arduino that's connected to the Internet?

body:
There is the [aJson][1] library that allows you to work with JSON objects in Arduino.

However, depending on the complexity of your program, I would just do it manually to save memory. You may be able to just copy the functions you want out of the library.

Then check out the [WebClient][2] library which has an example for making a POST request at the bottom.

  [1]: https://github.com/interactive-matter/aJson
  [2]: http://playground.arduino.cc/Code/WebClient


body:
Check [this][1] from Arduino docs.

In the "Post method request" code example just define your JSON as plain text like `char jsonData[] = "{name: 'yourName', data: 'yourData'}"` for example, and then call `byte postPage(char* domainBuffer,int thisPort,char* page,char* thisData)` function passing "jsonData" variable defined before for "thisData" parameter.

It worked for me, hope it helps.

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


message:
Is there a preprocessor constant for memory size

I would like my compiles to exclude some code depending upon the flash/program space available. To be used in the demo code of a library I support. Whereas my current solution is to use a #ifdef of processor type. But I would like to be more general and not have to specify all the various chips. Rather it would be nice if there was a pre-processor constant that stated the available size.

Where I am not fluent enough in gcc and or avr-gcc I might expect to find some constants similar those that define the beginning and end of the heap.

On case example. Is that both the UNO and Leo have 32K of Flash. But the Leo's core library uses 4K for USB support, resulting in only 28K available. My Library's demo is near max'ed out on the UNO and I would like to automatically trim out based on available program space.

body:
Find the `io__.h` file for your microcontroller, on Linux it is located in `/usr/lib/avr/include/avr`, on Windows it will be in a somewhat similar location.

Scroll down to the part that says `/* Constants */`. There are couple interesting macros defined there, `FLASHEND` being the one you should be interested in. You can use it for example as follows:

    #if FLASHEND > 0x8000
    /* Include some extra code when sufficient flash is available. */

    #endif


message:
How do I communicate with the Uno using R through RStudio?

I am working on a real time application which is recording sensor data continuously. I need to process the data in realtime using R. Is there a way to connect and communicate with the uno board through RStudio via serial port?

body:
If RStudio has serial support. Yes, it can talk to a Uno. If it does not. No.

This is really a question about RStudio (and actually just pure [R][1]), not arduinos.

Furthermore, RStudio is just an IDE. Therefore, no, *RStudio* can *not* communicate with an arduino, compile a program, or do much of all aside from edit source-code files. RStudio does not run your code at all. It uses an external interpreter to run your source files.

*R*, on the other hand probably *can* talk to serial interfaces. The fact that you're using RStudio is entirely irrelevant.

I'm not familliar with R, but a little googling leads me to think that R can talk to serial interfaces without *too* much trouble, though I have not been able to find any information about doing so on windows. What platform are you using?

  [1]: http://en.wikipedia.org/wiki/R_(programming_language)


body:
I can't seem to figure out directly how to read from a serial port using R; While there does seem to have been at least [one attempt](https://biostatmatt.com/archives/112) to provide this, it's not clear that it ever graduated to something supported or easily installable.

Having said that, R does have [`read.socket` and `write.socket`](http://stat.ethz.ch/R-manual/R-patched/library/utils/html/read.socket.html), which I believe would make it easy enough to use through [`ser2net`](http://ser2net.sourceforge.net), which exposes a serial-port as a socket.


message:
Arduino Uno R2 and Ethernet Shield R3 compatibility

I bought an [Ethernet Shield R3][1] for my [Arduino Uno R2][2], but since R3 has extra pins it does not fit. Can I use the shield? Should I cut off the extra pins. What do I need to do to make it work?

  [1]: http://arduino.cc/en/Main/ArduinoEthernetShield
  [2]: http://startingelectronics.com/articles/arduino/uno-r3-r2-differences/

body:
The extra pins do not matter. Just leave them. If you really want, cut them off, but this will remove some compatibility with other products.

They should hang off the ends of the headers closest to the power/USB end of the board.


body:
The only issue that may create an incompatibility seems to be the IOREF pin next the 5V output pin which is extra on Revision 3 but not in Revision 2.

However, I just had a look at the board schematics and the shield does not use IOREF.

>![][1]

<sub>**Pin 2 is extending IOREF**</sub>

So, the shield should work correctly with the Uno Revision 2. As far as the extra pins are concerned, I would recommend not damaging them in any way. If you absolutely *need* to, then just try to bend them outwards very carefully.

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


message:
What are the other IDEs for Arduino?

The basic Arduino IDE lacks a lot of the sophistication present in other IDEs such as code completion, code collapsing, folder organisation, etc. Are there other IDEs that allow programming in C or C++ and improve on these aspects?

body:
There is an [Arduino Eclipse plugin named sloeber][1]! And Eclipse is an awesome cross-platform open-source IDE!

[Stino][2] is good. It requires [Sublime Text 2][3] which has an indefinite free trial.

[Visual Micro][4] provides a full build system with debugger for Arduino in [Microsoft Visual Studio][5]. For advanced users it also allows the underlying Arduino source code to be viewed or modified, enabled projects and/or libraries to be edited from any location and shared in multiple projects alongside true [cross-platform intellisense][6].

For more go to [The Official Arduino Site][7]

For development on Windows, there is a special edition from Arduino official IDE called [arduino-erw][8], This edition much better the last one because it fixed a lot of lagging and stability issues!

  [1]: http://sloeber.io
  [2]: https://github.com/Robot-Will/Stino
  [3]: http://www.sublimetext.com/2
  [4]: http://www.visualmicro.com/
  [5]: https://www.visualstudio.com/vs/whatsnew/
  [6]: http://www.visualmicro.com/post/2017/01/16/Arduino-Cross-Platform-Library-Development.aspx
  [7]: http://playground.arduino.cc/Main/DevelopmentTools
  [8]: https://code.google.com/p/arduino-erw/


body:
Majenko created and maintains [UECIDE][1]. His contributions are pretty epic; I've seen first hand his coding prowess as we [worked together][2] to get the [Adafruit 1.8" TFT Joystick shield][3] working on the chipKIT platform.

  [1]: http://uecide.org/
  [2]: http://www.chipkit.net/forum/viewtopic.php?f=18&t=2530
  [3]: http://www.adafruit.com/products/802


body:
One rather good IDE extension is the Arduino Mode for Emacs. It allows using a highly versatile and extensible IDE such as Emacs for writing, compiling and uploading code to the Arduino.

The documentation and instructions can be found [here](http://www.emacswiki.org/emacs/ArduinoSupport).


body:
You can use [AVR Studio][1] to write programs for Arduinos.

There is a plugin that lets you link against and use the arduino libraries from [within Atmel Studio][2].

If you've used Microsoft Visual Studio, Atmel Studio is basically a reskin of Visual studio with different compiler backends that target the ATmega series of devices, so you'll feel right at home.

  [1]: http://www.atmel.com/microsite/atmel_studio6/
  [2]: https://arduinotemplateexpress.codeplex.com/


body:
Expanding on [Fake Name's answer][1], there is also [Visual Micro's Arduino plugin][2] for Atmel Studio (built off Visual Studio). It shares the tools, sources and libraries with the Arduino IDE but provides all the code completion and other features of Visual Studio.

The Visual Micro plugin also works in all versions of Visual Studio. Provides
Arduino usb debugging and an Arduino IDE compatible Board Manager.

  [1]: https://arduino.stackexchange.com/a/43/220
  [2]: http://www.visualmicro.com/


body:
[vim][1] can be used for Arduino development, but it will take some configuration (as is the way of vim). You'll need the [syntax file][2] and [this plugin][3] that enables you to compile and deploy from vim.

[Grant Lucas][4] produced a great write-up on getting your environment situation squared away:

> ## [Using Vim for Arduino development][5]
>
> Here's a quick post on setting up Vim for Arduino development instead
> of using the Arduino IDE. If you're a heavy Vim user, it can be a bit
> of a shock to go into a different editor. Thankfully the setup is
> pretty easy to get this all working with Vim. This post is assuming
> you are comfortable with how Vim is setup and ideally already have an
> environment that works for you.
>
> ### Install the Arduino IDE
>
> _Wait. What?!?_ I hear you say. I know, I know. We're not actually using the Arduino IDE but we need it for some configuration and the
> files it installs. The Vim plugin we'll be using ties into what the
> IDE installs and configures so it's needed. You can download the IDE
> from the [Arduino site][6].
>
> ### Install vim-arduino plugin
>
> To get the main goodness of compiling, monitoring and deploying to an
> Arduino, grab the latest version of [vim-arduino][7]. Install it in
> your .vim folder using what ever method you use to manage your Vim
> plugins. **Hint:** I'd recommend [Pathogen][8] as it makes installing
> as simple as dropping the plugin folder into a bundle folder.
>
> ### Vim syntax file
>
> Next up is to get the syntax file so we can have nice colour coding
> for .pde and .ino files. Download the latest [arduino.vim][9] and
> install it in your Vim syntax folder. To get the syntax to apply to
> the correct file types add the following to your vimrc file
>
>     au BufRead,BufNewFile *.pde set filetype=arduino
>     au BufRead,BufNewFile *.ino set filetype=arduino
>
> ### Configuring the Arduino IDE
>
> Before trying to compile and deploy with Vim, get it all working with
> the Arduino IDE first as the Vim plugin just calls from the settings
> saved by the IDE. If it's working in the IDE, it should work in Vim.
> Make sure you select the right tty.usbmodem* serial port from Tools >
> Serial Port in the IDE. **Note:** This will only show when the Arduino
> is plugged in.
>
> ### Working from Vim
>
> Once you can communicate with your Arduino from the IDE you should be
> fully good to go with Vim. You shouldn't have to open the IDE unless
> you want some example code. Open up your sketch file in Vim and use
> `<Leader>ac` to compile a sketch, `<Leader>ad` to compile and then
> deploy to the connected Arduino and `<Leader>as` to open a new window
> with `screen` to monitor the serial output from the Arduino.

  [1]: http://en.wikipedia.org/wiki/Vim_(text_editor)
  [2]: http://www.vim.org/scripts/script.php?script_id=2654 "Syntax file for Arduino .PDE files "
  [3]: https://github.com/tclem/vim-arduino "GitHub: tclem / vim-arduino"
  [4]: https://twitter.com/grantlucas
  [5]: http://grantlucas.com/posts/2012/09/using-vim-arduino-development
  [6]: http://arduino.cc/en/Main/Software
  [7]: https://github.com/tclem/vim-arduino
  [8]: https://github.com/tpope/vim-pathogen
  [9]: http://www.vim.org/scripts/script.php?script_id=2654


body: In addition to the mentioned IDEs you can use Xcode with [embedXcode](http://embedxcode.weebly.com/) if you use a mac. The IDE has a great file structure and support for a lot of boards. For big and complex projects it is really good. I like to use vim or the arduino IDE for simpler and less complex sketches/projects.


body:
There is one from Brazil called **MariaMole**: http://dalpix.com/mariamole

According to the author, like the original Arduino environment, the MariaMole facilitates the creation of software for the Arduino. However, while the original Arduino IDE has limitations to make life easier for beginners, MariaMole brings features that more advanced users are accustomed to find in professional IDEs, such as:

 - Runs over Arduino install
 - Workspace support multiple projects at the same time
 - Multiple serial port consoles at the same time
 - Files use open-formats
 - Building process configurable
 - Imports Arduino examples and sketches
 - Easily import Arduino libraries
 - Color-themes


body:
UPDATE->  [Codebender is being shut down.](https://codebender.cc/next-chapter)

There is a brilliant open source, web based IDE called [Codebender][1]

It is like Github for Arduino and has a great community working from it with thousands of examples and the dev team are exceptional.

With codebender, you can:

 - program an existing sketch to your device
 - clone an existing sketch
 - modfy it to your needs
 - share your work with the world
 - embed code in your website, blog, or tutorials

Cross-platform
Works on Windows, Mac & Linux, Firefox & Chrome

Codebender supports Windows (from Windows XP up to Windows 8.1, yes, even Vista :P), Mac OS X 10.6-10.9, and Linux and works within all major browsers

  [1]: http://codebender.cc


body:
There is a half way solution as well since the Arduino IDE has support for external a editor, then the Arduio IDE just compiles and uploads.

![enter image description here][1]

Now you can use whatever IDE/editor you like to edit the code,
and then you switch back to the Arduino IDE to press the compile and upload button when you are done.

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


body:
I have always wanted to use Eclipse, since that is our standard (for Java) at work. But I never managed to get the debugger working with my AVR Dragon board - just too many layers between the source code and the chip.
So I am back to using Atmel Studio. You can set the keyboard mapping to emulate various other IDEs (including Eclipse and Netbeans). I can accept the Microsft quirkiness in return for a stable debugging environment, multi-file support and professional source control features.


body: I use Xcode, set up as an external editor. I write everything in libraries, and the sketch simply call the libraries.


body:
# Fritzing
> This is the new “Code View”! It lets you write your code directly inside Fritzing, and even upload it from there to your microcontroller. It even has a serial monitor. :)

Normally known as a schematic builder, Fritzing has a built in IDE.
[See here for more.][1]

  [1]: http://blog.fritzing.org/2014/12/02/its-fritzmas-new-fritzing-code-view-release-and-a-little-present/


body: Haven't seen anyone mention it yet, but I use VisualMicro for Microsoft Visual Studio (not Atmel), and I like it just fine. It gives you everything you'd normally have in Visual Studio, like intellisense typing. The trial version is the full program, and the license is pretty cheap- like 30 bucks or something. I got my work to pay for a commercial license key. Do recommend!


body:
Notepad++

 - set Notepad++: view->folder as work space
 - and Language->C->C++ sets syntax highlighting
 - set arduino Ide file->preferences "Use external editor"

and everything runs smoothly, without the bulk of eclipse.


body:
Clion + PlatformIO
----------------------

I personally use **[Clion][1]** which is a cross-platform IDE along with **[PlatformIO][2]** which is a cross platform build system for arduino and alike.

Clion because I love the jet brains IDEs. As a student or teacher you can get a free licence. And I have been told by suspicious people on the internet that there are other ways of obtaining a license (not that I would advice on doing anything like that).

PlatformIO is quite powerful and integrates well into almost any IDE. It's easy to declare dependencies to other libraries which are automatically downloaded.

I am also using the [Clion serial port monitor plugin][3] to communicate over `Serial.print()`.

With this setup you can completely ditch the old Arduino IDE which I found to be quite satisfying!

  [1]: https://www.jetbrains.com/clion/
  [2]: http://docs.platformio.org/en/latest/ide/clion.html
  [3]: https://plugins.jetbrains.com/plugin/8031-serial-port-monitor


body: My go-to choice (pun, that's only a pun, folks!) is Sloeber - Eclipse with Jantje's EclipseArduino plugin. Having decades of emacs muscle-memory-training, I use MulgaSoft's Emacs+ plugin with it, switching to real GNU emacs for the heavy lifting - as developing a project and new libraries for it in parallel, f/ex, and use Sloeber to catch my typos & brain-f*ts.


body:
A good alternative to the Arduino IDE is Visual Studio Code in combination with the Microsoft extension for Arduino https://github.com/Microsoft/vscode-arduino

It gives all the features of the Arduino IDE such as

Verify and upload your sketches in Visual Studio Code

 - Built-in board and library manager
 - Built-in example list
 - Built-in serial monitor

but additionally to offers some attractive features:

- IntelliSense and syntax highlighting for Arduino sketches
- Snippets for sketches
- Automatic Arduino project scaffolding


body:
PlatformIO
---

I use GitHub's [Atom][1] text editor with the [PlatformIO][2] package.

I like both of them:

 - [Atom][1] has various useful built-in features and over 6,000 packages (which can be easily downloaded and installed from the settings pane) allowing the user to add essentially any feature he needs.
 - [PlatformIO][2] is a powerful IDE for microcontroller programming. It has all the features of the Arduino IDE (like the ability to upload code to an Arduino board with one single click, a serial monitor, ...) plus many others (like all those listed by the OP) and perfectly supports Arduino. Besides "it supports more than 200 development boards along with more than 15 development platforms and 10 frameworks". It can be natively installed either on GitHub's Atom either on Microsoft's [VSCode][3] code editors.

---

**Edit**

I still use PlatformIO on Atom on a regular basis, but I just saw on their [website][4] and forum that they are discouraging users from using their Atom package while proposing PlatformIO in VSCode as a better alternative.
The Atom version still works well, but if you are changing your editor and want to try PlatformIO I would suggest to follow their advice and install it in VSCode.

  [1]: https://atom.io/
  [2]: http://platformio.org/platformio-ide
  [3]: https://code.visualstudio.com/
  [4]: http://docs.platformio.org/en/latest/what-is-platformio.html


body:
after some experience

any editor (atom or vscode) are excellent with platformIO

offering:

 1. syntax highlighting
 2. debugger
 3. easy project (s) manager
 4. (which i like most) collapsible blocks


body:
In late 2019 we have the [Deviot][1] Sublime Text 3 plugin that runs on top of PlatformIO.

  [1]: https://github.com/gepd/Deviot


body:
I use Eclipse and Sublime Text for editing Arduino code, and I build in the Arduino IDE with it set to "external editor" mode, or using the Arduino Command Line tools. Eclipse has a fantastic indexer and makes understanding the Arduino core much easier. I've written a detailed PDF about using and setting up Eclipse for professional software development, incl for Arduino, here: https://github.com/ElectricRCAircraftGuy/eRCaGuy_dotfiles/blob/master/eclipse/Eclipse setup instructions on a new Linux (or other OS) computer.pdf.

Note that I'm using regular Eclipse for C/C++, with no Arduino plugins. I don't find them that useful since they can never seem to keep up with the latest Arduino build tools anyway.

See my document for full setup information in general.

# Related:
1. https://arduino.stackexchange.com/questions/816/c-vs-the-arduino-language/50839#50839


message:
Assembly on the Arduino: IO registers

**Question:** What registers do I use to access the IO on the Arduino Uno when I am using assembly for programming?

**Background:**  I was interested in practicing my assembly language skills on the Arduino (I thought it would be easier to turn LEDs on/off than to worry about console IO).  From doing a [preliminary search](https://electronics.stackexchange.com/q/12750/17375), I have found that the AVR toolchain can be used to program the Arduino.  Yet, I don't quite know how to find the corresponding registers for the IO pins.

body:
Check this out: http://arduino.cc/en/Reference/PortManipulation

Also: http://arduino.cc/en/Hacking/PinMapping168

As for other ports and pins, check put the datasheet for your controller, they're really useful to people who can understand them! :)


body:
The datasheets for the AVR microcontrollers are reasonably good to read. Just Google for the exact controller on your Arduino (eg. ATmege328) and find the "Complete" datasheet on the *atmel.com* website. Don't download the "Summary", it doesn't include a lot of information. Download the datasheet from atmel.com, that is the only location with the most recent documentation.

There are three registers used in basic IO (check the chapter called "I/O-Ports"):

Where *n* is a port identifier, a letter ranging from A, B, C, ... depending on the number of IO pins your controller has. Each bit in each register represents a single GPIO pin (yes, you need some basic knowledge on binary to fully understand this).

- **DDR***n*, Data Direction Register: This basically configures a pin for either input (0) or output (1).
- **PORT***n*, Port n Data Register: When a pin is set as output, the related bit toggles the output pin high (1) or low (0). When configured as input, this enables a weak pull up resistor on the output pin.
- **PIN***n*,  Port n Input Register: Use this register to read the current level on a pin that is configured as input.


message:
How do I figure out if my board is approaching end of life?

I have a uno that I have been using for 3 years now. I will be using it again in a rather critical project in which failure on the part of the board could be rather expensive and dangerous. So, I would like to be sure that the board is not approaching end of life or going to fail anytime soon. Is there any reliable way to figure out how long the board will function without failing or reduction in performance?

body:
Unfortunately, there isn't much way to really determine "wear" in the context of solid-state electronics.

Probably the things that are most likely to fail are the electrolytic capacitors and the connectors.

---

First, if you're using an ATmega CPU for something that could possibly injure someone **CONTACT ATMEL AND TALK ABOUT SAFETY PRECAUTIONS**. The ATmega CPU used in most of the arduino models is *not* rated for use in such situations.

In EVERY datasheet:
> Atmel products are not intended, authorized, or warranted for use as components in applications intended to support or sustain life.

Now, realistically, this is probably *mostly* lawyer repellent, but you should still take appropriate precautions.

Really, while there isn't anything on a common arduino board that really wears out except the connectors, *why are you trying to save $30 at a potential huge cost?* Just buy a new board.

I'd also strongly reccomend you chose a board with a SMT ATmega328P, since that removes the IC socket contacts from the list of concerns. If possible, also remove the pin-headers, and solder wires to the board directly. Try to minimize connectors, since they are frequent points of failure.


body:
One of the sections of the Arduino that is likely to become unreliable over time is its memory. There are [three pools of memory][1] in the microcontroller used on avr-based Arduino boards:

- Flash memory (program space), is where the Arduino sketch is stored.
- SRAM (static random access memory) is where the sketch creates and manipulates variables when it runs.
- EEPROM is memory space that programmers can use to store long-term information.

The memory is one part of the board that can be checked and verified, and thus evaluated for reliability/health. A very basic way to check memory would be to write a certain 8-bit pattern (byte character) over every address in the memory and then read the value present from every address. If the value that was written matches the value that is read, then that specific 8 bit block in memory is functioning correctly at the present moment.

Wear in ROM memory usually occurs in a blockwise pattern i.e. n*8-bit blocks become degraded over time. So, for a 2K byte ROM chip, the health of the chip can be estimated by writing and reading from every byte on the chip, and calculating the percentage of correctly functioning blocks. If the percentage of failed blocks is significant (15%-20%), that means that the memory is likely to fail soon.

The test code can be written using separate methods for each of the memory sections.

### SRAM
Any variables declared statically or dynamically are allocated on the SRAM. So, we could declare a large character array (~2000) and fill every element with 255 (all bits 1). Then, we could attempt to read each of those elements and see if the value being read is indeed 255.

### EEPROM
The EEPROM can be manipulated using the [EEPROM library][2]. The library provides functions to read and write from specific locations in the EEPROM. So, all memory addresses can be tested by simply looping over the entire memory
space. *This operation will require 500 writes and reads.*

Depending on the board usage, EEPROM is most likely to fail first but is not critical to board operation.

### Flash
Data can be stored on the flash memory using the [`PROGMEM`][3] directive. Similar to SRAM, a large array can be declared and initialized here. Then, values can be read and checked.

  [1]: http://arduino.cc/en/Tutorial/Memory
  [2]: http://www.arduino.cc/en/Reference/EEPROM
  [3]: http://www.arduino.cc/en/Reference/PROGMEM


message:
What is the best way to unit test my code without controller?

I want to unit test my Arduino code. Ideally, I want to execute and test my code without uploading it to the board. What tools or libraries can help me with this?

There is an [Arduino emulator][1] in development which could be useful, but it doesn't yet seem to be ready for use.

  [1]: http://radpartbrainmat.blogspot.in/search/label/arduemu

body:
Have you looked at the AVR simulator that's part of [Atmel Studio][1]? Considering Atmel designed the processor, the simulation may very well be running the HDL that was used to produce the MCU itself.

I suspect if you're doing something involved enough to be using unit-testing, you should probably stop thinking of your device as an "Arduino", but rather "An ATmega MCU on a PCB". There are **much** more information and tools available about ATmega CPUs in general then Arduinos.

  [1]: http://www.atmel.com/microsite/atmel_studio6/debugging_simulation.aspx


body:
You can easily simulate your Arduino code using the famous Proteus ISIS.
You just will have to search for the specific Arduino simulation library for Proteus.

*Here you a small **tutorial** of how to make this thing done:*

**First**, identify the path the Arduino IDE generates the hex file to?
for example if you are using the official IDE you will find the hex file location in the "arduino IDE path/lib/preferences.txt"
Or if you are using Arduino ERW which I recommended the most on windows! So you can simply open the output folder by "Sketch > Copy HEX file as path".

**Second**, download the Arduino library from [Here][1]. Then copy `ARDUINO.LIB` and `ARDUINO.IDX` to folder "library" in the install directory Proteus.

**Third**, open ISIS and you should be able to find the component.

Please find this image of the worksheet after finishing the above steps, and simulation works just fine!
![Simulating Arduino Uno on Proteus ISIS][2]

And as a head start for you, please find this small memo I prepared for the **Arduino Uno Pins Layout**:

    0-14: I/O
    A0-A5: Analog

    We can use analog as digital:
    =============================
    Pinout:
    00: Rx  | Can't be used as I/O if I wrote in the code Serial.begin
    01: TX  |
    02: Interrupt
    03: Interrupt & PWM
    04:
    05: PWM
    06: PWM
    07:
    08:
    09: PWM
    10: PWM & SPI
    11: PWM & SPI
    12: SPI
    13: SPI
    A0:
    A1:
    A2:
    A3:
    A4: TWI
    A5: TWI

  [1]: https://www.mediafire.com/?q2g7la3dfftfk2r
  [2]: https://i.stack.imgur.com/moWEA.png


body:
I always try to isolate the hardware logic from the rest of the domain logic.

Classes (or whatever) from domain logic can be programmed in c++ (with the known arduino restrictions like exceptions or std lib) and can be tested with gtest.
When these classes are tested, simply instance from arduino program excluding the main with tests.

If your project is pure hardware this solution will not help you very much, but if you have your own algorithms, protocols...etc, test them with Google test will save you hours of on board testing and memory problems with unexpected results and your software will gain in quality.


message:
What's the best way to put in a database sensors data's

I have not already started to try but I'm a good webmaster and I'm just asking which way is more suitable for sending and keeping data from sensors and I/0 state in a database.

Here are some points:

 -  Post versus get
 - MySQL or others types
 - Security layers
 - Graphics render of data's (google API?)
 - PHP, ruby, JavaScript...
 - Able to send data request's to Arduino's
 - Ethernet shield, wifi, I2c ???
 - Access via Android app...

Anyway, the goal here is to know pros and cons of integrate all my Arduino through database.

body:
It depends on your skills and what you have in your Arduino "box".
Let's assume you have an ethernet or WiFi shield.

I would go with a PHP script (I'm a PHP dev, but any language will fit) that accepts POST requests sent by the board and store them in a SQLite db.

**Why SQLite instead of MySQL?** Well, it's just a matter of data portability. You copy the SQLite file or send it via email and you're done: there are plenty of clients out there to read your db, in *nix based machines is frequently integrated in the OS.

MySQL requires a sort of "infrastructure" to be written/read.


message:
How to prevent breaking my Arduino by mistake?

What is the best practice to make my Arduino circuit more robust against prototyping mistakes (like shorting pins)? I don't want the controller to release its blue magic smoke while experimenting with it, what precautions can I make while designing a circuit?

body:
I don't know if there's *one* best practice, but the following might be helpful:

 - Limit the voltage on input pins to 5.5 V maximum.
 - Do not short IO pins.
 - Use pullup or pulldown resistors when conecting switches or pushbuttons.
 - Respect the current limits (for each pin and in total). Use resistors.
 - The Arduino is just the brain, not the power station. If you have to drive higher loads, use simple transistors, Darlington arrays, etc.


body:
Not best practices, but an alternative approach:

Consider the [Ruggeduino][1] instead of a standard Arduino. At a price ($39.95) comparable with the equivalent Arduino, the Ruggeduino offers:

 - Resettable fuse on each GPIO pin, i.e. all GPIO pins are protected from short-circuit to ground or other pins
 - All GPIO pins withstand 24 Volts
 - Reverse voltage protection (-30 V) on Vin
 - Microcontroller overcurrent protection
 - 3.3V and 5V outputs on the board are over-current and short-circuit protected

Besides the above points specific to the question, the boards are designed to survive harsh environments and various mistakes. Also, the clock is more precise than on the Arduino.

  [1]: http://ruggedcircuits.com/html/ruggeduino.html


body: Don't move any wires with the power on. Way too many boards are damaged that way.


message:
Can I program for Arduino without having a real board?

I would like to start the development of some basic Arduino projects but I don't own an Arduino board yet. Is there a way I can write my code and emulate/test it using a desktop computer so after my board arrives I just have to upload and run my project on it?

body:
There are a whole slew of Arduino simulators out there, many free, and some paid products as well.

 - The [CodeBlocks][1] Arduino development environment includes a free Arduino simulator, still under development but functional.
 - [Simuino][2] simulates the Arduino Uno and Mega pins - not a pretty-looking realistic simulator, but it works.
 - The Python based [Arduino Simulator][3] is another option, that plays well with the official IDE
 - Virtronics [Simulator for Arduino][4] looks promising, but I don't see why I would pay $14.99 for it, when I could buy one or more actual Arduino clones for that price

Many other Arduino simulators are out there if you search, and new ones are being announced, even crowdfunded, all the time.

  [1]: http://arduinodev.com/codeblocks/
  [2]: https://sites.google.com/site/adcajo
  [3]: http://sourceforge.net/projects/arduinosim/
  [4]: http://www.virtronics.com.au/Simulator-for-Arduino.html


body:
Yes, you can, try using [Proteus ISIS][1] for simulating your code...

For full emulation of Arduino, there is a shareware program called [VBB (Virtual BreadBoard)][2], I tried it too and it was nice.

**Edit:** You can check my detailed tutorial [**here**][3] on how to simulate on Proteus ISIS

  [1]: https://www.labcenter.com/
  [2]: http://www.virtualbreadboard.com/
  [3]: https://arduino.stackexchange.com/questions/56/what-is-the-best-way-to-unit-test-my-code-without-controller/175#175


body:
I like to use [circuits.io aka TinkerCAD][1] for this.

It's cloud based and has some nice features including PCB design and collaboration.

IMO the Arduino simulation and capability is impressive and intuitive.

  [1]: https://www.tinkercad.com/learn/circuits


body:
You can use [Yenka](http://www.yenka.com) (free for home use) to simulate Arduino, PIX, PIXACE and other boards with digital, analog and serial I/O. It provides a lot of components and sample projects.

Screenshot:

![Yenka Arduino simulation][1]

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


body:
Virtualbreadboard has a new VBB4Arduino 'Two Arduino's' edition which includes BOTH a JVM Arduino emulator AND a AVR Instruction set simulator with examples that cover almost all of the Arduino distribution examples and a bunch of peripheral hardware - LCD's, WS2812 Neo LEDS, Motors, Servo's, Logic Analyser and more.

http://www.virtualbreadboard.com

Disclaimer: I am the author of Virtual Breadboard


body:
Be aware that no simulator will reproduce real-life situations. There have been plenty of posts on the Arduino forum about problems with code or electronics, which turn out to be something subtle, such as:

* Timing issues
* Race conditions (related/dependent events not always happening in the same order)
* Voltage levels, eg. floating input pins
* Driving motors which drop the Arduino voltage enough that it resets
* Not having decoupling capacitors
* Input pins being in an "undefined" state (eg. 2.5V on a pin where 2 or less V is LOW and 3V or more is HIGH)
* Problems with interrupt handlers, such as variables not being declared volatile
* Voltage spikes due to not having flyback diodes on motors
* The processor resetting once more than 10 LEDs are turned on because the current draw exceeds the amount the hardware can supply
* Interrupt handlers taking 10 µS to process an interrupt when only 9 µS is available.

By their nature simulators can't reproduce all of this. Even if they could, would you think to toggle the "insert random noise from motors" option?

---

As for getting ready for the board to arrive, download the IDE and start programming. You can get libraries installed, code written and free of syntax errors, organize it neatly, and be generally ready for the big day when the hardware is in your hands.

---

Have fun and enjoy experimenting with your Arduino!


body:
Plenty of options exist in the world of electronics simulators, but [circuits.io aka TinkerCAD][1] is probably the most versatile one out there.

- You can compose your circuit on a virtual breadboard which looks just like real.
- You can actually watch a LED blinking or press a button during real-time simulation rather than struggling with abstract waveforms.
- You can combine digital devices like a 555 timer or shift registers with (interactive) analog components like resistors and LEDs.
- You can program an Arduino and simulate the microcontroller together with your analog circuit around it.
- You can debug an Arduino: when the simulator reaches your breakpoint, the simulation is paused and you can easily check every variable in your code and every voltage or current in your circuit.
- You can use and observe different communication protocols like UART, I2C and SPI.
- You can pause the simulation in the middle of an I2C sequence by putting a breakpoint in the driver code (e.g. interrupt service routine for I2C events)
- It's FREE!

[![Example][2]][2]

This is an example circuit that has with an IR Remote and an LCD Screen.

Disclaimer: We are the makers of 123D Circuits

  [1]: https://www.tinkercad.com/learn/circuits
  [2]: https://i.stack.imgur.com/XIkP1.png


body:
You could e.g. use my simulator.
It is especially suitable for PLC-like applications, where multitasking is achieved by cyclic evaluation of interconnected circuit-like objects: Timers, Markers, Latches, Oneshots and Registers.
You can use it to simulate your controlled system as well, as becomes clear from the examples in the download. It has modest visualisation capacities, can draw timing charts, and allows you to access and alter c.q. force all variables in real time during a running simulation. Also you can freeze time. When you're satisfied with the behavior of your control it generates the C code to be uploaded to an actual Arduino.

https://pypi.python.org/pypi/SimPyLC


body:
I believe this [website][1] has a list of both emulators and simulators along with their price and availability.

Update:

Since some users mentioned there are broken links in that website, here's a selection of emulators I found. Note that some descriptions may have been taken from the mentioned link:

 - [Emulino][2]: Is an open source linux based software in early development that emulates Arduino-specific MCUs.

 - [Emulare][3]: is a general purpose hardware emulator. It aims to provide a central interface to build electronic simulations for embedded software development. At present emulare focuses on the ATMega line of microcontrollers (Arduino UNO has the ATMega processor).

 - [SimAVR][4]: is a new AVR simulator for linux, or any platform that uses avr-gcc. The simulator loads ELF files directly, and there is even a way to specify simulation parameters directly in the emulated code using an .elf section. It supports emulation of many ATMega processors and it is mentioned that it's easy to even add new ones.

 - [Amtel Studio][5]: This doesn't seem to mention the term emulation, but it is a sophisticated IDE to debug your code for many platforms specially Arduino. Atmel Studio 7 features seamless one-click import of projects created in the Arduino development environment. Your sketch, including any libraries it references, will be imported into Studio 7 as a C++ project. Once imported, you can leverage the full capabilities of Studio 7 to fine-tune and debug your design. Atmel Studio 7 fully supports the powerful embedded debugger on the Arduino Zero board. For other Arduino boards, shield-adapters that expose debug connectors are available, or switch to one of the many available Xplained-Mini/PRO boards to fully leverage the Atmel HW eco-system.

You can still use simulators such as [EasyEDA][6] to test your code and in most cases be able to run it on the device. But note that given the nature of electronic components, you may have to provide external resistors, capacitors etc to get the expected results.

  [1]: http://www.smashingrobotics.com/arduino-simulators-lineup-start-developing-without-real-board/
  [2]: https://github.com/ghewgill/emulino
  [3]: http://emulare.sourceforge.net/
  [4]: https://github.com/buserror/simavr
  [5]: http://www.atmel.com/tools/ATMELSTUDIO.aspx
  [6]: https://easyeda.com/