# Question
Title: 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) 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?**
2. **Why is the problem intermitent?** Why does it happen sometimes and others it doesn't?
3. **How can I fix that problem?** Is there a simple change to the Severino design that would fix that?

# Answer
**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.
> 3 votes

---
Tags: severino, reset
---


# Question
Title: Arduino Uno R2 and Ethernet Shield R3 compatibility
I bought an Ethernet Shield R3 for my Arduino Uno R2, 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?

# Answer
> 4 votes
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.

>

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

# Answer
> 1 votes
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.

---
Tags: ethernet, arduino-uno, shields
---


title: Assembly on the Arduino: IO registers

text:
# Question
Title: 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, 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.

# Answer
> 8 votes
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.

# Answer
> 1 votes
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! :)

---
Tags: software, avr-toolchain
---


# Question
Title: 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.

# Answer
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

```
> 11 votes

---
Tags: compile, sketch-size, avr-gcc, gcc
---


# Question
Title: 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?

# Answer
> 8 votes
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. 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:

There is also the Bootloader, 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. This is the documentation for the MCU that basically forms the "Arduino". It should address what seems to be misconceptions.

# Answer
> 6 votes
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.

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.

---
Tags: arduino-uno, firmware
---


# Question
Title: 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.

# Answer
> 4 votes
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.

---
Tags: web-service
---


# Question
Title: Is there an Arduino simulator that runs on Mac OS X?
I need to simulate my Arduino project with other circuit components before implementing the project. Is there a decent simulator that runs on Mac platform?

# Answer
There is a decent program called Simulator for Arduino made by Virtronics. Although it is made to run only in windows, you could run it in a WINE environment. WINE allows windows programs to be ran in Mac and Linux OS.
> 3 votes

---
Tags: mac-os, simulator
---


# Question
Title: 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?

# Answer
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.
> 8 votes

# Answer
One of the sections of the Arduino that is likely to become unreliable over time is its memory. There are three pools of memory 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. 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` directive. Similar to SRAM, a large array can be declared and initialized here. Then, values can be read and checked.
> 4 votes

---
Tags: arduino-uno, safety, reliability
---


# Question
Title: 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?

# Answer
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 ), 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 votes

# Answer
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 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`, which I believe would make it easy enough to use through `ser2net`, which exposes a serial-port as a socket.
> 0 votes

---
Tags: arduino-uno
---


# Question
Title: Does Arduino Uno R3 require cooling in a closure?
I was looking at getting an enclosure to house my Arduino Uno R3, but I'm not sure if I should also attach a fan. Does anyone have experience with this? It doesn't look like much heat is being generated, but with no ventilation except some slits in the enclosure, there won't be much air circulation without a fan. My concern with adding a fan was the fact that I'd need to power it.

# Answer
The only times I had an AVR run hot was when I applied reverse power to it. You'll be fine without a fan for the Arduino board itself, as long as you don't run power hungry peripherals from it.

Probably the only thing you really need to check (apart from absolute maximum ratings: 40mA max per IO pin and 200mA max for the whole microcontroller) is the on board voltage regulator (usually three pin device with a heat sink soldered down to the PCB) if you power it from a voltage \> 7V or so.
> 16 votes

# Answer
No, You shouldn't need any type of cooling device such as a fan as long as the case has a few holes in order to allow the heat to rise out of the case. I do not recommend using cases that are completely sealed, unless you are using it in an environment that has things that could hard the Arduino such as ROVs or Nuclear waste facility (although I don't know why you would be at one in the first place).
> 5 votes

---
Tags: arduino-uno, enclosure
---


# Question
Title: What are the steps involved in porting an Arduino library?
I want to use the Adafruit CC3000 and its Arduino libraries on another platform. In this case it's the Arduino pin compatible PSOC4 Pioneer Kit. This is an ARM Cortex M0 based platform.

My question is: How would I go about porting a library like this? What are the steps, key files etc?

One obvious issue is that PSOC Creator does not readily support C++.

One positive might be that the Arduino Due board is based on the Atmel SAM3X8E ARM Cortex-M3 CPU.

NOTE: If you think this question is off topic; please head over to this question on Arduino Meta to voice your opinion on whether questions on Arduino Compatible devices are appropriate for this list.

# Answer
> 10 votes
I did essentially the same thing with getting the Adafruit ST7735 library working in chipKIT. I started a support thread here which can lead you through my process.

I tackled it the same way I do general programming:
1-» Copy over Libraries, get it so your compiler can actually SEE them.
2-» Start trying to compile and then triage errors from the "top level" down:
3-» Look for stlib functions you recognize as should be working and fix those.
4-» Look for AVR specific code and comment those out. I normally also add my initials and a comment: `ckck - bitbanging SPI`, so I can search for these later.
Repeat 3 and 4 until it works or you quit. :)

Reach out to the forums for your target; they might have been there done that -- or like in my case, you introduce them to something that they want, so they dive in and help.

---
Tags: library
---


# Question
Title: Is my ATmega broken, and would replacing it with another break that one, too?
I was communicating between my computer and my Arduino Uno R3 through Bluetooth using this Bluetooth module. The connector I use has a red wire where it connects to GND, and a black wire where it connects to +5V.

> ```
>                 ↓        ↓  to Uno ↓       ↓
>                +5V      GND       pin 0  pin 1
>
> ```

I forgot this one time when I connected the Bluetooth module to the Uno, so the polarity was reversed. This fried the Bluetooth module.

After getting a new module, I discovered that the Uno was apparently fried too. Plugging a USB cable into the Uno made the little green integrated LED turn on, but that was all that happened; none of the pins put out any electricity. When I tried to upload a program, it gave the infamous `avrdude: stk500_getsync(): not in sync: resp=0x00` error. I could upload programs to my other Uno fine, and I could not upload to the broken Uno on my other computer.

Two of the Arduino experts I know told me that the ATmega328 chip might be the only broken part. Is this likely to be the case? I have an Uno R2 with a working ATmega328. Would temporarily replacing the R3's ATmega with that R2's ATmega have a change of damaging anything?

# Answer
Besides breaking a pin while removing the IC from its socket, or static electricity during manipulation, I don't see what could fry the ATmega.

However, it is possible that the R2 ATmega has a different bootloader and that may be an issue.

If I was you I would just remove the ATmega from the R3 board and test it on a breadboard (don't need a lot of components to do that); at least that could tell you if it is fried or if it is the R3 board that is fried...
> 7 votes

---
Tags: arduino-uno, atmega328
---


# Question
Title: What are the AREF, IOREF, and the unlabeled pin next to IOREF on the Uno R3?
There are some pins on the Arduino which I haven't been able to find out anything about:

* `IOREF`
* `AREF`
* An unlabeled one next to `IOREF`

What are they?

# Answer
**AREF:**

This is the voltage reference analog-to-digital converter (ADC). It can be used instead of the standard 5V reference for the top end of the analog spectrum – for example, if you wanted to use the ADC to monitor a signal that had a 0-1.5 volt range you could get the full scale of the ADC by connect AREF to a 1.5V signal. **DO NOT CONNECT A SIGNAL OUTSIDE THE 0V TO 5V RANGE!**

Note that in order for this to work, you must run `analogReference(EXTERNAL);` before using `analogRead()`. Also:

> After changing the analog reference, the first few readings from analogRead() may not be accurate.

Fore more information, see AnalogReference.

**IOREF:**

This is a voltage corresponding to the i/o of that board, for example an Uno would supply 5v to this pin, but a Due would supply 3.3v. Sending a signal to this pin does nothing.

**Unlabeled pin:**

This pin is unused, but is there to ensure compatibility with future products. It is not connected to anything on any R3 boards I have seen.
> 32 votes

# Answer
Concerning the `AREF` pin, you have to remember that the Arduino comes with a 10bit ADC (Analog-Digital-Converter), which converts incoming voltages between 0V and 5V to integer values between 0 and 1023. This results in a resolution of roughly 4.8 mV.

If a sensor only delivers a lower maximum voltage, it is resonable to apply this voltage to the `AREF` pin, just in order to obtain a higher resolution.
> 14 votes

---
Tags: pins, arduino-uno
---


# Question
Title: What is the difference between the revisions of the Arduino Uno board?
There are three different revisions of the Arduino Uno. What changed in each revision?

# Answer
> 11 votes
Here is a summary from the official site:

> Revision 2 of the Uno board has a resistor pulling the 8U2 HWB line to ground, making it easier to put into DFU mode.
>
> Revision 3 of the board has the following new features:
>
> * 1.0 pinout: added SDA and SCL pins that are near to the AREF pin and two other new pins placed near to the RESET pin, the IOREF that allow the shields to adapt to the voltage provided from the board. In future, shields will be compatible with both the board that uses the AVR, which operates with 5V and with the Arduino Due that operates with 3.3V. The second one is a not connected pin, that is reserved for future purposes.
> * Stronger RESET circuit.
> * Atmega 16U2 replace the 8U2.

A more detailed list of changes can be found here.

## R2:

* The rotation of the ATMEGA8U2 (the little chip near the USB port) was changed by 45 degrees.
* Four solder pads (JP2) were added, connecting to pins PB4 to PB7 of the USB ATMEGA."
* Instead of R1's solder pads, R2 adds header pins to the USB ATMEGA ICSP.
* An LED connected to pin 13 was added. It turns on when pin 13 is `HIGH`, off when `LOW`.
* The main microchip was changed from an ATmega168 to an ATmega328.
* A resistor was added between the DTR (HWB) line and the ATMEGA PD7 pin.

## R3:

* The rotation of the ATMEGA8U2 was changed back by 45 degrees.
* The ATMEGA8U2 was changed to an ATMEGA16U2.
* A diode was added, wired from +5vdc to the reset pin, cathode to +5vdc.
* The 8 pin connector that contains Arduino pins 8 was changed to 13, GND and AREF for a 10 pin connector. The extra 2 pins are connected to AD4/SDA and AD5/SCL. Also, the 6 pin connector that has the reset pin connected to it changed to an 8 pin connector. One of the new pins on this header is the IOREF pin that allows shields connected to the board to adapt to the voltage of the board. The second pin is not connected and reserved for future use.

# Answer
> 5 votes
### User Side Changes

* Both revision 2 and 3 boards add four solder pads (JP2) connecting to pins PB4 to PB7 of the USB ATMEGA.
* Revision 2 and 3 boards are both supplied with header pins in the USB ATMEGA ICSP header rather than just solder pads in the Arduino Uno.
* The revision 3 board changes the 8 pin connector that contains Arduino pins 8 to 13, GND and AREF for a 10 pin connector. The extra 2 pins are connected to AD4/SDA and AD5/SCL. These are the two analog input pins that can be used for I2C.
* Revision 3 boards change the 6 pin connector that has the reset pin connected to it to an 8 pin connector. One of the new pins on this header is the IOREF pin that allows shields connected to the board to adapt to the voltage of the board. The second pin is reserved for future use.

### Electronics Based Changes

* The Arduino Uno and Arduino Uno revision 2 both have an ATMEGA8U2 USB microcontroller on board – this is upgraded to an ATMEGA16U2 on the revision 3 board.
* Revision 3 adds a diode across the USB ATMEGA reset pin pull-up resistor.
* Both revision 2 and 3 boards add a 1k pull-down resistor to the DTR (HWB) line coming from the USB ATMEGA microcontroller – from the PD7 pin.
* The Arduino Uno and Arduino Uno revision 2 both have a LED and resistor connected in series on Arduino pin 13. The revision 3 board buffers this LED/resistor through a unity gain op-amp. This is the spare op-amp that was unused on previous boards.

### Sources:

1. http://startingelectronics.com/articles/arduino/uno-r3-r2-differences/

---
Tags: arduino-uno, revisions
---


# Question
Title: Connecting breakout board to Arduino with UART
I'm using a DigiX (Arduino Due based 3.3V) board to connect to a GPRS/GSM SIM908 breakout board. The SIM908 EVB board has the following pins on its RS232:

I've got all three UART TX lines hooked up to the RX Lines (and RX to TX) on my Arduino but the board keeps resetting, which I would guess is some sort of voltage issue (I turned the board off immediately). However there are three MAX3232s on the underside of the board, which I thought would have made it so I could just connect the lines directly to the Arduino. Does anyone know why this might be happening or how to properly connect these two devices?

Additional info:

Pinout of the DigiX.

Schematic of the DigiX.

(The below links are in Chinese):

Here is a SIM908 Hardware guide.

The full schematic of the breakout board.

# Answer
> 5 votes
Both the DigiX and the SIM908 are natively 3.3V boards. They should be able to connect to each other directly.

For some reason, the SIM908 breakout seems to only offer RS232 level serial outputs for the GPRS and GPS. On U3 (the SIM908 module itself) Pins 68/71 offer 3.3V levels for the GPRS (GPRS-TXD and GPRS-RXD) and 15/16 offer 3.3V levels for the GPS (GPS-TXD and GPS-RXD).

These are converted to RS232 levels by the MAX3232 and presented on J3 and J13. I can't see any point where the 3.3V signals are presented on a connector.

You could either:

* Breakout the 3.3V signals onto connectors by modifying the SIM908 breakout board.
* Build a level converter to take the 3.3V signals from the DigiX to RS232 and then connect them as before.

You may have damaged the DigiX board connecting RS232 levels directly to it however. The ARM based Arduinos are far less tolerant of voltage abuse than the ATmega based Arduinos.

---
Tags: serial, arduino-due
---


# Question
Title: Is it possible to find the time taken by millis?
The function `millis` would be running in the span of 100+ microseconds or less. Is there a reliable way to go about measuring the time taken by a single millis call?

One approach that comes to mind is using `micros`, however, a call to `micros` will include the time taken by the function call of `micros` itself as well, so depending on how long micros takes, the measurement for `millis` may be off.

I need to find this as an application I am working on requires accurate time measurements for every step taken in the code, including `millis`.

# Answer
If you want to know *exactly* how long something will take, there is only one solution: Look at the disassembly!

Starting with the minimal code:

```
void setup(){};

volatile uint16_t x;
void loop()
{
  x = millis();

}

```

This code compiled and then fed into `avr-objdump -S` produces a documented disassembly. Here are the interesting excerpts:

`void loop()` produces:

```
000000a8 <loop>:
  a8:   0e 94 a7 00     call    0x14e   ; 0x14e <millis>
  ac:   60 93 00 01     sts 0x0100, r22
  b0:   70 93 01 01     sts 0x0101, r23
  b4:   80 93 02 01     sts 0x0102, r24
  b8:   90 93 03 01     sts 0x0103, r25
  bc:   08 95           ret

```

Which is a function call (`call`), four copies (which copy each of the bytes in the `uint32_t` return value of `millis()` (note that the arduino docs call this a `long`, but they are incorrect to not be explicitly specifying the variable sizes)), and finally the function return.

`call` requires 4 clock cycles, and each `sts` requires 2 clock cycles, so we have a minimum of 12 clock cycles just for function call overhead.

Now, lets look at the disassembly of the `<millis>` function, which is located at `0x14e`:

```
unsigned long millis()
{
    unsigned long m;
    uint8_t oldSREG = SREG;
 14e:   8f b7           in  r24, 0x3f   ; 63

    // disable interrupts while we read timer0_millis or we might get an
    // inconsistent value (e.g. in the middle of a write to timer0_millis)
    cli();
 150:   f8 94           cli
    m = timer0_millis;
 152:   20 91 08 01     lds r18, 0x0108
 156:   30 91 09 01     lds r19, 0x0109
 15a:   40 91 0a 01     lds r20, 0x010A
 15e:   50 91 0b 01     lds r21, 0x010B
    SREG = oldSREG;
 162:   8f bf           out 0x3f, r24   ; 63

    return m;
}
 164:   b9 01           movw    r22, r18
 166:   ca 01           movw    r24, r20
 168:   08 95           ret

```

As you can see, the `millis()` function is fairly simple:

1. `in` saves the interrupt register settings (1 cycle)
2. `cli` turns off the interrupts (1 cycle)
3. `lds` copy one of the 4 bytes of the current value of the milli counter into a temporary register (2 clock cycles)
4. `lds` Byte 2 (2 clock cycles)
5. `lds` Byte 3 (2 clock cycles)
6. `lds` Byte 4 (2 clock cycles)
7. `out` restore interrupt settings (1 clock cycle)
8. `movw` shuffle registers around (1 clock cycle)
9. `movw` and again (1 clock cycle)
10. `ret` return from subroutine (4 cycles)

So, if we add them all up, we have a total of 17 clock cycles in the `millis()` function itself, plus a call overhead of 12, for a total of 29 clock cycles.

Assuming a 16 Mhz clock rate (most arduinos), each clock cycle is `1 / 16e6` seconds, or 0.0000000625 seconds, which is 62.5 nanoseconds. 62.5 ns * 29 = 1.812 microseconds.

Therefore, the total execution time for a single `millis()` call on *most* Arduinos will be **1.812 microseconds**.

---

AVR Assembly reference

As a side-note, there is space for optimization here! If you update the `unsigned long millis(){}` function definition to be `inline unsigned long millis(){}`, you would remove the call overhead (at the cost of *slightly* larger code size). Furthermore, it looks like the compiler is doing two unnecessary moves (the two `movw` calls, but I haven't looked at it that closely).

Really, considering the function call overhead is 5 instructions, and the actual *contents* of the `millis()` function is only 6 instructions, I think the `millis()` function should really be `inline` by default, but the Arduino codebase is rather poorly optimized.

---

Here is the full disassemby for anyone interested:

```
sketch_feb13a.cpp.elf:     file format elf32-avr

Disassembly of section .text:

00000000 <__vectors>:
    SREG = oldSREG;

    return m;
}

unsigned long micros() {
   0:   0c 94 34 00     jmp 0x68    ; 0x68 <__ctors_end>
   4:   0c 94 51 00     jmp 0xa2    ; 0xa2 <__bad_interrupt>
   8:   0c 94 51 00     jmp 0xa2    ; 0xa2 <__bad_interrupt>
   c:   0c 94 51 00     jmp 0xa2    ; 0xa2 <__bad_interrupt>
  10:   0c 94 51 00     jmp 0xa2    ; 0xa2 <__bad_interrupt>
  14:   0c 94 51 00     jmp 0xa2    ; 0xa2 <__bad_interrupt>
  18:   0c 94 51 00     jmp 0xa2    ; 0xa2 <__bad_interrupt>
  1c:   0c 94 51 00     jmp 0xa2    ; 0xa2 <__bad_interrupt>
  20:   0c 94 51 00     jmp 0xa2    ; 0xa2 <__bad_interrupt>
  24:   0c 94 51 00     jmp 0xa2    ; 0xa2 <__bad_interrupt>
  28:   0c 94 51 00     jmp 0xa2    ; 0xa2 <__bad_interrupt>
  2c:   0c 94 51 00     jmp 0xa2    ; 0xa2 <__bad_interrupt>
  30:   0c 94 51 00     jmp 0xa2    ; 0xa2 <__bad_interrupt>
  34:   0c 94 51 00     jmp 0xa2    ; 0xa2 <__bad_interrupt>
  38:   0c 94 51 00     jmp 0xa2    ; 0xa2 <__bad_interrupt>
  3c:   0c 94 51 00     jmp 0xa2    ; 0xa2 <__bad_interrupt>
  40:   0c 94 5f 00     jmp 0xbe    ; 0xbe <__vector_16>
  44:   0c 94 51 00     jmp 0xa2    ; 0xa2 <__bad_interrupt>
  48:   0c 94 51 00     jmp 0xa2    ; 0xa2 <__bad_interrupt>
  4c:   0c 94 51 00     jmp 0xa2    ; 0xa2 <__bad_interrupt>
  50:   0c 94 51 00     jmp 0xa2    ; 0xa2 <__bad_interrupt>
  54:   0c 94 51 00     jmp 0xa2    ; 0xa2 <__bad_interrupt>
  58:   0c 94 51 00     jmp 0xa2    ; 0xa2 <__bad_interrupt>
  5c:   0c 94 51 00     jmp 0xa2    ; 0xa2 <__bad_interrupt>
  60:   0c 94 51 00     jmp 0xa2    ; 0xa2 <__bad_interrupt>
  64:   0c 94 51 00     jmp 0xa2    ; 0xa2 <__bad_interrupt>

00000068 <__ctors_end>:
  68:   11 24           eor r1, r1
  6a:   1f be           out 0x3f, r1    ; 63
  6c:   cf ef           ldi r28, 0xFF   ; 255
  6e:   d8 e0           ldi r29, 0x08   ; 8
  70:   de bf           out 0x3e, r29   ; 62
  72:   cd bf           out 0x3d, r28   ; 61

00000074 <__do_copy_data>:
  74:   11 e0           ldi r17, 0x01   ; 1
  76:   a0 e0           ldi r26, 0x00   ; 0
  78:   b1 e0           ldi r27, 0x01   ; 1
  7a:   e2 e0           ldi r30, 0x02   ; 2
  7c:   f2 e0           ldi r31, 0x02   ; 2
  7e:   02 c0           rjmp    .+4         ; 0x84 <.do_copy_data_start>

00000080 <.do_copy_data_loop>:
  80:   05 90           lpm r0, Z+
  82:   0d 92           st  X+, r0

00000084 <.do_copy_data_start>:
  84:   a0 30           cpi r26, 0x00   ; 0
  86:   b1 07           cpc r27, r17
  88:   d9 f7           brne    .-10        ; 0x80 <.do_copy_data_loop>

0000008a <__do_clear_bss>:
  8a:   11 e0           ldi r17, 0x01   ; 1
  8c:   a0 e0           ldi r26, 0x00   ; 0
  8e:   b1 e0           ldi r27, 0x01   ; 1
  90:   01 c0           rjmp    .+2         ; 0x94 <.do_clear_bss_start>

00000092 <.do_clear_bss_loop>:
  92:   1d 92           st  X+, r1

00000094 <.do_clear_bss_start>:
  94:   ad 30           cpi r26, 0x0D   ; 13
  96:   b1 07           cpc r27, r17
  98:   e1 f7           brne    .-8         ; 0x92 <.do_clear_bss_loop>
  9a:   0e 94 f0 00     call    0x1e0   ; 0x1e0 <main>
  9e:   0c 94 ff 00     jmp 0x1fe   ; 0x1fe <_exit>

000000a2 <__bad_interrupt>:
  a2:   0c 94 00 00     jmp 0   ; 0x0 <__vectors>

000000a6 <setup>:
  a6:   08 95           ret

000000a8 <loop>:
  a8:   0e 94 a7 00     call    0x14e   ; 0x14e <millis>
  ac:   60 93 00 01     sts 0x0100, r22
  b0:   70 93 01 01     sts 0x0101, r23
  b4:   80 93 02 01     sts 0x0102, r24
  b8:   90 93 03 01     sts 0x0103, r25
  bc:   08 95           ret

000000be <__vector_16>:
#if defined(__AVR_ATtiny24__) || defined(__AVR_ATtiny44__) || defined(__AVR_ATtiny84__)
ISR(TIM0_OVF_vect)
#else
ISR(TIMER0_OVF_vect)
#endif
{
  be:   1f 92           push    r1
  c0:   0f 92           push    r0
  c2:   0f b6           in  r0, 0x3f    ; 63
  c4:   0f 92           push    r0
  c6:   11 24           eor r1, r1
  c8:   2f 93           push    r18
  ca:   3f 93           push    r19
  cc:   8f 93           push    r24
  ce:   9f 93           push    r25
  d0:   af 93           push    r26
  d2:   bf 93           push    r27
    // copy these to local variables so they can be stored in registers
    // (volatile variables must be read from memory on every access)
    unsigned long m = timer0_millis;
  d4:   80 91 08 01     lds r24, 0x0108
  d8:   90 91 09 01     lds r25, 0x0109
  dc:   a0 91 0a 01     lds r26, 0x010A
  e0:   b0 91 0b 01     lds r27, 0x010B
    unsigned char f = timer0_fract;
  e4:   30 91 0c 01     lds r19, 0x010C

    m += MILLIS_INC;
  e8:   01 96           adiw    r24, 0x01   ; 1
  ea:   a1 1d           adc r26, r1
  ec:   b1 1d           adc r27, r1
    f += FRACT_INC;
  ee:   23 2f           mov r18, r19
  f0:   2d 5f           subi    r18, 0xFD   ; 253
    if (f >= FRACT_MAX) {
  f2:   2d 37           cpi r18, 0x7D   ; 125
  f4:   20 f0           brcs    .+8         ; 0xfe <__vector_16+0x40>
        f -= FRACT_MAX;
  f6:   2d 57           subi    r18, 0x7D   ; 125
        m += 1;
  f8:   01 96           adiw    r24, 0x01   ; 1
  fa:   a1 1d           adc r26, r1
  fc:   b1 1d           adc r27, r1
    }

    timer0_fract = f;
  fe:   20 93 0c 01     sts 0x010C, r18
    timer0_millis = m;
 102:   80 93 08 01     sts 0x0108, r24
 106:   90 93 09 01     sts 0x0109, r25
 10a:   a0 93 0a 01     sts 0x010A, r26
 10e:   b0 93 0b 01     sts 0x010B, r27
    timer0_overflow_count++;
 112:   80 91 04 01     lds r24, 0x0104
 116:   90 91 05 01     lds r25, 0x0105
 11a:   a0 91 06 01     lds r26, 0x0106
 11e:   b0 91 07 01     lds r27, 0x0107
 122:   01 96           adiw    r24, 0x01   ; 1
 124:   a1 1d           adc r26, r1
 126:   b1 1d           adc r27, r1
 128:   80 93 04 01     sts 0x0104, r24
 12c:   90 93 05 01     sts 0x0105, r25
 130:   a0 93 06 01     sts 0x0106, r26
 134:   b0 93 07 01     sts 0x0107, r27
}
 138:   bf 91           pop r27
 13a:   af 91           pop r26
 13c:   9f 91           pop r25
 13e:   8f 91           pop r24
 140:   3f 91           pop r19
 142:   2f 91           pop r18
 144:   0f 90           pop r0
 146:   0f be           out 0x3f, r0    ; 63
 148:   0f 90           pop r0
 14a:   1f 90           pop r1
 14c:   18 95           reti

0000014e <millis>:

unsigned long millis()
{
    unsigned long m;
    uint8_t oldSREG = SREG;
 14e:   8f b7           in  r24, 0x3f   ; 63

    // disable interrupts while we read timer0_millis or we might get an
    // inconsistent value (e.g. in the middle of a write to timer0_millis)
    cli();
 150:   f8 94           cli
    m = timer0_millis;
 152:   20 91 08 01     lds r18, 0x0108
 156:   30 91 09 01     lds r19, 0x0109
 15a:   40 91 0a 01     lds r20, 0x010A
 15e:   50 91 0b 01     lds r21, 0x010B
    SREG = oldSREG;
 162:   8f bf           out 0x3f, r24   ; 63

    return m;
}
 164:   b9 01           movw    r22, r18
 166:   ca 01           movw    r24, r20
 168:   08 95           ret

0000016a <init>:

void init()
{
    // this needs to be called before setup() or some functions won't
    // work there
    sei();
 16a:   78 94           sei

    // on the ATmega168, timer 0 is also used for fast hardware pwm
    // (using phase-correct PWM would mean that timer 0 overflowed half as often
    // resulting in different millis() behavior on the ATmega8 and ATmega168)
#if defined(TCCR0A) && defined(WGM01)
    sbi(TCCR0A, WGM01);
 16c:   84 b5           in  r24, 0x24   ; 36
 16e:   82 60           ori r24, 0x02   ; 2
 170:   84 bd           out 0x24, r24   ; 36
    sbi(TCCR0A, WGM00);
 172:   84 b5           in  r24, 0x24   ; 36
 174:   81 60           ori r24, 0x01   ; 1
 176:   84 bd           out 0x24, r24   ; 36
    // this combination is for the standard atmega8
    sbi(TCCR0, CS01);
    sbi(TCCR0, CS00);
#elif defined(TCCR0B) && defined(CS01) && defined(CS00)
    // this combination is for the standard 168/328/1280/2560
    sbi(TCCR0B, CS01);
 178:   85 b5           in  r24, 0x25   ; 37
 17a:   82 60           ori r24, 0x02   ; 2
 17c:   85 bd           out 0x25, r24   ; 37
    sbi(TCCR0B, CS00);
 17e:   85 b5           in  r24, 0x25   ; 37
 180:   81 60           ori r24, 0x01   ; 1
 182:   85 bd           out 0x25, r24   ; 37

    // enable timer 0 overflow interrupt
#if defined(TIMSK) && defined(TOIE0)
    sbi(TIMSK, TOIE0);
#elif defined(TIMSK0) && defined(TOIE0)
    sbi(TIMSK0, TOIE0);
 184:   ee e6           ldi r30, 0x6E   ; 110
 186:   f0 e0           ldi r31, 0x00   ; 0
 188:   80 81           ld  r24, Z
 18a:   81 60           ori r24, 0x01   ; 1
 18c:   80 83           st  Z, r24
    // this is better for motors as it ensures an even waveform
    // note, however, that fast pwm mode can achieve a frequency of up
    // 8 MHz (with a 16 MHz clock) at 50% duty cycle

#if defined(TCCR1B) && defined(CS11) && defined(CS10)
    TCCR1B = 0;
 18e:   e1 e8           ldi r30, 0x81   ; 129
 190:   f0 e0           ldi r31, 0x00   ; 0
 192:   10 82           st  Z, r1

    // set timer 1 prescale factor to 64
    sbi(TCCR1B, CS11);
 194:   80 81           ld  r24, Z
 196:   82 60           ori r24, 0x02   ; 2
 198:   80 83           st  Z, r24
#if F_CPU >= 8000000L
    sbi(TCCR1B, CS10);
 19a:   80 81           ld  r24, Z
 19c:   81 60           ori r24, 0x01   ; 1
 19e:   80 83           st  Z, r24
    sbi(TCCR1, CS10);
#endif
#endif
    // put timer 1 in 8-bit phase correct pwm mode
#if defined(TCCR1A) && defined(WGM10)
    sbi(TCCR1A, WGM10);
 1a0:   e0 e8           ldi r30, 0x80   ; 128
 1a2:   f0 e0           ldi r31, 0x00   ; 0
 1a4:   80 81           ld  r24, Z
 1a6:   81 60           ori r24, 0x01   ; 1
 1a8:   80 83           st  Z, r24

    // set timer 2 prescale factor to 64
#if defined(TCCR2) && defined(CS22)
    sbi(TCCR2, CS22);
#elif defined(TCCR2B) && defined(CS22)
    sbi(TCCR2B, CS22);
 1aa:   e1 eb           ldi r30, 0xB1   ; 177
 1ac:   f0 e0           ldi r31, 0x00   ; 0
 1ae:   80 81           ld  r24, Z
 1b0:   84 60           ori r24, 0x04   ; 4
 1b2:   80 83           st  Z, r24

    // configure timer 2 for phase correct pwm (8-bit)
#if defined(TCCR2) && defined(WGM20)
    sbi(TCCR2, WGM20);
#elif defined(TCCR2A) && defined(WGM20)
    sbi(TCCR2A, WGM20);
 1b4:   e0 eb           ldi r30, 0xB0   ; 176
 1b6:   f0 e0           ldi r31, 0x00   ; 0
 1b8:   80 81           ld  r24, Z
 1ba:   81 60           ori r24, 0x01   ; 1
 1bc:   80 83           st  Z, r24
#if defined(ADCSRA)
    // set a2d prescale factor to 128
    // 16 MHz / 128 = 125 KHz, inside the desired 50-200 KHz range.
    // XXX: this will not work properly for other clock speeds, and
    // this code should use F_CPU to determine the prescale factor.
    sbi(ADCSRA, ADPS2);
 1be:   ea e7           ldi r30, 0x7A   ; 122
 1c0:   f0 e0           ldi r31, 0x00   ; 0
 1c2:   80 81           ld  r24, Z
 1c4:   84 60           ori r24, 0x04   ; 4
 1c6:   80 83           st  Z, r24
    sbi(ADCSRA, ADPS1);
 1c8:   80 81           ld  r24, Z
 1ca:   82 60           ori r24, 0x02   ; 2
 1cc:   80 83           st  Z, r24
    sbi(ADCSRA, ADPS0);
 1ce:   80 81           ld  r24, Z
 1d0:   81 60           ori r24, 0x01   ; 1
 1d2:   80 83           st  Z, r24

    // enable a2d conversions
    sbi(ADCSRA, ADEN);
 1d4:   80 81           ld  r24, Z
 1d6:   80 68           ori r24, 0x80   ; 128
 1d8:   80 83           st  Z, r24
    // here so they can be used as normal digital i/o; they will be
    // reconnected in Serial.begin()
#if defined(UCSRB)
    UCSRB = 0;
#elif defined(UCSR0B)
    UCSR0B = 0;
 1da:   10 92 c1 00     sts 0x00C1, r1
#endif
}
 1de:   08 95           ret

000001e0 <main>:
#include <Arduino.h>

int main(void)
 1e0:   cf 93           push    r28
 1e2:   df 93           push    r29
{
    init();
 1e4:   0e 94 b5 00     call    0x16a   ; 0x16a <init>

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

    setup();
 1e8:   0e 94 53 00     call    0xa6    ; 0xa6 <setup>

    for (;;) {
        loop();
        if (serialEventRun) serialEventRun();
 1ec:   c0 e0           ldi r28, 0x00   ; 0
 1ee:   d0 e0           ldi r29, 0x00   ; 0
#endif

    setup();

    for (;;) {
        loop();
 1f0:   0e 94 54 00     call    0xa8    ; 0xa8 <loop>
        if (serialEventRun) serialEventRun();
 1f4:   20 97           sbiw    r28, 0x00   ; 0
 1f6:   e1 f3           breq    .-8         ; 0x1f0 <main+0x10>
 1f8:   0e 94 00 00     call    0   ; 0x0 <__vectors>
 1fc:   f9 cf           rjmp    .-14        ; 0x1f0 <main+0x10>

000001fe <_exit>:
 1fe:   f8 94           cli

00000200 <__stop_program>:
 200:   ff cf           rjmp    .-2         ; 0x200 <__stop_program>

```
> 22 votes

# Answer
Write a sketch that millis 1000 times, not by making a loop, but by copy and paste. Measure that and compare it to the actual expected time. Mind you that that the results may vary with different versions of the IDE (and its compiler in particular).

Another option is to toggle an IO pin before and after the millis call, then measure the time for a very small value and a somewhat larger value. Compare the measured timings and calculate the overhead.

The most accurate way is to take a look at the disassembly listing, the generated code. But that is not for the faint of heart. You'll have to carefully study the datasheet how long each instruction cycle takes.
> 8 votes

# Answer
I second calling millis repeatedly and then comparing actual vs. expected.

There will be some minimal overhead, but it will diminish in significance the more times you call millis().

If you look at

```
C:\Program Files (x86)\Arduino\Arduino ERW 1.0.5\hardware\arduino\cores\arduino\wiring.c

```

You can see that millis() is very tiny at only 4 instructions `(cli is simply # define cli() \__asm__ \__volatile__ ("cli" ::))` and a return.

I'd call it about 10 million times using a FOR loop which has a volatile as the conditional. The volatile keyword will prevent the compiler from attempting any optimization on the loop itself.

I don't guarantee the following to be syntactically perfect..

```
int temp1,temp2;
temp1=millis();
for (volatile unsigned int j=0;j<1000000;++j){
temp2=millis();}
Serial.print("Execution time = ");
Serial.print((temp2-temp1,DEC);
Serial.print("ms");

```

my guess is that takes ~900ms or about 56us per call to millis. ( I don't have an aruduino handy ATM.
> 3 votes

---
Tags: time, millis
---


title: Code for one-time execution in Arduino

text:
# Question
Title: Code for one-time execution in Arduino
**Question:** Where do I put code if I want it to execute only once per Arduino startup?

**Background:** I tend to use my Arduino to perform tasks that should be executed once per power cycle. (For example, my robot should only drive forward *once* every time I turn it on--more than that, and it might fall off the table.)

The standard Arduino IDE "template" consists of a `loop()` and a `setup()` function. The `setup` code is run once per power cycle, and the `loop` is re-started every time it finishes.

I see two approaches to code "1 time tasks:"

## Method 1: "Loop once"

```
void setup() {
  //do setup stuff
}

void loop() {
  //do task

  while(1) ; //Repeat forever, preventing function from re-starting
}

```

## Method 2: "Setup only"

```
void setup() {
  //do setup stuff

  //do task
}

void loop() {
  //do nothing
}

```

**More detailed form of question:** Is one of these methods "better" from a hardware/software sense? (e.g. is there anything "special" about the `setup` function, like it can only run for so much time?)
And, if they are the same from a hardware/software perspective, is there a "best practice" or standard way of writing code for these situations in the Arduino community?

# Answer
> 14 votes
I'm kind of confused by your question. You ask where you want to put once-per-startup setup functions, and then discuss the setup function. *That's what the setup function is for.*

As such, one-time setup functionality goes in the setup function.

FWIW, if you look in the file that *calls* the `setup` and `loop` functions:

```
#include <Arduino.h>

int main(void)
{
    init();

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

    setup();
    for (;;) {
        loop();
        if (serialEventRun) serialEventRun();
    }
    return 0;
}

```

For all intents and purposes, the two options are completely identical. Either way, you get a empty busy-wait loop. Frankly, I'd expect the two different options to probably emit the same machine code anyways, so the whole thing is a non-issue.

Note:
`if (serialEventRun) serialEventRun();` appears to be a facility to allow you to attach a function that is called upon reception of serial data, but if you do not define a function `void serialEvent(){}` in your code, it will compile out completely and not be present in the produced machine code.

# Answer
> 6 votes
I usually go with Method 2, but end up doing this:

```
void setup() {
  //do setup stuff

  //do task
  init(); //Do start-up initialization steps
}

void init() {
  // do tasks on startup
}

void loop() {
  //do looping code
}

```

With the above setup it allows my code to be even more organized.

# Answer
> 5 votes
I would strongly prefer Method 2. If you ever plan to add code to handle input, output, etc, it's easy with Method 2 -- just fill in `loop()`, but requires reworking/refactoring in Method 1.

# Answer
> 3 votes
There is no time limit on the setup function. I prefer method 2 because the loop can be filled with whatever you need to later.

# Answer
> 1 votes
Definitely go with method two. That's what the setup function is there for. It's much easier to read as well. Anything in the `loop()` implies it will be run in a loop.

# Answer
> 0 votes
As most other answers, I would go for method 2.

But I would try to avoid the call, by Arduino library, to an an empty `loop()` that makes the Atmel consume "a lot" of current for nothing.

Edit:

As some comments pointed out though, using `delay()` in `loop()` will change nothing to power consumption.

Hence, if you would like to reduce power consumption once your `setup()` has run, you will have to play with Atmel sleep modes. You can take a look at this article that shows how to deal with sleep modes from your Arduino sketches; it does more than just putting the Atmel to sleep but it is a good (and simple) read if you want to play with sleep modes.

---
Tags: programming
---


title: Why is the regulator very hot?

text:
# Question
Title: Why is the regulator very hot?
We have an LED strip connected to output 6 and is powered by the Uno board itself. Shouldn't be drawing too much current, only have 10 elements on the LED strip. While this LED strip is connected to the Uno, I noticed that the regulator is getting very hot.

One thing we haven't done yet is to power the LED strips from an external source, which will be necessary since there will be many strips. At the moment, the students are simply trying to debug their program with the small strip.

# Answer
When a circuit is hot, it's very likely that it is drawing too much current. It may be a component that's getting more current than it's designed for, or a PCB track, or a wire.

So, before you do anything else, I strongly suggest that you get a DMM and measure the current drawn by the board when powering the led strip. Google for ways to measure current with a DMM, as it can be tricky if you never done it before.

Then, compare the value to those specified by the voltage regulator datasheet. The current should be within those values shown in the "Electrical Characteristics", and well below those from "Absolute Maximum Ratings".
> 5 votes

# Answer
If you power the Arduino with an external power supply the on board regulator has to *dissipate* the voltage difference between input and 5VDC at the total current you draw from the board.

As Klaus Warzecha wrote in an answer to another question

> The Arduino is just the brain, not the power station.

If the output voltage of your power supply is 12V, then the regulator will be dissipating 12-5V = 7 V at the total current drawn. Total dissipated power for eg. 150mA (just an estimate) would be P = V × I = 7 × 0.150 = 1W The regulator will be pretty hot from dissipating 1W.

Mind you that the current is not limited to 150mA, enough LEDs can easily increase current and power. If the regulator is stressed (often) enough, sooner or later it will fail. It is better practice to power any load directly from the external power supply, taking the higher voltage into account.
> 11 votes

# Answer
A regulator normally get hot when is driven a current near to the maximum that could be driven, and its a normal thing the regulator keep warm.

A normal regulator like LM7805 could work until 125 C°.

If you try to drive more current that it can probably it will burn, so, maybe its time to you change your power supply to an external one to keep safe your Arduino board.
> 7 votes

---
Tags: power, heat
---


# Question
Title: Why can't I declare a class in another tab in Arduino IDE?
I wanted to move some of my code out into a second tab in the Arduino IDE, to keep things better organised. At first, I only tried moving a function, and it seemed to work fine. I could call the function from the `setup()` function in my main tab, and there were no problems compiling or uploading.

However, I tried putting a whole class into the second tab, and suddenly it didn't work any more. For example:

**Tab 1:**

```
TestClass obj;

void setup()
{
    obj.init();
}

void loop()
{
    //...
}

```

**Tab 2:**

```
class TestClass
{
public:
    void init()
    {
        //...
    }
};

```

When I tried to compile this, it gave me the following errors:

```
tab1:1: error: 'TestClass' does not name a type
tab1.ino: In function 'void setup()':
tab1:5: error: 'obj' was not declared in this scope

```

Why does it recognise a function in another tab, but not a class? Is there a way to make it work in the Arduino IDE, or do I need to use an alternative like Eclipse?

# Answer
It is not possible to declare and use classes declared in one `.pde` file in another `.pde` file from within the Arduino IDE.

One workaround is to make the second file into a C++ source file (`.cpp`) and then add a `#include "<filename>"` directive in the beginning of the first file.

---

This code compiles correctly:

Tab 1:

```
#include "test.cpp"

TestClass obj;

void setup()
{
    obj.init();
}

void loop()
{
    //...
}

```

test.cpp :

```
class TestClass
{
public:
    void init()
    {
        //...
    }
};

```
> 17 votes

# Answer
The way the Arduino IDE works is that it compiles your code (the code you write in the IDE) as the "main" code. Then it pulls code from all of the libraries you have imported and compiles that along with the main code. To do what you are suggesting would require you to create a library for Arduino.

### Here is some more information on Arduino libraries:

http://arduino.cc/en/Guide/Libraries

### And here is some on how to create a library:

http://arduino.cc/en/Hacking/LibraryTutorial //this one is the easiest to understand imo
http://playground.arduino.cc/Code/Library
http://www.divilabs.com/2013/03/write-your-own-arduino-library.html#

Here is an example library I wrote https://github.com/jamolnng/Arduino/tree/master/libraries/ShiftRegister as you can see there is no problem with calling Arduino functions from the .cpp file (I know, I've tested the library)
> 6 votes

---
Tags: programming, arduino-ide, compile
---


# Question
Title: What I should be aware before I touch my Arduino?
Before you start to mess with a computer there are basic guidelines to be aware of, such as turn the power off and watch out for static electricity. What guidelines should I be aware of when I work with an Arduino board if I don't want to harm neither myself nor the board. The three kind of activity that requires touching the Arduino and what I'm asking about:

* Setting up wire, component layout or breadboard.
* Debugging a running setup.
* Moving, mounting up the board somewhere.

# Answer
> 14 votes
Turning the power off and taking proper static precautions also applies to Arduinos. Anorton's tip about not resting it on a conductive surface is also useful. Some other things to keep in mind:

* Double check the polarities of any connections you make.
* Keep a consistent wiring color code. Use red for power and black for ground.
* Calculate the expected current through all components before you apply power. Check the datasheet to make sure it's within safe limits.
* Calculate the heat dissipation for higher power components like power supplies and motor drivers.
* Connect and test one small part at a time, instead of in one big bang.
* Make sure the parts you buy expect the same voltage, or perform the appropriate conversion.

For keeping people safe:

* Know where the fire extinguisher is.
* Don't put cords where people can trip on them.
* Use a proper stand to hold your soldering iron, and keep pets and small children away.
* If your project has a propeller or something physically dangerous, build failsafes and kill switches into the system.
* Be careful to charge any batteries properly, and not let them overheat.
* Be careful what you touch while troubleshooting. Arduinos usually don't deal with very high voltages, but inductors and capacitors can build up higher charges than you expect, and hold it after power is removed.

# Answer
> 4 votes
One of the most common bad things I have seen is connecting LEDs directly to addition pins without a current limiting resistor.

Basically, in electronics there are a few main sources of problems. Too much current, too much voltage, overheating, and physical damage.

Too much current usually comes from shorting things, too much voltage(or reversed polarity) usually comes from not paying attention to what is being connected, overheating comes from too much current or not using a heatsink when you should be.

Basically, just think before you connect things and you'll be fine. Learn some basic circuit theory if you haven't already, get in the habit of knowing the ratings of the parts you want to use, and double check stuff before turning it on.

I like this list here of things not to do: http://ruggedcircuits.com/html/ancp01.html

---
Tags: safety
---


title: When to use different variable types?

text:
# Question
Title: When to use different variable types?
There are several different types in the Arduino programming language. They each have different applications that can use up the limited RAM in the Arduino. When should i use each?

# Answer
> 5 votes
One should appreciate that the Arduino is an Embedded Processor. *Specifically that it has limited resources of RAM and ROM(aka Flash/program space).*

Often is the case I see coding use the "int" defaultly. Almost sloppily. If that works great.

BUT!!!! You can run out of room REAL FAST with only 2K of RAM.

I would recommend that you size down your type to the minimum of what it needs to be describing it. One also gets a better understanding of what it really is and its limitations. There is no need for an array of int(16bits) from bytes that were recieved from the SPI, UART or I2C. Or a matrix of RGB's that consume 3 bytes each, being int's. You cut your capacity in half.

The pro/con: PRO: using default int everywhere makes it more inter changeable. The CON is that such interchangeability can lead to unintentional casting errors.

I would also recommend using C99 type def's which can be found at "avr\_stdint.html"\>http://www.nongnu.org/avr-libc/user-manual/group\_*avr*\_stdint.html" and elsewhere. It makes things vivid, regards to this aspect. Hence a "int" would be a "int16\_t", "unsigned long" be "uint32\_t" etc...

It is worth knowing that in some cases a byte or char can not be replaced with int8\_t, as such when used with string array functions. But they are still just as vivid.

# Answer
> 3 votes
An overview of the most commonly used variables:

* **byte**: uses one byte (8 bits), holds numbers from 0 to 255
* **char**: a signed byte
* **boolean**: uses 1 byte, but only holds a value of `true` or `false`
* **int**: uses 2 bytes, holds numbers from -32768 to 32767, mostly used in general programming. an `int` is what is known as a signed variable, where the last bit controls if it is negative or positive
* **long**: uses 4 bytes, holds numbers from -2147483647 to 217283648, it is also signed
* **long long**: uses 8 bytes, can hold -9223372036854775808 to 9223372036854775807, signed
* **float**: uses 4 bytes, holds decimals from -3.4028235E+38 to 3.4028235E+38.
* **double**: almost identical to `float`
* **string**: an array of chars that represent text
* **String**: not to be confused with `string`, this is a class that holds text data with extra functions

Most variable declarations can be prefixed with `signed` or `unsigned` to change the function of the sigh bit. For example, `unsigned int x = 0;` would create a variable that holds numbers from 0 to 65535 because the sign bit is used as an extra data bit.

---
Tags: programming, variables
---


# Question
Title: What happens when I call exit() from my program?
In either of `setup` or `loop`, if I were to add an `exit(0)` call, where would control be passed to? What would the next state of the microcontroller be? Would it stop execution and power down?

I am using a revision 2 Arduino Uno.

# Answer
> 12 votes
My initial guess is wrong. I would have thought it would simply return from loop and the core library would just call loop() again. However, I see the following code was created. Noticing that \__stop\_program is a hard loop...

An extract of Blink.ino's listing, with exit(0) added:

```
// the loop routine runs over and over again forever:
void loop() {
  digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);               // wait for a second
  digitalWrite(led, LOW);    // turn the LED off by making the voltage LOW
  delay(1000);               // wait for a second
  exit(0);
}

```

The disassembly of the above:

```
// the loop routine runs over and over again forever:
void loop() {
  digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
 100:   80 91 00 01     lds r24, 0x0100
 104:   61 e0           ldi r22, 0x01   ; 1
 106:   0e 94 ca 01     call    0x394   ; 0x394 <digitalWrite>
  delay(1000);               // wait for a second
 10a:   68 ee           ldi r22, 0xE8   ; 232
 10c:   73 e0           ldi r23, 0x03   ; 3
 10e:   80 e0           ldi r24, 0x00   ; 0
 110:   90 e0           ldi r25, 0x00   ; 0
 112:   0e 94 f7 00     call    0x1ee   ; 0x1ee <delay>
  digitalWrite(led, LOW);    // turn the LED off by making the voltage LOW
 116:   80 91 00 01     lds r24, 0x0100
 11a:   60 e0           ldi r22, 0x00   ; 0
 11c:   0e 94 ca 01     call    0x394   ; 0x394 <digitalWrite>
  delay(1000);               // wait for a second
 120:   68 ee           ldi r22, 0xE8   ; 232
 122:   73 e0           ldi r23, 0x03   ; 3
 124:   80 e0           ldi r24, 0x00   ; 0
 126:   90 e0           ldi r25, 0x00   ; 0
 128:   0e 94 f7 00     call    0x1ee   ; 0x1ee <delay>
  exit(0);
 12c:   80 e0           ldi r24, 0x00   ; 0
 12e:   90 e0           ldi r25, 0x00   ; 0
 130:   0e 94 1e 02     call    0x43c   ; 0x43c <_exit>

...

0000043c <_exit>:
 43c:   f8 94           cli

0000043e <__stop_program>:
 43e:   ff cf           rjmp    .-2         ; 0x43e <__stop_program>

```

Note that if \_exit had not called cli, interrupts would be able to do stuff. But that is not the case.

# Answer
> 11 votes
Well I just tested it with my Arduino Uno and it just completely stopped the code and left all the outputs as they were when the code stopped running (so it left an LED I had on on). There seems to not be a IO cleanup when you call exit. This was what I expected because the Arduino IDE provides the setup and loop functions, if you program the ATMEGA\*28 with with any other AVR IDE you start with the main function like all C/C++ programs. The setup and loop functions are not standard on AVR MCU's.

**Note:** The press of the reset button restarts the code, if you were wondering.

---
Tags: programming, arduino-uno
---


# Question
Title: Why do some pins have a different PWM frequency?
According to the Arduino reference for `analogWrite()`, the PWM frequency on most pins is ~490 Hz. However, it's ~980 Hz for pins 5 and 6 on the Uno, and for pins 3 and 11 on the Leonardo.

Why are these different? Is it a deliberate design feature, or is it somehow dictated by the hardware?

# Answer
Those aren't the only frequencies available for the PWM signals. However, they are the frequencies as determined by the applied prescaler (which you can readily change as detailed below).

Each of the 3 pairs of PWM pins is tied to one timer, each of which has its own base frequency, as follows:

* Pins 5 and 6 are paired on timer0, with base frequency of 62500Hz
* Pins 9 and 10 are paired on timer1, with base frequency of 31250Hz
* Pins 3 and 11 are paired on timer2, with base frequency of 31250Hz

Then each set of pins have a number of prescaler values that can be chosen, that will divide the base frequency of that pair of pins. The prescaler values available are:

* Pins 5 and 6 have prescaler values of 1, 8, 64, 256, and 1024
* Pins 9 and 10 have prescaler values of 1, 8, 64, 256, and 1024
* Pins 3 and 11 have prescaler values of 1, 8, 32, 64, 128, 256, and 1024

The different combinations yield different frequencies in a given PWM pin. Notice that timer 2 (tied to pins 3 and 11) have more prescaler values available, resulting in more frequencies available.

Now, why timer 2 is different, that's a separate question.

Edit: Here's a list of possible PWM frequencies per pin (from this article):

> For pins 6 and 5 (OC0A and OC0B):
>
> * If TCCR0B = xxxxx001, frequency is 64kHz
> * If TCCR0B = xxxxx010, frequency is 8 kHz
> * If TCCR0B = xxxxx011, frequency is 1kHz (this is the default from the Diecimila bootloader)
> * If TCCR0B = xxxxx100, frequency is 250Hz
> * If TCCR0B = xxxxx101, frequency is 62.5 Hz
>
> For pins 9, 10, 11 and 3 (OC1A, OC1B, OC2A, OC2B):
>
> * If TCCRnB = xxxxx001, frequency is 32kHz
> * If TCCRnB = xxxxx010, frequency is 4 kHz
> * If TCCRnB = xxxxx011, frequency is 500Hz (this is the default from the Diecimila bootloader)
> * If TCCRnB = xxxxx100, frequency is 125Hz
> * If TCCRnB = xxxxx101, frequency is 31.25 Hz

`TCCRnB` is where you set the prescaler bits for timer `n`, replacing `n` by 0, 1 or 2, depending on the timer you want to set. If you are still unsure about bitwise operations, read this bit math tutorial.

My sources:

Note that there seems to be divergence in those sources about whether pins 9 and 10 have the same behavior as 5 and 6 or 3 and 11, but you get the idea anyway. I'm reading the datashet to try and figure out which is correct, or whether this is a difference between boards.
> 24 votes

# Answer
I am not aware of the design considerations, but if you check the datasheet for the microcontroller on your Arduino, you will notice that PWM pins are grouped together and per group connected to a timer. The speed at which this timer is increased varies by the configured prescaler. If you change the prescaler for a certain timer, you change the PWM frequency for the related PWM pins. I believe some timers double for other purposes like the `millis();` function. If you change the prescaler for that timer, values returned by `millis()` will be off by the same factor.

You can calculate the setting for the prescaler as follows:

$$\text{prescaler} = \dfrac{f\_{CPU}}{PWMresolution × f\_{PWM}} = \dfrac{16\text{MHz}}{256×490} \approx 128$$

> prescaler = f\[CPU\]/(PWMresolution×f\[PWM\]) = 16000000/(256×490) = approx 128.

Check the datasheet and you'll find that 128 is indeed one of the prescaler values you can select.
> 8 votes

---
Tags: arduino-uno, pwm, arduino-leonardo, analogwrite
---


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

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

# Answer
There are several options for Arduino power in an external environment.

* Wall wart: Connects to a wall socket, provides a great long-term source of power
* Rechargeable battery: Doesn't last long, but they can be recharged and monitored with a low cost board
* Alkaline Battery: Last longer, there are some monitoring systems available.
* Solar: Only works when the sun is out, unless you combine it with a rechargable battery (example)
* Nuclear power: NOT RECOMMENDED!!!
> 4 votes

---
Tags: power
---


# Question
Title: What can I do if I run out of Flash memory or SRAM?
According to the Arduino documentation, the ATmega328 has 32KB of Flash memory for the bootloader + uploaded sketch, and only 2KB SRAM for runtime data. The ATmega2560 has quite a bit more, totalling 256KB and 8KB respectively.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

## Storing strings in Flash instead of SRAM.

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

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

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

```

## Use the right data types

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

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

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

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

Available Memory

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

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

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

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

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

# Answer
> 10 votes
There are two things to do if you run out of storage:

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

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

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

* variable storage: it is possible to expand SRAM, as sachleen has already pointed out. **SRAM, FRAM, and NVSRAM** are all appropriate for rapidly-changing variables. (While in principle you could use flash to store variables, then you have to worry about flash wear-out). SPI (a serial protocol) is the easiest to connect to the Arduino. The SpiRAM library works with the Microchip 23K256 serial SRAM chip. The Ramtron FM25W256 serial FRAM chip (now owned by Cypress) also uses SPI. The Cypress CY14B101 NVSRAM also uses SPI. Etc.
* constant data that needs to still be there the next time the power comes on: this is almost as simple as expanding SRAM. There are many external **EEPROM, FRAM, NVSRAM, and FLASH** storage devices available. Currently the lowest cost per MB are **SD flash cards** (which can accessed via SPI). The Ramtron FM25W256 (see above), the Cypress CY14B101 (see above), etc. can also store constant data. Many expansion shields include a SD card slot, and several libraries and tutorials support reading and writing to (flash) SD cards. (We can't use SRAM for this, because SRAM forgets everything when the power goes out).
* executable code: Unfortunately, expanding an Arduino's Flash memory to increase program space isn't possible. However, a programmer can always refactor a sketch to reduce code size at the expense of increasing data size and making it run slightly slower. (In theory, you could go so far as translate your entire sketch into some interpreted language, store that version of your sketch on a SD card, and then write a interpreter for that language that runs on the Arduino to fetch and execute instructions from the SD card -- Forth on Arduino, a BASIC interpreter, a Tom Napier Picaro interpreter, some application-specific language, etc.).

---
Tags: flash, sketch-size
---


title: Washable, Wearable Tech with Arduino

text:
# Question
Title: Washable, Wearable Tech with Arduino
**Question:** How does one prepare clothing with embedded electronics for washing?

**Background:** There are several Arduino boards/clones that are designed for "wearable tech." (For example, the Lilypad.) Wearable tech with LED light patterns, microphones, GPS, or other circuitry is an interesting concept, but water and electricity tend not to mix.

To prepare wearable tech for washing, I would assume people make large circuitry removable. Yet, inevitably, some electronics will be more-or-less permanently affixed to the cloth. What, if anything, can be done to these electronics (e.g. sewn-in Arduino Lilypad) to make them washing-machine (preferred--hand wash could be done, but it's so much easier to machine wash) safe?

# Answer
I would use some sort of epoxy and cover up the exposed circuitry. The major concern would be where the wires connect to the board as flex over time can weaken it.

Some options include:

* 3M™ Scotchcast™ Wet-Niche Potting Kit
* Hysol
> US1150™—For electronics, telecommunications, and automotive components. Provides environmental hazard protection.
>
> US1152™—For electronic assemblies. Provides environmental hazard protection.

Heat might play a factor if you cover up the boards in epoxy but you shouldn't be producing that much heat in a wearable device anyway, right?
> 5 votes

# Answer
I would make it so the Board has velcro on it so that it can be un attached from the clothing, and then have all the wires have snap terminals that wires from the Arduino connect to. This way you un snap all the wires and remove the arduino. As far as components, I would cover them in an epoxy to protect them.
> 4 votes

# Answer
> How does one prepare clothing with embedded electronics for washing?

* Remove the battery(ies) and other power supplies, and set them far away from the water. Buzzers and speakers also.
* Gently wash clothing (including the Lilypad, LEDs, resistors, capacitors, integrated circuits, accelerometers, magnetometers, Bluetooth modules, GPS modules, etc.) by hand with a mild detergent.
* Drip dry, or manually dry with a hair-dryer.

See:
> 4 votes

---
Tags: safety
---


title: Using the Waspmote Sensor Board

text:
# Question
Title: Using the Waspmote Sensor Board
Spanish company Libelium makes this pretty impressive sensor board:

http://www.libelium.com/products/waspmote/sensors/

for their Waspmote series of boards. These are not meant for Arduino compatibility, but they are not only interesting for combining so many sensors, the availability of calibrated sensor sets makes it even more unique.

So here is the challenge: can we reasonably leverage these from an Uno or a Mega?

# Answer
> 3 votes
Too long for a comment...

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

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

All that's saying is you can't simply plug in a sensor into your Arduino like a shield, because it's not a shield. You'd have to hook up the connections to the right pins and then use their libraries and code to communicate with it.

That involves reading their documentation and code to figure out what pins it uses to communicate with what. You may have to modify the code slightly to work with Arduino (mainly changing pin numbers).

All in all, I wouldn't invest my time or effort into it. Don't lock yourself into a product that isn't intended to be used the way you're using it. You'll get no support from the company and there's no guarantee future versions of their product will work. Or things like this (from the forum link):

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

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

---
Tags: arduino-uno, sensors, arduino-mega
---


# Question
Title: What will happen when I use an invalid pin number?
> Related to: What happens if there is a runtime error?

This question is similar to the one above, however this is an alternate situation:

```
int pin = 999;
pinMode(pin, OUTPUT);
digitalWrite(pin, HIGH);

```

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

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

---

The second line in your code is where the magic will happen and thats where we need to focus.

```
pinMode(pin, OUTPUT);

```

The portion of `pinMode` relevant to this discussion is:

```
void pinMode(uint8_t pin, uint8_t mode)
{

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

    if (port == NOT_A_PIN) return;

//Do something
}

```

(The complete implementation can be found in wiring\_digital.c)

So, here, `digitalPinToBitMask` seems to be using `pin` to compute an intermediate bit. Exploring further, `digitalPinToBitMask` is a macro defined in `Arduino.h` whose definition is this one-liner:

```
#define digitalPinToBitMask(P) ( pgm_read_byte( digital_pin_to_bit_mask_PGM + (P) ) )

```

This weird looking one liner does a very simple task. It indexes the Pth element in the array `digital_pin_to_bit_mask_PGM` and returns it. This array `digital_pin_to_bit_mask_PGM` is defined in `pins_arduino.h` or the pin map for the specific board being used.

```
const uint8_t PROGMEM digital_pin_to_bit_mask_PGM[] = {
    _BV(0), /* 0, port D */
    _BV(1),
    _BV(2),
    _BV(3),
    _BV(4),
    _BV(5),
    _BV(6),
    _BV(7),
...
};

```

This array has 20 elements in total, so we are out of luck. 999 will index a memory location in the flash memory outside of this array, thereby leading to unpredictable behavior. *Or will it?*

We still have another line of defense against runtime anarchy. Its the next line of the function `pinMode`:

```
uint8_t port = digitalPinToPort(pin);

```

`digitalPinToPort` takes us along a similar path. It is defined as a macro along with `digitalPinToBitMask`. Its definition is:

```
#define digitalPinToPort(P) ( pgm_read_byte( digital_pin_to_port_PGM + (P) ) )

```

Now, we index the Pth element of `digital_pin_to_port_PGM` which is an array defined in the pin map:

```
const uint8_t PROGMEM digital_pin_to_port_PGM[] = {
    PD, /* 0 */
    PD,
    ....
    PC,
    PC,
};

```

This array contains 20 elements, so 999 is again out of range. Again, this command reads and returns a value from flash memory of whose value we cannot be certain. This will again lead to unpredictable behavior from here on.

There is still one last line of defense. That is the `if` check in `pinMode` on the return value of `digitalPinToPort`:

```
if (port == NOT_A_PIN) return;

```

`NOT_A_PIN` is defined as 0 in `Arduino.h`. So, if the returned byte from `digitalPinToPort` happens to be zero, then `pinMode` will silently fail and return.

In any case, `pinMode` cannot save us from anarchy. 999 is destined to result in doom.

---

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

# Answer
> 4 votes
In the standard libraries, there are macros designed for converting pins to ports, which are used in assembly. Here they are for the Uno from Arduino 1.0.5:

```
#define digitalPinToPCICR(p)    (((p) >= 0 && (p) <= 21) ? (&PCICR) : ((uint8_t *)0))
#define digitalPinToPCICRbit(p) (((p) <= 7) ? 2 : (((p) <= 13) ? 0 : 1))
#define digitalPinToPCMSK(p)    (((p) <= 7) ? (&PCMSK2) : (((p) <= 13) ? (&PCMSK0) : (((p) <= 21) ? (&PCMSK1) : ((uint8_t *)0))))
#define digitalPinToPCMSKbit(p) (((p) <= 7) ? (p) : (((p) <= 13) ? ((p) - 8) : ((p) - 14)))

```

There are more, but I won't show them here.

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

---
Tags: programming
---


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

**Edit:** How can I use these with my Arduino?

# Answer
Transistors (such as Bipolar Junction Transistors (BJT)) are solid state switchers, that is, they don't have any moving parts. Metal-Oxide-Semiconductor Field-Effect Transistors (MOSFET) are also transistors, but are voltage controlled, whereas classical BJTs are current-controlled. Relays are more expensive, but they have moving parts.

BJTs and MOSFETs produce a lot of heat (with high currents). They both have three pins (usually) called the base, collector and emitter (in the case of BJT) or gate, source, drain (in the case of MOSFET). More info here

Relays use a magnet to control the position of a metal switch. They generally take more power than an Arduino pin can deliver, and therefore they are often controlled by a transistor. Relays can usually switch more current than either a transistor or a MOSFET.

There are also Solid State Relays (SSR), which have a triac (a device similar to a transistor) in them. These can't switch as much as a normal relay, but they generally have better ratings than MOSFETs and BJT. example
> 11 votes

# Answer
Big differences between relays and transistors are:

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

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

---
Tags: relay, mosfet, transistor
---


title: Serial sensors and the Yun

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

# Answer
The Yun is a bit different to other Arduinos. The main microcontroller is a ATmega32U4 with a build in USB interface. This is used for the connection to the PC so the single USART is not used for this purpose.

However, the single USART is used for connecting to the built in wireless processor. This means that you can't use the wireless and hardware serial at the same time. I presume you are using the Yun for wireless, so disabling this is not desirable.

SoftwareSerial is relatively good, but does consume a lot of cycles. You can only listen on a single port at a time. It is possible to use pin change interrupts to listen for activity on multiple ports and switch to the one required, but this requires that the other end can wait for a response.

SoftwareSerial will tie up the microcontroller whilst sending, which can lead to problems when supporting *low* baud rates. Conversely, because it is CPU heavy, it can also have problems with *high* baud rates. There is a window, between 9600 and 38400 baud, where it seems to work best.

There is another software serial version called AltSoftSerial. This works faster than SoftwareSerial and can transmit and receive at the same time.

You can use the USART, SoftwareSerial and AltSoftSerial all at the same time. Be warned that because all three of these use interrupts and some use timers, you are highly likely to end up with complex, hard to debug interactions.

Note than in older versions of Arduino (pre v1), SoftwareSerial was very, very poor. It was replaced entirely with "NewSoftSerial".

Sensors are often have very basic USART hardware with limited buffer sizes, and drop data when they aren't serviced in a timely manner.

I am not a massive fan of the Yun. It isn't popular, the wireless is still relatively hard to use (compared to the TI CC3000), and the wireless interface uses valuable pins. Personally, if I was to work on a project that required multiple serial interfaces, I would either

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

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

# Answer
I don't have any experience with the Yun so I can't comment on that specifically, but the only problem you'll encounter with using SoftwareSerial is that you can only communicate with one device at a time.

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

```
sensor1.listen()

```

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

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

---
Tags: serial, arduino-yun, sensors
---


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

# Answer
The difference is simple:

## Clones don't say "Arduino," where counterfeits do

If I were to create 200 boards all labeled "Arduino UNO R3," it would be a counterfeit. If I were to call them "Happyduino," it would be a *clone*.

---

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

> Not okay:
>
> * Arduino Xxxxxx
> * Xxxxxx Arduino
> * Arduino Compatible Xxxxxx - use "Xxxxxx (Arduino-Compatible)" instead
>
> Okay:
>
> * Xxxxxx for Arduino - products that work with official Arduino boards (e.g. shields or kits)
> * Xxxxxx (Arduino-Compatible) - variations and clones which are software and hardware compatible
>
> Note that while we don't attempt to restrict uses of the "duino" suffix, its use causes the Italians on the team to cringe (apparently it sounds terrible); you might want to avoid it. (It's also trademarked by a Hungarian company.)
> 21 votes

# Answer
A **clone** is an exact or almost exact replica of an original Arduino board, with a different branding.

A **derivative** is a board based or inspired by Arduino boards, with some specific addition or modification (different layouts, built-in sensors...)

A **counterfeit** is a clone of an Arduino board, with the same branding of an Arduino board.

More info on an article on the Arduino blog.
> 8 votes

---
Tags: clones, counterfeit
---


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

They can be seen on this image:

Most of them are immediately above the SainSmart and UNO logos. The SVG pins corresponding to the analog pins can be seen immediately below the microprocessor.

What are these pins for? Is this a standard format for some applications, or is it something unique to the SainSmart?

# Answer
SVG = Signal, Voltage, Ground.

The Signal pin will carry the actual output, which may be high or low at any given time. It's basically just a male version of the corresponding standard GPIO pin. The Voltage pin will always be high (which can be 5v or 3.3v on this board, depending on the output level switch). The Ground pin is exactly what the name suggests -- it's connected to the board's ground.

This obviously means there is a lot of duplication. Why have two signal pins? And why bother having so many Voltage and Ground pins if they're all the same anyway?

The reason is simply convenience.

If you have a standalone external component (such as a motor), you would normally have to run 3 separate wires to it. With the regularly-spaced SVG pins on the board, you can instead use a 3-way cable with a suitable female header block. You can run that to an equivalent set of 3 pins on the external component. That means you are able to attach/detach the component by plugging/unplugging (effectively) a single cable.

I don't think the SVG idea is a 'standard' as such, largely because (in this form) it's only really of benefit to people who are experimenting or prototyping (as opposed to designing a more permanent system). It seems to be fairly popular among hobbyists and enthusiasts though. You just need to watch out for components which may put their equivalent SVG pins in a different order.
> 10 votes

---
Tags: pins, arduino-uno, clones
---