message:
Arduino Pro Mini (3.3V version) input voltage range / tolerance

I have a few Arduino Pro Mini clones (cheap Chinese stuff) and would like to power them with 12V power supply (same as fan voltage). According to the [Arduino Pro Mini spec][1] the RAW pin can take 3.35-12V (3.3V model). In practice this means a 12V PSU cannot be used as they are almost always over 12V with low load. I read that the voltage regulator in this board is capable up to 16V input. I tried plugging in a cheap 12V power adapter that read 15.1V with no load but a component on the arduino clone board actually exploded instantly. The board seems to work still when powered from usb programmer. Component that burned out is just above VCC, RST and GND pins.

Why did this happen? What did I just damage and most importantly what is a safe voltage level to use? I already have a few 12V switching power supplies it would be a shame if I could not use them.

Solution:

In the end it seems to have been a faulty arduino clone, faulty or poor quality power adapter or the fact that I powered the power supply before plugging it to the board's RAW input pin. The cheap 12V switching power supplies work just fine even though my multimeter registers a voltage spike as high as 30V during power up.

  [1]: http://arduino.cc/en/Main/ArduinoBoardProMini#.UyT9APl_sz0

body:
The component that exploded during your test is a capacitor.

According to the position on the board you mentioned, it is one of the 2 electrolytic capacitors used on both sides of the 3.3V regulator (I would say that's probably the upstream capcitor).

There are [a few reasons why a capacitor may explode][1]:

- apply an inverted voltage to it (polarized capacitors only)
- apply a voltage above its rating
- apply a current above its rating

Your situation is probably the 2nd one: too high voltage applied.

According to Sparkfun original schematics, this capacitor must be polarized with 10uF capacity. Unfortunately the schematics do not mention the maximum voltage.

According to the [specification for the original board][2], the maximum voltage for this cap should be at least 12V, but there is no guarantee that it is anthing above than 12V. Hence, you have to consider **12V is the maximum voltage applicable** to your board (on the RAW pin).

In addition, you have mentioned you are using a cheap chinese clone, it is perfectly possible (although not expected, as it would make the board operate differently than the original specs) that this one uses a lower voltage cap (eg 10V) which would be a bit cheaper.

If you do want to reuse your 12V PSU, you will have to ensure that its output voltage never exceeds 12V, for this you are left with a few options:

- use a [voltage divider][3] made of 2 resistors: you must first know the max voltage output of your PSU and then calculate resistance values to get 12V based on that max voltage. That's easy but it can waste a lot of energy
- use a 12V [Zener diode][4] outside your PSU
- use a 12V [voltage regulator][5] circuit after your PSU: that one is the safest, but also the most expensive solution

**Edit:**

Of course, if you have already done it and are equipped for it, you can find replacements for the capacitor that has exploded and buy a higher-voltage one, then replace it on your boards; that will reauire good soldering/desoldering equipement usable for surface-mounted components.

  [1]: http://en.wikipedia.org/wiki/Capacitor#Hazards_and_safety
  [2]: http://arduino.cc/en/Main/ArduinoBoardProMini
  [3]: http://en.wikipedia.org/wiki/Voltage_divider
  [4]: http://en.wikipedia.org/wiki/Zener_diode
  [5]: http://en.wikipedia.org/wiki/Voltage_regulator


sender: user

sender: assistant

body:
The genuine Pro Mini's use a [MIC5205 regulator][1] which should accept up to 16V at it's input normally, with an absolute maximum of 20V. It's unlikely that the regulator would be damaged by 15.1V.

However, the component you have indicated that has blown is a capacitor. SMD capacitors are available in different voltage ratings, typically 4V, 6.3V, 10V, 16V, 25V, 35V and 50V (and above, but let's ignore them for this). It's rare to see any intermediate values.

SMD capacitors are very intolerant of being used at a higher voltage than specified. This is especially true of electrolytic and tantalum capacitors. The blown capacitor on the genuine Pro Mini's is polarised (the grey band not he package and the schematic indicates this), so we can infer it is either electrolytic or tantalum. A 10µF SMD electrolytic is unlikely to be in this package, so it is almost certainly a tantalum.

Sparkfun sell [10µF tantalums][2], and they are rated at 16V. It's quite likely these are the same ones used on the Pro Mini. 15.1V is very close to 16V - in fact, if this is a poorly smoothed power supply, the meter might show 15.1V but the peaks could well be 16V or even 20V. It is recommended that you de-rate the voltage ratings on tantalums by 50% at least.

It's really important to realise that most low-cost DC power supplies are not regulated and produce a very bumpy output voltage with no regulation:

![enter image description here][3]

Tantalums also have no tolerance for reverse voltage, so if you did apply reverse voltage, it would pop.

So it is quite likely that you over-volted the cap and blew it. You could replace them with higher rated capacitors - I would go for 35V ones if you want to supply 15.1V. Desoldering and desoldering a single capacitor is relatively easy as long as the pads haven't been damaged. Realistically, you could use a normal leaded 10uF electrolytic between RAW and GND instead of the SMD one.

**EDIT:** However, looking at the data sheet for the regulator, it shouldn't really matter if that 10uF is there or not:

> A 1μF capacitor should be placed from IN to GND if there is more than
> 10 inches of wire between the input and the ac filter capacitor or if
> a battery is used as the input.

Some regulators absolutely require an input capacitor, with others it is just advisable. This looks like it is just advisable. So if it isn't working on external power now, you may have blown the regulator as well.

Even if the clone board uses a different SMD regulator, their characteristics are all very similar. As stated, some do need a capacitor on the input to work, so replacing it might fix it.

There is a further consideration that dropping from 15.1V to 3.3V on a SMD regulator is not a great idea. You will need to burn off a lot of power.

The MC5205 can dissipate 455mW with a minimal PCB footprint (which the Pro Mini has) with a 25°C ambient:

![Thermal calc][4]

So, we know the maximum power we can dissipate, and we know the voltage drop - we can then calculate the current:

P = (Vin - Vout) * I

0.455 / (15.1 - 3.3) = I

I = 38.5mA

This isn't very much at all. You might want to consider regulating off the board, and probably with a switching regulator rather than linear regulator.

I also note your PS:

> the ground of the 12V PSU is shared with Arduino ground pin, not sure
> if this might be the cause.

If they weren't shared, there would be no way that this could work. They need to be shared otherwise the Vcc from the power supply is not referenced to anything and may as well not be there.

  [1]: http://www.micrel.com/_PDF/mic5205.pdf
  [2]: https://www.sparkfun.com/products/11244
  [3]: https://i.stack.imgur.com/ihvi5.gif
  [4]: https://i.stack.imgur.com/lBlQZ.png


body: Although this thread is old, people has to be aware that some clone boards uses 4B2X regulator and they support maximum 10v (https://epstik.com/p744820729-xc6204b332mr-4b2x-stabilizator.html , https://www.mcucity.com/product/3240/xc6204b332mr-g-3-3v-4b2x-4b2y-positive-voltage-regulator). Theses clones are extremely common on ebay and another marketplaces.


message:
Is there a way to detect if Arduino, Stino or another IDE/toolchain is in use?

I've noticed some irritating differences between the Arduino IDE and Stino (mainly around including certain header files). These are likely bugs that need following up with one or both of the parties, but in the meantime, I would like my code to compile with both of them without editing. This is because I do not want to lock any users out of using my code.

Are there any macros or similar that are readily available (as in, require no modification of the toolchain or IDE) that would allow me to detect which is in use?

For example, in many libraries, there is this snippet:

    #if ARDUINO >= 100
      #include "Arduino.h"
    #else
      #include "WProgram.h"
    #endif

However both Stino and Arduino define this.

body: As Stino claims to use the installed Arduino IDE you already have, which means you can not differentiate at compile time.


message:
What alternatives are there to the Optiboot bootloader?

Nearly all modern Arduino boards use the [Optiboot bootloader][1]. Compared to the ATmegaboot used before, this is smaller in flash terms (by about 1.5KB) and faster in upload speed (115.2k vs 57.6k) and starts your sketch quicker (the delay whilst waiting after reset is shorter).

Are there any alternatives to the Optiboot bootloader? Specifically, are there any smaller (in flash terms) boot loaders? What differences do they have?

  [1]: https://code.google.com/p/optiboot/

body:
> Are there any alternatives to the Optiboot bootloader?

Err... not really. There's actually **a [unofficial] [modification to Optiboot to make it faster when uploading](http://zygomorphic.com/arduino-tiny/?attachment_id=257).**

> To install the high baud rate variations…
>
>  - Ensure the Arduino IDE is not running
>  - Download the 7-Zip archive using the link above
>  - Extract the three files to the following directory: `{Arduino Installation Root}\hardware\arduino\bootloaders\optiboot\`
>  - Open the boards.txt file located in the following directory: `{Arduino Installation Root}\hardware\arduino\`
>
> Find This section inside it:
>
>     uno.name=Arduino Uno
>     uno.upload.protocol=arduino
>     uno.upload.maximum_size=32256
>     uno.upload.speed=115200
>     uno.bootloader.low_fuses=0xff
>     uno.bootloader.high_fuses=0xde
>     uno.bootloader.extended_fuses=0x05
>     uno.bootloader.path=optiboot
>     uno.bootloader.file=optiboot_atmega328.hex
>     uno.bootloader.unlock_bits=0x3F
>     uno.bootloader.lock_bits=0x0F
>     uno.build.mcu=atmega328p
>     uno.build.f_cpu=16000000L
>     uno.build.core=arduino
>     uno.build.variant=standard
>
> Add the following section…
>
>     uno_uf.name=Arduino Uno / Upload Fast
>     uno_uf.upload.protocol=arduino
>     uno_uf.upload.maximum_size=32256
>     uno_uf.upload.speed=250000
>     uno_uf.bootloader.low_fuses=0xff
>     uno_uf.bootloader.high_fuses=0xde
>     uno_uf.bootloader.extended_fuses=0x05
>     uno_uf.bootloader.path=optiboot
>     uno_uf.bootloader.file=optiboot_atmega328_250000.hex
>     uno_uf.bootloader.unlock_bits=0x3F
>     uno_uf.bootloader.lock_bits=0x0F
>     uno_uf.build.mcu=atmega328p
>     uno_uf.build.f_cpu=16000000L
>     uno_uf.build.core=arduino
>     uno_uf.build.variant=standard
>
>  - Change the two highlighted values to the baud rate you plan to use:    250000, 500000, or 1000000 Save and close the boards.txt file
>  - Using your favourite ISP programmer, install the new bootloader. *Don’t forget to: Ensure the Arduino Uno / Upload Fast board is selected (Tools / Board)*, *If appropriate, ensure the Serial Port of
> your programmer is selected (Tools / Serial Port)*, *Ensure the
> programmer is selected (Tools / Programmer)*, *After installing the
> bootloader, change the Serial Port to the serial port of your Arduino
> Uno*.

Above text slightly modified for compatibility with site. *[Original post](http://zygomorphic.com/arduino-tiny/?page_id=249)*
****
Besides that, and the ATmegaboot bootloader, you can't really find any alternative. I would imagine that if Arduino loads it on all the Unos ever produced, it's pretty optimized. The above hack speeds up upload time, but it doesn't reduce the size of the bootloader. You can also [remove the wait time on the bootloader](http://learn.adafruit.com/arduino-tips-tricks-and-techniques/bootloader) so it has a faster startup.

If you're that concerned about maximising flash see: *<https://arduino.stackexchange.com/questions/193/how-to-really-shrink-a-sketch>* and [this answer](https://arduino.stackexchange.com/a/222/220) [on on *<https://arduino.stackexchange.com/questions/221/what-can-i-do-if-i-run-out-of-flash-memory-or-sram>*].


body:
Optiboot is about the smallest bootloader available.

But, there is a much more powerful (with inbuilt console for hardware testing, RAM and Flash contents checking, etc) bootloader with a more developed and robust stk500v2 communications protocol between avrdude and the AVR bootloader.

I've used it on the ATmega2560 and on the ATmega1284p. It works for both 3 byte and 2 byte program counter MCU.

I have a [STK500v2 Bootloader][1] version on [Sourceforge][2].

This bootloader is based the Peter Fleury STK500v2 bootloader, updated by Mark Sproul. I've made edits to have it supporting with the Goldilocks (an ATmega1284p) board.

The key feature is to use the **STK500v2** protocol for uploading the Flash image to the Arduino. This protocol is more robust and gives better error capabilities than the **avr109** protocol. As an aside the avr109 protocol is called "Arduino" in the Arduino world, because it toggles DTR (to reset the board and automatically enter the bootloader), and the STK500v2 protocol is called "Wiring" in the Arduino world, because of the same reason.

The Fleury/Sproul STK500v2 bootloader is designed to work with the ATmega2560 which has a 3 byte program register, because of the larger Flash size. But, it also supports normal 2 byte boards (everything else really).

For boards with plenty of Flash (like Goldilocks 1284p), there is a **hardware monitor** that can be used to query Flash, SRAM and hardware; you can check connections without additional code, and check the actual contents of Flash and EEPROM. Because the 1284p supports 2 USART, I added the ability to have debugging on **USART1**, so that the upload process via **USART0** isn't disturbed.

  [1]: https://sourceforge.net/projects/avrfreertos/files/AVRstk500v2_bootloader/ "STK500v2 Bootloader"
  [2]: https://sourceforge.net/projects/avrfreertos/ "AVRfreeRTOS"


body:
[TinySafeBoot][1] is an alternative for ATtiny and ATmega devices.

 - Compatible to plenty of ATtinys and ATmegas (see below)

 - Read/Write access to Flash and EEPROM.

 - All IOs available for serial communication

 - One-wire, also with multiple AVRs on a single line

 - Autobauding, rugged protocol.

 - Activated by Reset + Password (optional)

 - Password and Timeout user changeable anytime.

 - "Emergency Erase" to overcome lost Password - kills all data but leaves bootloader intact.

 - ATtinys: ~ 550 bytes,

 - ATmegas: < 512 bytes (!)

 - TSB for ATtiny can update itself.

 - The Sourcecode is free Software (GPL)

  [1]: http://jtxp.org/tech/tinysafeboot_en.htm


message:
Most power efficient way to constantly save 2 kilobytes of data per second

I would like to constantly save data coming from sensors (for an activity tracker) while consuming as less battery as possible (I'd like to have a 4/5 days autonomy on a 3000 mAh battery) but I can't find the best way to save about 2 kBytes/s on a memory large enough to contain several days of data.

Sensors would be read at a rate of 20 times per second and produce about 100 bytes each time.

What options do I have in order to:

- store such an amount of data (hardware)?
- ensure the system can work properly with required autonomy?

body:
This would be possible with a standard SD card.

**Capacity**

Using some simple calculations, I was able to find that writing at 2kB/s for 5 days would only consume 0.8GB. You could probably get by with a 1 or 2 GB card.

**Speed**

I found [this benchmark](http://forum.arduino.cc/index.php/topic,109862.0.html), which says it is possible to write SD card data from an Arduino at 192 kB/s, which should be more than enough for your needs.

There are a lot of great tutorials and examples out there for using an SD card with an Arduino. The [official documentation](http://arduino.cc/en/Reference/SD) is always a good place to start.


body:
There are two constraints here, and I think it might back you into a corner. Size and then power.

2Kbyte/s is 2*60*60*24/1024 = 168.75Mbyte/day. This is a lot. The only readily available technology that can be used with a small microprocessor that can store this volume of data is an SD card. There are no serial EEPROM or flash chips this large, and the Arduino, as far as I know, can't deal with the NAND flash used in USB sticks and SD cards.

However, SD cards can be relatively power hungry. They draw between 5mA and 100mA when writing, typically around 30-50mA. The SD spec says the maximum is 200mA. Writing is also quite lengthy as they operate on blocks of data rather than individual cells. I've never done a full analysis of how much power they use, but it is not insignificant and much, much more than serial EEPROM or flash.

So your only choice, if you have to store that much, is to go with SD cards.

I would investigate compressing the data. Even very basic schemes can make a huge difference.


message:
3.3V, 5V and 9V pins on Arduino

On my Arduino Uno R3 and Arduino Mega R3, there are 5V and 3.3V pins.

However on this page [Introduction to the Arduino Board](http://arduino.cc/en/reference/board), there is a 5V and 9V pin but no 3.3V pin. The page at [Arduino: What Adapter?](http://playground.arduino.cc/Learning/WhatAdapter) also mentions a 9V pin.

Why is there a discrepency?

![Arduino UNO Board Layout][1]

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

body:
There are three power supply pins on the Arduino Uno and on the Mega:

- 5V - Labelled as 5V. Can be used to power other 5V devices.
- 3.3V - Labelled as 3.3V. Can be used to power other 3.3V devices.
- Vin - This also referred to as the 9V pin that is shown in the schematic. This is used to power the Arduino board itself, usually using a 9V battery.

![enter image description here][1]

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


body:
The link you provide looks rather old and I don't think it applies to UNO Revision 3 as it has more pins than on the diagram you show.

I suggest you rather take a look at this [Arduino UNO link][1] which contains uptodate information about the UNO; in there you will see that for R3, the "power rail" has been extended and has the following pins, left to right:

- 1 unlabeled pin (can't remember what it is)
- 1 **IOREF** pin (used by shields to know if they should operate as 3.3V or 5V devices)
- **3.3V** regulated output
- **5V** regulated output
- 2 **GND** pins
- **Vin** pin: this pin can be used in 2 different ways:
    - either as a voltage supply input (instead of using the power plug or the USB); the input voltage should be in 7-12V range and will be regulated internally (by the board circuits) to 5V
    - or an output supply voltage (if you plugged voltage supply through the power plug or the USB plug) that is a "copy" of the voltage input through the power plug or USB plug (not regulated yet)

  [1]: http://arduino.cc/en/Main/ArduinoBoardUno


message:
I'm using too much RAM. How can this be measured?

I would like to know how much RAM I am using in my project, as far as I can tell, there's no way to actually work that out (other than going through and calculating it myself). I have got to a stage in a rather large project where I have determined that I am running out of RAM.

I have determined this because I can add a section and then all hell breaks loose **somewhere else in my code** for no apparent reason. If I `#ifndef` something else out, it works again. There is nothing programatically wrong with the new code.

I suspected for a while that I was getting to the end of available RAM. I don't think I'm using too much stack (although it's possible), what is the best way to determine how much RAM I am actually using?

Going through and trying to work it out, I have problems when I get to enums and structs; how much memory do they cost?

_first_ edit: ALSO, I have edited my sketch so much since starting, these are not the actual results I initially got, but they are what I am getting now.

      text    data     bss     dec     hex filename
     17554     844     449   18847    499f HA15_20140317w.cpp.elf
     16316     694     409   17419    440b HA15_20140317w.cpp.elf
     17346     790     426   18562    4882 HA15_20140317w.cpp.elf

The first line (with text 17554) was not working, after much editing, the second line (with text 16316) is working as it should.

_edit: the third line has everything working, serial reading, my new functions, etc. I essentially removed some global variables and duplicate code. I mention this because (as suspected) it's not about this code per sae, it has to be about the RAM usage. Which brings me back to the original question, "how to best measure it" I'm still checking out some answers, thanks._

How do I actually interpret the above information?

So far my understanding is:

    `TEXT` is program instruction memory
    `DATA` is variables (unitialised?) in program memory
    `BSS`  is variables occupying RAM

since BSS is considerably less than 1024 bytes, why does the second work, but the first doesn't? If it's `DATA+BSS` then both occupy more than 1024.

**_re-edit:_ I edited the question to include the code, but now I've removed it because it really had nothing to do with the problem (other than maybe poor coding practices, variable declarations and the like). You can review the code by looking back through the edits if you _really_ want to see it. I wanted to get back to the question at hand, which was more based around: How to measure RAM usage.**

body:
> I suspected for a while that I was getting to the end of available RAM. I don't think I'm using too much stack (although it's possible), what is the best way to determine how much RAM I am actually using?

It would be best to use a combination of manual estimation and by using the `sizeof` operator. If all your declarations are static, then this should give you an accurate picture.

If you are using dynamic allocations, then you may run into a problem once you start deallocating the memory. This is due to memory fragmentation on the heap.

> Going through and trying to work it out, I have problems when I get to enums and structs; how much memory do they cost?

An enum takes as much space as an `int`. So, if you have a set of 10 elements in a `enum` declaration, that would be `10*sizeof(int)`. Also, every variable that uses an enumeration is simply an `int`.

For structures, it would be easiest to use `sizeof` to find out. Structures occupy a (minimum) space equal to sum of its members. If the compiler does structure alignment, then it may be more, however this is unlikely in the case of `avr-gcc`.


body:
When you figure out how to locate the generated .elf file in your temporary directory, you can execute the command below to dump a SRAM usage, where `project.elf` is to be replaced with the generated `.elf` file. The advantage of this output is the ability to inspect *how* your SRAM is used. Do all the variables need to be global, are they really all required?

    avr-objdump -S -j .bss project.elf

    project.elf:     file format elf32-avr

    Disassembly of section .bss:

    00800060 <__bss_start>:
            ...

    00800070 <measurementReady>:
            ...

    00800071 <cycles>:
            ...

    00800073 <measurement>:
      800073:       00 00 00 00                                         ....

    00800077 <measurementStart>:
      800077:       00 00 00 00                                         ....

    0080007b <timerOverflows>:
      80007b:       00 00 00 00

Notice that this doesn't show stack or dynamic memory use as Ignacio Vazquez-Abrams noted in the comments below.

Additionally a `avr-objdump -S -j .data project.elf` can be checked, but none of my programs output anything with that so I can't tell for sure if it is useful. It [supposed to list](http://mcuoneclipse.com/2013/04/14/text-data-and-bss-code-and-data-size-explained/) 'initialized (non-zero) data'.


body:
You can use the functions provided [AVRGCC: Monitoring Stack Usage](http://www.avrfreaks.net/index.php?name=PNphpBB2&file=viewtopic&t=52249)

The function was intended to check the stack usage but what it reports is the actual RAM that has never been used (during execution). It does so by "painting" (filling) the RAM with a known value (0xC5), and then checking the RAM area counting how many bytes have still the same initial value.
The report will show the RAM that has not been used (minimum free RAM) and therefor you can calculate the max RAM that has been used (Total RAM - reported RAM).

There are two functions:

 - **StackPaint** is executed automatically during initialization and "paints" the RAM with the value 0xC5 (can be changed if needed).

 - **StackCount** can be called at any point to count the RAM that hasn't been used.

Here is an example of usage. Doesn't do much but is intended to show how to use the functions.

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

    // -----------------------------------------------------------------------------
    extern uint8_t _end;
    extern uint8_t __stack;

    void StackPaint(void) __attribute__ ((naked)) __attribute__ ((section (".init1")));

    void StackPaint(void)
    {
    #if 0
        uint8_t *p = &_end;

        while(p <= &__stack)
        {
            *p = 0xc5;
            p++;
        }
    #else
        __asm volatile ("    ldi r30,lo8(_end)\n"
                        "    ldi r31,hi8(_end)\n"
                        "    ldi r24,lo8(0xc5)\n" /* STACK_CANARY = 0xc5 */
                        "    ldi r25,hi8(__stack)\n"
                        "    rjmp .cmp\n"
                        ".loop:\n"
                        "    st Z+,r24\n"
                        ".cmp:\n"
                        "    cpi r30,lo8(__stack)\n"
                        "    cpc r31,r25\n"
                        "    brlo .loop\n"
                        "    breq .loop"::);
    #endif
    }

    uint16_t StackCount(void)
    {
        const uint8_t *p = &_end;
        uint16_t       c = 0;

        while(*p == 0xc5 && p <= &__stack)
        {
            p++;
            c++;
        }

        return c;
    }

    // -----------------------------------------------------------------------------

    void setup() {

    Serial.begin(9600);
    }

    void loop() {
      // put your main code here, to run repeatedly:
    Serial.println(StackCount(), DEC);  // calls StackCount() to report the unused RAM
    delay(1000);
    }


body:
The main issues you can have with memory usage at runtime are:

- no available memory in the **heap** for dynamic allocations (`malloc` or `new`)
- no room left on the **stack** when calling a function

Both are actually the same as the AVR **SRAM** (2K on Arduino) is used for both (in addition to **static data** which size never changes during program execution).

Generally, dynamic memory allocation is seldom used on MCUs, only a few libraries typically use it (one of them is `String` class, which you mentioned you don't use, and that's a good point).

The stack and the heap can be seen in the picture below (courtesy of [Adafruit][1]):
![enter image description here][2]

Hence, the most expected issue comes from stack overflow (i.e. when the stack grows towards the heap and overflows on it, and then -if the heap was not used at all- overflows on the static data zone of the SRAM. At that time, you have a high risk of either:

- data corruption (i.e. the stack ovewrites heap or static data), giving you ununderstandable behavior
- stack corruption (i.e. the heap or static data overwrites stack content), generally leading to a crash

In order to know the amount of memory that's left between the top of the heap and the top of the stack (actually, we might call it the bottom if we represent both the heap and the stack on the same image as depicted below), you can use the following function:

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

In the code above, `__brkval` points to the top of the heap but is `0` when the heap has not been used, in which case we use `&__heap_start` which points to `__heap_start`, the first variable that marks the bottom of the heap; `&v` points of course to the top of the stack (this is the last variable pushed on the stack), hence the formula above returns the amount of memory available for the stack (or the heap if you use it) to grow.

You can use this function in various locations of your code to try and find out where this size is getting dramatically reduced.

Of course, if ever you see this function return a negative number then it is too late: you have already overflown the stack!

  [1]: http://learn.adafruit.com/memories-of-an-arduino/measuring-free-memory
  [2]: https://i.stack.imgur.com/waoHN.gif


body:
There is a program called [Arduino Builder][1] that provides a neat visualization of the amount of flash, SRAM and EEPROM your program is using.

[![Arduino Builder][2]][2]

The Arduino builder makes up part of the [CodeBlocks Arduino IDE][3] solution. It can be used as either a standalone program or through the CodeBlocks Arduino IDE.

Unfortunately Arduino Builder is a little [old][4] but it should work for most programs and most Arduinos, such as the Uno.

  [1]: http://arduinodev.com/arduino-uploader/
  [2]: https://i.stack.imgur.com/rwDID.png
  [3]: http://arduinodev.com/codeblocks/
  [4]: http://arduinodev.com/arduino-builder-updated/


message:
Arduino Not Responding During Program

I got an Arduino Uno to play around with, and started to actually dive in. During a program that I am writing for a friend, it suddenly stopped outputting to the serial monitor. When I comment out the part I added (the for loop for changing the names), it still doesn't respond.

    #include <TrueRandom.h>
    #include <EEPROM.h>
    #define numPokemon 151
    String nameArray[] = {"MISSINGNO","Bulbasaur","Ivysaur","Venusaur","Charmander","Charmeleon","Charizard","Squirtle",
    "Wartortle","Blastoise","Caterpie","Metapod","Butterfree","Weedle","Kakuna","Beedrill","Pidgey","Pidgeotto",
    "Pidgeot","Rattata","Raticate","Spearow","Fearow","Ekans","Arbok","Pikachu","Raichu","Sandshrew","Sandslash",
    "Nidoran♀","Nidorina","Nidoqueen","Nidoran♂","Nidorino","Nidoking","Clefairy","Clefable","Vulpix","Ninetales","Jigglypuff",
    "Wigglytuff","Zubat","Golbat","Oddish","Gloom","Vileplume","Paras","Parasect","Venonat","Venomoth","Diglett","Dugtrio","Meowth",
    "Persian","Psyduck","Golduck","Mankey","Primeape","Growlithe","Arcanine","Poliwag","Poliwhirl","Poliwrath","Abra","Kadabra","Alakazam",
    "Machop","Machoke","Machamp","Bellsprout","Weepinbell","Victreebel","Tentacool","Tentacruel","Geodude","Graveler","Golem","Ponyta","Rapidash",
    "Slowpoke","Slowbro","Magnemite","Magneton","Farfetch`d","Doduo","Dodrio","Seel","Dewgong","Grimer","Muk","Shellder","Cloyster","Gastly","Haunter",
    "Gengar","Onix","Drowzee","Hypno","Krabby","Kingler","Voltorb","Electrode","Exeggcute","Exeggutor","Cubone","Marowak","Hitmonlee","Hitmonchan","Lickitung",
    "Koffing","Weezing","Rhyhorn","Rhydon","Chansey","Tangela","Kangaskhan","Horsea","Seadra","Goldeen","Seaking","Staryu","Starmie","Mr. Mime","Scyther","Jynx",
    "Electabuzz","Magmar","Pinsir","Tauros","Magikarp","Gyarados","Lapras","Ditto","Eevee","Vaporeon","Jolteon","Flareon","Porygon","Omanyte","Omastar","Kabuto","Kabutops",
    "Aerodactyl","Snorlax","Articuno","Zapdos","Moltres","Dratini","Dragonair","Dragonite","Mewtwo","Mew",
    };
    int a = 0;
    int b = 0;
    int value;
    String pokemonName;
    int currentID = TrueRandom.random(1,numPokemon+1);
    // a = CurrentID
    void setup(){
      Serial.begin(9600);
      if (EEPROM.read(a)!=0){
        currentID = EEPROM.read(a);
        Serial.print("The Stored ID is ");
        Serial.println(EEPROM.read(a));
        Serial.println("Stored = true");
      }else{
        value = EEPROM.read(a);
        Serial.println(value);
        EEPROM.write(a,currentID);
        value = EEPROM.read(a);
        Serial.println(value);
        Serial.println("Stored = false");
      }
      for (int i = 0 ; i < 152 ; i++){
          if (currentID = i){
            pokemonName = nameArray[i];
            Serial.print(pokemonName);
            break;
          }
       }
      //nameChange(currentID);
      //Serial.println(pokemonName);
    }
    void loop(){

    }
    void nameChange(int currentID){
       for (int i = 0 ; i < 152 ; i++){
          if (currentID = i){
            pokemonName = nameArray[i];
            break;
          }
       }
    }

What is the problem with this code?

body:
the string array is too big for ram, place it in flash with the fucntion F()

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

also a detailed example with array with explanation cn be found [here][1]

  [1]: http://forum.arduino.cc/index.php/topic,145756.0.html


body:
You have mixed up your comparison and assignment operators in two instances:

First is towards the end of `setup`.

      for (int i = 0 ; i < 152 ; i++){
          //if (currentID = i){ //This is assignment, not comparison
          //This is a comparison operation
            if (currentID == i){
            pokemonName = nameArray[i];
            Serial.print(pokemonName);
            break;
          }
       }

Second, is in the function definition of `nameChange`.

    void nameChange(int currentID){
       for (int i = 0 ; i < 152 ; i++){
          //if (currentID = i){ //This is an assignment operation, not comparison.
          //This is a comparison operation
            if (currentID == i){
            pokemonName = nameArray[i];
            break;
          }
       }

Also, you have defined a constant `numPokemon` but are not using it at any point.


body:
The primary reason that this isn't working is that you are using more RAM than the ATmega328 has (2Kbytes).

The array nameArray is huge. Each one of those characters is 1 byte, it's ~1.1k in itself. Add in Serial, TrueRandom and String, and you are over the limit. It could be you are right on the bounds and calling a single function pushes the stack over it's limit.

To save size, you can place the strings in flash. There is functionality to do this in Arduino, namely [PROGMEM directive][1] from underlying AVR-GCC and F() from Arduino. Making arrays of string is quite painful though, and using the [Flash library][2] helps here.

Personally I would avoid String for anything like this. The insides of String use dynamic memory allocation and when you are near the limits of RAM, it really isn't helpful. You lose a lot of ease of use by moving to arrays of char though.

You are also using assignment instead of comparison in your code:

    if (currentID = i){
       pokemonName = nameArray[i];
       Serial.print(pokemonName);
       break;
    }

This needs to be `currentID == i`.

I'm not confident what you are doing here though. If you want to get the *i* th element from the array, then just do

    pokemonName = nameArray[currentID]

You also have an odd conditional at the beginning where you check for an EEPROM value being non zero, and then the else reads out the EEPROM value which by definition must be zero.

Also, you have a define for `numPokemon` but you aren't using it for the bounds on your for loops.

  [1]: http://arduino.cc/en/Reference/PROGMEM#.UyXZldzGnHg
  [2]: http://arduiniana.org/libraries/flash/


message:
Unrecognizable Message From PROGMEM char*

I'm using a PROGMEM char* to store a massive array. When I try to print a certain part of the array, the message comes out mangled. How do I fix this?

The output should be "Poliwag", but it comes out as "arow".

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

    #include <TrueRandom.h>
    #include <EEPROM.h>
    #define numPokemon 151
    PROGMEM char* nameArray[] = {"MISSINGNO","Bulbasaur","Ivysaur","Venusaur","Charmander","Charmeleon","Charizard","Squirtle",
    "Wartortle","Blastoise","Caterpie","Metapod","Butterfree","Weedle","Kakuna","Beedrill","Pidgey","Pidgeotto",
    "Pidgeot","Rattata","Raticate","Spearow","Fearow","Ekans","Arbok","Pikachu","Raichu","Sandshrew","Sandslash",
    "Nidoran♀","Nidorina","Nidoqueen","Nidoran♂","Nidorino","Nidoking","Clefairy","Clefable","Vulpix","Ninetales","Jigglypuff",
    "Wigglytuff","Zubat","Golbat","Oddish","Gloom","Vileplume","Paras","Parasect","Venonat","Venomoth","Diglett","Dugtrio","Meowth",
    "Persian","Psyduck","Golduck","Mankey","Primeape","Growlithe","Arcanine","Poliwag","Poliwhirl","Poliwrath","Abra","Kadabra","Alakazam",
    "Machop","Machoke","Machamp","Bellsprout","Weepinbell","Victreebel","Tentacool","Tentacruel","Geodude","Graveler","Golem","Ponyta","Rapidash",
    "Slowpoke","Slowbro","Magnemite","Magneton","Farfetch`d","Doduo","Dodrio","Seel","Dewgong","Grimer","Muk","Shellder","Cloyster","Gastly","Haunter",
    "Gengar","Onix","Drowzee","Hypno","Krabby","Kingler","Voltorb","Electrode","Exeggcute","Exeggutor","Cubone","Marowak","Hitmonlee","Hitmonchan","Lickitung",
    "Koffing","Weezing","Rhyhorn","Rhydon","Chansey","Tangela","Kangaskhan","Horsea","Seadra","Goldeen","Seaking","Staryu","Starmie","Mr. Mime","Scyther","Jynx",
    "Electabuzz","Magmar","Pinsir","Tauros","Magikarp","Gyarados","Lapras","Ditto","Eevee","Vaporeon","Jolteon","Flareon","Porygon","Omanyte","Omastar","Kabuto","Kabutops",
    "Aerodactyl","Snorlax","Articuno","Zapdos","Moltres","Dratini","Dragonair","Dragonite","Mewtwo","Mew"
    };
    int a = 0;
    int b = 0;
    int value;
    String pokemonName = "Missingno";
    int currentID = TrueRandom.random(1,numPokemon+1);
    // a = CurrentID
    void setup(){
      Serial.begin(9600);
      if (EEPROM.read(a)!=0){
        currentID = EEPROM.read(a);
        Serial.print("The Stored ID is ");
        Serial.println(EEPROM.read(a));
        Serial.println("Stored = true");
      }else{
        value = EEPROM.read(a);
        Serial.println(value);
        EEPROM.write(a,currentID);
        value = EEPROM.read(a);
        Serial.println(value);
        Serial.println("Stored = false");
      }
      pokemonName = nameArray[currentID];
      Serial.println(pokemonName);
    }
    void loop(){

    }

body:
The way you've written in, the *pointer* is stored in flash, but the strings are stored in *SRAM*. Read the appropriate documentation (also found in the Arduino reference) more closely, and do as it says.

    char nmPokemon0[] PROGMEM = "MISSINGNO";
    char nmPokemon1[] PROGMEM = "Bulbasaur";
     ...

    PGM_P nameArray[] PROGMEM =
    {
      nmPokemon0, nmPokemon1, ...
    };

And don't forget to copy the string to SRAM as shown further down before outputting it, since `Serial.println()` can't work directly with flash.


message:
PROGMEM char* mangled text

I wrote a program using PROGMEM for massive string arrays. One of the arrays worked, but when I added the second one, the serial output only puts out "th".

Pastebin Code: http://pastebin.com/9U7QZQKn

body:
Your declaration of char buffers is done like so:

    char* move1 = "N/A";

This will only allocate 3 characters with an additional one for null termination i.e. not long enough to hold the name.

You need to do:

    char buffer[16];

Where the length is long enough to hold your string.


body:
I see one major flaw in your code, related to index usage on arrays.

Arrays in C and C++ are using a **0-based index**, meaning that, for an array containing `N` elements:

- the first element is accessible with index `0`
- the last element is accessible with index `(N-1)`

However, your code uses `TrueRandom.random(1,numPokemon+1);` which means you'll get an index between `1` and `numPokemon` (included), if you get the `numPokemon` value for your index, then you'll get garbage as it will try access some other part of memory.

Maybe that is not the only problem in your code, but this one is a major bug.


message:
Can I program a 3.3v chip on a 5v board?

I bought a Gertboard a while ago, and one of the features it has on-board is an ATMega328 (DIP). However, since the Gertboard is designed for use with the Raspberry Pi, it only operates at 3.3v, so the clock speed is limited to ~12MHz.

Programming it via the Raspberry Pi is quite cumbersome though. Instead, I'd like to transfer the chip to an Arduino Uno board so I can upload sketches from my desktop PC. I would then transfer it back to the Gertboard for normal operation.

The problem is that my Uno operates at the more typical 5v / 16MHz.

Is it safe to attempt this? Do I need to make any configuration changes in the IDE to tell it to account for a different clock speed?

body:
The clock speed selected will affect both `delay*()` and `millis()`/`micros()` as well as the functions in `<util/delay.h>`, therefore you *must* use the target system's correct clock speed if you are using any of these functions. This can be easily done by editing `boards.txt` and copying an existing entry for the Uno and changing the value of the `f_cpu` parameter to match the target system (in this case, `12000000`).

The difference in voltage does not matter, since the chip can run at either voltage and no connection is being made between the 5V system and the 3.3V system.


message:
Arduino USB Power vs External Power Supply

Why is the Arduino able to accept ~5V from the USB, but requires a min of 7V when using an external power supply?

body: The design assumes USB provides a regulated 5v so no further regulation is necessary. The power connecter is meant to accept a wider range of voltage and regulate it to 5v, and the kind of regulators used on the Arduino board need that much higher voltage to provide regulation. If you already have a regulated +5v source you can supply it to the 5v pin. You'll bypass the on-board regulator this way, so just know that it will then be up to you to provide clean power.


body:
![AA Battery][1]

Above is an AA Battery voltage curve. Many people assume that 5* 1.5V AA batterys would be enough to power the Arduino. As you can see the 1.5 is the maximum voltage and it quickly drops. Different brands have different values and sometimes this can drop below the value of the voltage regulator input. I usually tend to aim between 7 and 9 Volts for  running from batteries, ie the nominal voltage of the batteries, eg 6 x 1.5V = 9V.

For wall socket charges, Buy a cheap one and hook it up to a volt meter, Many that say 5V actually have a range of values. Raspberry Pi users often have problems with power caused by manufacturers saying its 5v and it actually delivering something like 4.85 and fluctuating beacuse of the power demand of the pi

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


message:
Arduino Mega not flashable with XBee PRO S2B

I have an Arduino Mega 2560 with a [libelium XBee Shield][1]. If I have an XBee S2 mounted on it and set the two jumpers to the USB setting or remove them, I am able to flash a program onto my Arduino.

However, when I'm mounting one of my XBee PRO S2B (I have three of them available and all behave the same) on the Arduino, no matter how I set the jumpers, it is not possible to flash anything on it. I always see `avrdude: stk500v2_getsync(): timeout communicating with programmer` in the Arduino IDE.

Is the XBee PRO S2B incompatible with the Arduino or what might be the issue? I also tried to add an external power source additionally to the USB, but it didn't help either.

**Update**

After some more experimenting, I found out new details. I tried to disconnect each pin of the shield individually. While doing it, I discovered that disconnecting the `reset` pin from the arduino makes it possible to flash it - take a look at the [XBee shield schematic][2], it's pin 5 from the ICSP connector; Photo: ![photo of it][3]

I used a multimeter and discovered that the XBee PRO S2B CTS / DIO7 port is high, while the one from the XBee S2 is low, and so constantly resetting the arduino. I mounted the XBee PRO S2B onto the [Sparkfun XBee Explorer USB][4] and opened a serial port with PuTTY.
In contrast to the S2, the PRO S2B provides a menu with several options:

    B-Bypass Mode
    F-Update App
    T-Timeout
    V-BL Version
    A-App Version
    R-Reset
    >

![Sparkfun XBee Explorer USB, CTS port][5]

As soon as I type B, the CTS port goes low, and would prevent the arduino from resetting. Also this mode is needed to detect the module via XCTU. However, with an unmodified arduino, I wouldn't have a chance to send this letter, since the XBee is constantly resetting it. What is this menu, can it be disabled somehow?

  [1]: http://arduino.cc/en/Main/ArduinoXbeeShield#.UybqgHVSm4I
  [2]: http://www.arduino.cc/en/uploads/Main/XbeeShieldSchematic.pdf
  [3]: https://i.stack.imgur.com/wgXvG.jpg
  [4]: https://www.sparkfun.com/products/8687
  [5]: https://i.stack.imgur.com/ju3TV.jpg

body:
I don't have a PRO to play with, but I just looked at the [datasheet][1] and it appears that it SHOULD timeout after 60 seconds

> If no serial transaction is initiated within a 60 second timeout period, the bootloader times out and returns to
the menu. If the upload is interrupted with a power cycle or reset event, the EM250 will detect an invalid
application image and enter bootloader mode.  (page 139)

Also, it seems that it takes a particular set of conditions to get to the bootloader, obviously these conditions are being met:

> XBee modules use a modified version of Ember’s bootloader. This bootloader version supports a custom entry
mechanism that uses module pins DIN (pin 3), DTR / SLEEP_RQ (pin 9), and RTS (pin 16). To invoke the bootloader,
do the following:

> 1. Set DTR / SLEEP_RQ low (TTL 0V) and RTS high.
2. Send a serial break to the DIN pin and power cycle or reset the module.
3. When the module powers up, DTR / SLEEP_RQ and DIN should be low (TTL 0V) and RTS should be high.
4. Terminate the serial break and send a carriage return at 115200bps to the module.
5. If successful, the module will send the Ember bootloader menu out the DOUT pin at 115200bps.
6. Commands can be sent to the bootloader at 115200bps.

> **Note:** Hardware flow control should be disabled when entering and communicating with the EM250 bootloader.

Perhaps check pins 3, 9 and 16 on boot and see if you can modify their behaviour.

  [1]: ftp://ftp1.digi.com/support/documentation/90000976_F.pdf


message:
Expected Unqualified-ID Before 'do'(and 'while')

I am getting the error "error: expected unqualified-id before 'do'" multiple times for every do{
}while(); loop I have... Any help?

Pastebin:http://pastebin.com/DubuAEUs

body:
The do whiles are outside of the setup() or loop(), so they won't work.

I would suggest doing a simple C/C++ tutorial like [this one][1] to get up to speed with how things work.

  [1]: http://www.learn-c.org


message:
My DS18B20 is reading high. How can I get it to return the correct temperature?

I am working on a heating control system for my home, but having problems with the temperature sensor reading higher than I expect.

I have a 5V Arduino Mini Pro clone hooked up to a relay module, an HD47780 display and a Tiny RTC module, with a DS18B20 attached to it.

The DS18B20 is powered from the 5v Vcc applied to the Tiny RTC module rather than using parasitic power on the DQ line (as I wasn't sure if the Onewire libraries supported this mode of operation) and the [DS18B20 datasheet][1] says that Vcc may be between 3.0v and 5.5v. I measured the regulated power from the Mini Pro's  being at 5.2v.

I am comparing the temperature from the DS with the existing room thermostat (bi-metallic), an RS desktop temperature monitor with two sensors, a small ['thermo-hygrometer'][2] and a [bi-metallic fridge thermometer][3] (in the upper quarter of its temperature range)†. The readout from the DS is always around 1-2 degrees higher than the readout from the other sensors, which are within a degree of each other.

† Not the actual one, but something similar.

Reading various forums I have heard that these sensors are quite accurate but can suffer from localised heating from components near them, so I moved the sensor onto a 20cm cable and positioned it well away from the rest of the electronics. This made no difference.

I then read that the DS can become self heating if it is supplied with too high a Vcc voltage, so I added a Red LED with 1.7v drop and measured the new voltage over the DS as 3.5v, but again, after waiting for the temperatures to stabilise once more, this made no difference.

Can anyone suggest why the DS may be reading high and what I can can do to prevent this?

  [1]: http://datasheets.maximintegrated.com/en/ds/DS18B20.pdf
  [2]: http://i01.i.aliimg.com/photo/v4/376190273/In_out_Thermo_Hygrometer_HC520.jpg
  [3]: http://ecx.images-amazon.com/images/I/71sVnFU5AQL._SL1436_.jpg

body:
I've put a lot of DS18B20 sensors in place now on various sensor nodes - maybe 50 or so. I've learnt a bit about the readings returned from them. I know you have isolated some of these as not being the cause, but it is good to confirm that they are issues.

I don't know if you are using Celsius or Fahrenheit, so the degree of the problem isn't clear.

**Localised heating**

I don't think of Arduino as a "hot" chip, but putting a DS18B20 in an enclosure with an Arduino and LCD caused me to see readings 2-3°C higher than expected.

Moving it outside the enclosure fixed this.

**Heating from high Vcc/frequent conversions**

If you supply the chip with a high Vcc and perform frequent conversions (i.e. as frequently as you can), the chip does warm up. I have seen this increase readings by 1-2°C.

I haven't seen the problem with high Vcc alone, but I operate most DS18B20 in parasitic mode and convert at most once every 10s. The ones operated in active mode generally have the powered turned off when not being used.

OneWire and DallasTemperature do support parasitic mode.

**Not all temperature sensors are created equal**

I had a number of temperature sensors before I started playing around with DS18B20. Almost without exception, these under-read. Most of them are based on thermistors and calibration is poor. I thought the DS18B20 were over reading, but when I used a good thermocouple and meter, I could validate that they were correct.

This was about learning to trust the DS18B20.

**Heat conducted along wire**

If you have the sensors on a wire, the wire conducts a surprising amount of heat. This can be an issue when running wiring along pipes.

**Fake DS18B20**

These sensors are very popular, and this seems to have caused fakes to appear. I have a batch of stainless steel waterproof sensors that over-read and the timings were out. They worked with the OneWire library, but not a DS2482 OneWire master. I have heard of the normal TO-92 cased ones being fake as well.


body:
Perhaps you might want to calibrate your sensor.

What does it read when immersed in boiling water (assuming sea level) ? 102.5 Celsius?  That would give you a high-temperature calibration of -2.5C.

Obviously it's better to calibrate around the temperatures you expect to me measuring.  That means trusting (or averaging?) some measuring device and calibrating to that.


body: In my case, the wiring between my uC and the sensor was too short, and was transmitting some heat. I thought that couldn't be the case at first, since another temp sensor was reporting accurate temps at the same distance. I moved it to another location on the board and voila!


body: I have seen offsets of several degrees C when using DS18B20 on a 3.3V bus, switching to a stable 5.0V bus and I got more reasonable values. (tested with and without parasitic power)


body:
I've made some experiments.
If DS18B20 was on short cable <1cm to my Arduino Pro Micro the readings was 5 degrees more than environment was. On cable lenght >10cm from arduino board and no matter where the resistor was mounted (near arduino or near DS18B20) the readings was fine.


message:
Corrupted output from HC-05 Bluetooth module

I have arduino Pro Mini 3.3V version with hc-05 module connected to 3.3V/GND and RXI/TX0 pins. I am then using my android phone to connect to the module. It shows up and pairs fine. Then I use BlueTerm app to view the output. I am seeing output that is occasionally as expected but mostly partially corrupted (characters replaced with random characters).

I am using 9600 baud rate and trasmitting the following:

    void serialTransmit(int data){
      // send to raspberry pi or other device(s).
      Serial.print("Serial Transmit: ");
      Serial.println(data); // this is hard coded as "12" for testing
    }

I tried switching rx/tx pins around but got same corrupt output. Tried changing baud rate but then it wouldn't transmit anything at all and default rate is 9600 so that was expected.

What could be the cause?

body:
First thing to try:

Connect a 2.2k - 10k resistor from the arduino RX pin (the hc-05 tx pin) to ground.

If that didn't work, I recommend getting everything into a known state and eliminating some complexity. So, first let's remove the Android software from the equation.  And second, let's put the module into a known baud rate.

To do this wire up the arduino and module like this:![schematic][1]

Notice that the Key pin is connected to 3.3v.  That will ensure the module is at 38400 baud on power up.

Connect the arduino to your computer with the FTDI cable.  Upload the following sketch:

    /* Serial Loop */

    #include <SoftwareSerial.h>

    #define rxPin 8
    #define txPin 9

    SoftwareSerial mySerial(rxPin, txPin); // RX, TX
    char myChar ;

    void setup() {
      Serial.begin(9600);
      Serial.println("AT");

      mySerial.begin(38400);
      mySerial.println("AT");
    }

    void loop() {
      while (mySerial.available()) {
        myChar = mySerial.read();
        Serial.print(myChar);
      }

      while (Serial.available()) {
        myChar = Serial.read();
        Serial.print(myChar); //echo
        mySerial.print(myChar);
      }
    }

With the sketch now uploaded and running, open the Arduino serial console and enter these AT commands. The serial console baud rate should be set to 9600 and line endings should be "Both NL & CR"

    AT+ORGL //back to factory settings
    AT+ROLE=0 //slave role - transparent serial bridge
    AT+UART=9600,0,0 //default baud rate
    AT+INIT //init module

You should get "OK" back from the module after each command. If you've gotten this far, we know the module is working fine and we know what baud rate it will default to now.

Hook the module back up the way you had it before.  Make sure 3.3v is disconnected from key pin and make sure you have added the pulldown resistor on the RX line. Cycle the power to the module. The module should start up running 9600 baud, slave mode. Delete the module from the Android pairing list and re-pair it.  The name probably will have changed.  Hopefully it works correctly now.

Cheers

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


body:
I have the same problem with arduino pro mini and HC-06, only change the baud rate of your BTserial port... try diferent baud rates in my case:

    Serial.begin(9600);
    Serial.println("AT");

    BTSerial.begin(2400);
    BTSerial.println("AT");

Works fine, it happens because the arduino try to "understand" the module, but if the module speaks other leanguage, the arduino will never understand the command.

like me... sorry for my bad english. se ya.


message:
RF remote control using VirtualWire on ATtiny85 running at 8MHz on internal oscillator

I'm trying to make an RF remote control using ATtiny85 running at 8MHz on internal oscillator, [this cheap RF 434MHz transmitter module](http://www.wenshing.com.tw/Products/RF_Module/ASK_RF_Transmitter_Module/TWS-DS-3_433.92MHz_Miniaturization_Wireless_Transmitter_Module/) (like the one below), and VirtualWire lib, **but had no success so far**.

![RF transmitter][1]

So, before I go any further, **is it possible to use VirtualWire with ATtiny85 running at 3.6V and 8MHz with its internal oscillator? If so, how?**

I've found a few scattered sources of information on the Net about it, but couldn't make much sense of it.

I have build ATMega328 versions of the receiver and transmitter using VirtualWire without any major problems. Both modules talk to each other will very little data drop out. Now, when I tried to replace the ATMega328 transmitter with a smaller version using the ATtiny85, I'm having problems.

Here are the symptoms:

1. The major one seem to be that when I add the VirtualWire include, **my sketch seems to slow down a lot**. So I figure it's a timing issue. But I'm not sure what the problem is.

2. I put a scope on ATtiny85 pin 6 (PB1) but **I don't see anything being transmitted**. I think I've messed up with the pin names.

3. I can make the LED blink and also can read the buttons without problems.

Here are the schematics and the board design for the remote controller:

![RC schematic][2]

The board is currently powered by 2 AA NiMH batteries that are currently at 2.6V. I can make the ATtiny85 blink with that voltage. I plan to power the RC with a 3.6V CR2 lithum battery.

Here are more details of my development enviroment:

* Arduino IDE 1.05
* I'm using ATtiny cores [from here](https://docs.google.com/file/d/0B4cPTBXMMjz9Q0NWN3Q1cWhuV0U/edit?pli=1)
* I'm programming the ATtiny85 using an Arduino UNO R3 as ISP, without problems (it's working as I can make the ATtiny85 blink an LED).

And here's my code:

    #include <VirtualWire.h>

    #define VCC_PIN  A1
    #define BTN_PIN  A2
    #define LED_PIN  A3
    #define TXD_PIN  PB1

    #define BLINK_UP_TIME  25

    #define BUTTON_NONE  0
    #define BUTTON_1     1
    #define BUTTON_2     2
    #define BUTTON_3     3
    #define BUTTON_4     4
    #define BUTTON_5     5
    #define BUTTON_6     6

    void setup()
    {
      pinMode(BTN_PIN, INPUT);
      pinMode(TXD_PIN, OUTPUT);
      pinMode(VCC_PIN, OUTPUT);
      pinMode(LED_PIN, OUTPUT);

      // leave RF transmitter off for now
      digitalWrite(VCC_PIN, LOW);

      // Initialise the IO and ISR
      vw_set_tx_pin(TXD_PIN);
      vw_setup(2000);  // Bits per sec

      // let the user know we are alive: heartbeat
      blink(3, 50);
      delay(1000);
    }

    uint8_t buf[VW_MAX_MESSAGE_LEN];
    uint8_t buflen = VW_MAX_MESSAGE_LEN;

    void loop()
    {
      byte button = ReadButtons();
      if (button != BUTTON_NONE) {
        // transmit button pressed
        digitalWrite(LED_PIN, HIGH); // Flash a light to show transmitting
        digitalWrite(VCC_PIN, HIGH); // turn tranmitter on
        delay(10);
        buf[0] = button;
        vw_send(buf, 1);
        vw_wait_tx(); // Wait until the whole message is gone
        digitalWrite(LED_PIN, LOW); // turn off LED
        digitalWrite(VCC_PIN, LOW); // turn tranmitter off
      }
      delay(100);
    }

    byte ReadButtons()
    {
      unsigned int buttonVoltage = analogRead(BTN_PIN);
      byte button = BUTTON_NONE;   // return no button pressed if the below checks don't write to btn
      if      (buttonVoltage < 10)   {    button = BUTTON_1; }
      else if (buttonVoltage < 200)  {    button = BUTTON_2; }
      else if (buttonVoltage < 400)  {    button = BUTTON_3; }
      else if (buttonVoltage < 550)  {    button = BUTTON_4; }
      else if (buttonVoltage < 720)  {    button = BUTTON_5; }
      else if (buttonVoltage < 900)  {    button = BUTTON_6; }
      else if (buttonVoltage > 1000) {    button = BUTTON_NONE; }
      return( button );
    }

So, **What's wrong with my setup?**

  [1]: https://i.stack.imgur.com/LHs0b.gif
  [2]: https://i.stack.imgur.com/skxbK.png

body:
I tried those Tiny cores you are using and had a lot of problems. I switched to http://code.google.com/p/arduino-tiny/ and it seems much better. Create a second Arduino installation folder and add the arduino-tiny cores.  The pin name constants are like PIN_A0, PIN_A1,...,PIN_B1, etc. So, try that out.

I looked briefly at the VirtualWire code and there are ifdefs specifically for the Attiny85, so it should work.  Here is a derivative project with working ATTINY85 examples: http://cosa-arduino.blogspot.de/2013/03/news-virtual-wire-interface.html


body:
Try the manchester library instead.
This post includes all the necessary info except wiring diagrams:
https://arduino.stackexchange.com/questions/1304/manchester-library-wont-compile-for-attiny85


body:
I spent some time getting VirtualWire to work on attiny84. I see two issues with your code:

1. Since the tiny85 only has one timer, that one is being used by both VirtualWire and `millis`/`micros`. So your delays won't work as expected.
1. VirtualWire uses default values for vw_ptt_pin (10) and vw_rx_pin (11). Those pins don't exist on the attiny85. When `vwsetup` calls `pinMode` with these values, it causes writes to arbitrary memory addresses. This is likely to make your sketch behave unpredictably. To fix set `vw_set_ptt_pin()` and `vw_set_rx_pin()` to pins that exist on the tiny85 or modify the VirtualWire source.


body:
Updated 26-08-2018: added tx(false); at the end of send.  Without it, the TX pin could remain high, flooding the 433MHz band and making any other communication on it almost impossible!!!

Although these are all pretty old posts, I've still been struggling to get VirtualWire or its successor RadioHead working on an Attiny85.  Typically the problem is that VirtualWire uses timer 0 and thereby breaks other stuff.

Now, for RX you typically don't want to spend all your processing cycles waiting for bits to come in, so you want it to be interrupt-driven, but for TX you can often do without that ...  So, I did a bit of reverse-engineering of the VirtualWire TX code and implemented it as a simple send routine which can be used without needing a dedicated timer-interrupt.  Using the code below on Attiny85 and an Arduino Uno as receiver with the normal VirtualWire library and the same baudrate, works just great for me, so if someone else can benefit from it, then here it is (including some code to read out an ultrasonic distance sensor and driving some leds - up to the reader to strip out what he doesn't need):

    #include <util/crc16.h>

    #define LED_PIN           3
    #define LED2_PIN          4

    #define TX_PIN            2
    #define TX_BAUDRATE       2000
    #define TX_MICROINTERVAL  (1000000UL/TX_BAUDRATE)
    #define TX_MAXLEN         12

    #define TRIGGER_PIN       0
    #define ECHO_PIN          1

    inline void led(const bool onOff) { digitalWrite(LED_PIN, onOff ? HIGH : LOW); }
    inline void led2(const bool onOff) { digitalWrite(LED2_PIN, onOff ? HIGH : LOW); }
    inline void tx(const bool onOff) { digitalWrite(TX_PIN, onOff ? HIGH : LOW); }
    inline void trigger(const bool onOff) { digitalWrite(TRIGGER_PIN, onOff ? HIGH : LOW); }

    const uint8_t header[8] = { 0x2A, 0x2A, 0x2A, 0x2A, 0x2A, 0x2A, 0x38, 0x2C };
    const uint8_t conv4to6[16] = { 0x0D, 0x0E, 0x13, 0x15, 0x16, 0x19, 0x1A, 0x1C,
                                   0x23, 0x25, 0x26, 0x29, 0x2A, 0x2C, 0x32, 0x34 };

    void rawSend(const uint8_t * p, uint8_t len) {
      while (len--) {
        const uint8_t val = *p++;
        for (uint8_t mask = 1; mask != 0x40; mask <<= 1) {
          tx(val & mask);
          delayMicroseconds(TX_MICROINTERVAL);
        }
      }
    }

    void send(const uint8_t * buf, const uint8_t len) {
      //  First create the payload ...
      static uint8_t payload[(TX_MAXLEN+3)*2];
      uint8_t * p = payload;
      uint16_t crc = 0xFFFF;
      uint8_t v = len + 3;
      crc = _crc_ccitt_update(crc, v);
      *p++ = conv4to6[v >> 4];
      *p++ = conv4to6[v & 0x0F];
      for (uint8_t l = len; l--;) {
        v = *buf++;
        crc = _crc_ccitt_update(crc, v);
        *p++ = conv4to6[v >> 4];
        *p++ = conv4to6[v & 0x0F];
      }
      crc = ~crc;
      v = (uint8_t)crc;
      *p++ = conv4to6[v >> 4];
      *p++ = conv4to6[v & 0x0F];
      v = (uint8_t)(crc >> 8);
      *p++ = conv4to6[v >> 4];
      *p++ = conv4to6[v & 0x0F];

      //  Now transmit the header and the payload ...
      rawSend(header, sizeof(header));
      rawSend(payload, (len + 3)*2);
      tx(false);
    }

    void setup() {
      pinMode(LED_PIN, OUTPUT);
      pinMode(LED2_PIN, OUTPUT);
      led(false);
      led2(false);

      pinMode(TX_PIN, OUTPUT);
      tx(false);

      pinMode(TRIGGER_PIN, OUTPUT);
      pinMode(ECHO_PIN, INPUT);
      trigger(false);
    }

    int measure() {
      trigger(false); delay(10); trigger(true); delay(10); trigger(false);

      //  We support up to 6m, i.e. 6000mm, so that would take
      //  6000mm * 2 / 0.34mm/ms = 35294ms to get to the end
      //  and back, hence let's use a timeout along those
      //  lines ...
      unsigned long duration = pulseIn(ECHO_PIN, HIGH, 36000);
      if (!duration || (duration > 35500)) return 0;
      return (int)(duration * 34 / 200);
    }

    int bufferedMeasure() {
      static int lastVal = 0;
      static bool toggle = true;
      int newVal = measure();
      if (newVal) {
        led2(toggle);
        toggle = !toggle;
        lastVal += (newVal-lastVal)/10;
      }
      return lastVal;
    }

    // the loop routine runs over and over again forever:
    void loop() {
        //  Measure the distance ...
        int val = bufferedMeasure();
        if (val) {
          static unsigned long data;
          led(true);
          data = 0xD1570000UL|val;
          send((const uint8_t *)&data, sizeof(data));
          led(false);
        } else {
          led(true); delay(100); led(false); delay(100);
          led(true); delay(100); led(false); delay(100);
          led(true); delay(100); led(false);
        }
        delay(1000);
    }


message:
How to connect 5V sensors to 3.3V digital input (Due)?

I'm completely new with Arduino and microcontrollers in general.

I have several 5V sensors, and need 3.3V because that's the max for the Due. Is it possible to use a resistor to connect it to the Arduino? Do I have to measure the current from the sensor and calculate the needed resistor like this?

    $$\frac{5.0 - 3.3}{\text{Measured current}}$$
    (5.0 - 3.3)/(Measured current)

body:
Well if you're not sure of what you're doing, you can always go with **level-converters** for your sensors (that does not apply to shields though)

Level-converters (sometimes called **level-shifters**) come in different flavors:

- breakout board (the easiest to work with)
- IC
- DIY circuits with a few components

Some are "one-way": they have pin-pairs with converters 3.3V -> 5V, and other pin-pairs with 5V -> 3.3V conversion; others are bi-directional, i.e. you can use the same pair of pins in 2 directions 3.3V <-> 5V.

There are plenty of these converters, and they are rather cheap; here are just a few examples:

- [one-way breakout][1] usable with 4 pairs of pins
- [bi-directional breakout][2] usable with 4 pairs of pins
- 74HC4050 IC discussed [here][3]

  [1]: https://www.sparkfun.com/products/11978
  [2]: https://www.sparkfun.com/products/12009
  [3]: http://forum.arduino.cc/index.php?topic=109493.0


message:
Is there a transmission protocol library for SPI?

When communicating over SPI, one byte is sent at a time. Is there a library (C or C++) that allows for sending strings? Essentially it would be a protocol library handling the start and the end of a message, as well as integrity checking. (I'm using an Arduino.)

body:
Each spi peripheral has its own protocol in the sense of commands and addresses if any and data.  Spi simply makes a common ground for chip select vs clocks and clocks vs data and separate miso and mosi data lines.

So a general purpose library doesnt make sense.

Also spi certainly is not limited to a byte, many peripherals and many spi controllers allow for long sequences of data, you are also not strictly limited to multiples of 8 bits either although that is the norm.

Your arduino spi master may have its limitations but that has nothing to do with spi in general.

Integrity testing is not part of the spi protocol, you get what you get.  Ideally all of the parts are soldered down on the same board or through known connectors and the margins have been designed in.  You would need to do something outside the spi protocol, for example if it is a spi flash then after you read a chunk of data you can do a checksum and compare it with a checksum you have embedded in the data (or crc).  If it is a spi ethernet part you may choose to leave the frame checksums in the frames and re-validate each frame yourself.  If you create your own peripheral (hardware design or cpld or fpga) then certainly you can add a crc or checksum to every transfer if you wish.


message:
Arduino Nano uploading gives error: avrdude: stk500_recv(): programmer is not responding

I have a [Arduino Nano (Sainsmart)][1] that I'm trying to upload a sketch to. Under the Arduino IDE, the device selected was `Arduino Nano w/ ATmega328`.

However uploading the sketch gives me the error

    avrdude: stk500_recv(): programmer is not responding

I tried both USB ports (`/dev/tty.usbserial` & `/dev/cu.usbserial`) but the same error persist. The Arduino is connected to a Macbook Air via the USB cable, and the `PWR` LED indicator light on the Arduino is turned on and the `L` indicator LED blinks. There was no problem uploading to a Arduino Uno.

Retried after installing the latest FTDI drivers (MAC OSX, x64, v2.2.18, FTDIUSBSerialDriver_10_4_10_5_10_6_10_7.mpkg) from http://www.ftdichip.com/Drivers/VCP.htm. However that did not help.

What could have gone wrong?

  [1]: http://www.amazon.com/SainSmart-Nano-v3-0-Compatible-Arduino/dp/B00761NDHI/

body: This error message basically shows up for any communication problem, so by itself, it is not all that instructive. The Arduino Nano is supposed to have auto-reset, but maybe your clone does not? In that case, you'd have to press the reset key on the board just before starting an upload.


body:
Did you remember to tell the IDE that the board type is a Nano?

`Tools` -> `Board` => `Arduino Nano ...`

This gets me every time I swap between my Nano and Uno.


body:
I also had that error message. I think there are many possible causes, so I haste to specify my special case.

I have a hackintosh with OS X Yosemite 10.10.2, Arduino software 1.0.6 and Funduino UNO. Uploading the example for Serial.write() succeeded the first time. Thereafter most uploads failed. Even when the upload succeeded the serial monitor would not always show output.

This seemed to me to be due to miscommunication on the USB port. I had to repeatedly reset the funduino, unplug and replug the USB cable or even restart the system. When replugging the USB cable sometimes my system would freeze.

By googling I found a solution to "Inserting USB device causes Mavericks 10.9.1 to freeze".
Answer no 12 on tonymacx86.com basically instructs you to remove GenericUSBXHCI.kext from /System/Library/Extensions.

I am happy to report that after removing this kext I have no problems uploading the example and monitoring the output. Because I don't need to replug the USB cable I don't know whether this solves my system freeze. I'm not even sure it was a system freeze, because my system may only have become unresponsive to my USB keyboard and mouse.


body:
Having a similar issue with my `Sainsmart Nano`.

Under `Preferences` check "Show verbose output during [x] upload, then when uploading, you should get a red trace like this:

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

             System wide configuration file is "/Applications/Arduino.app/Contents/Resources/Java/hardware/tools/avr/etc/avrdude.conf"
             User configuration file is "/Users/johannes/.avrduderc"
             User configuration file does not exist or is not a regular file, skipping

             Using Port                    : /dev/tty.usbserial-A403MRTP
             Using Programmer              : arduino
             Overriding Baud Rate          : 57600
    avrdude: Send: 0 [30]   [20]
    avrdude: Send: 0 [30]   [20]
    avrdude: Send: 0 [30]   [20]

You'll notice a little "pause" just before the first line of `avrdude: Send: 0 [30]   [20]`. Try uploading again and have you finger ready on the physical reset button of your `Nano`. *Just the moment before the first `avrdude: ...` appears, press the reset button.*

When you succeed, you'll see the screen filling with all sort of gibberish, and ending something like this after a few seconds:

    [78] . [00] S [53] h [68] o [6f] u [75] l [6c] d [64]   [20] b [62] e [65]   [20] 0 [30] x [78] 4 [34] 9 [39] D [44] 4 [34] . [00] . [01] . [00] . [00] . [00] . [02] . [00] . [03] . [00] . [04] . [00] . [00] . [00] . [00] . [00] . [e6] . [06] . [b5] . [06] n [6e] . [06] w [77] . [06] . [8c] . [06] . [9d] . [06] . [00] . [00] . [00] . [00] . [02] . [0d] . [aa] . [0d] . [95] . [0c] . [c9] . [0c] . [a9] . [0c] . [f2] . [0c] . [00]
    avrdude: Recv: . [10]
    # | 100% 3.71s

    avrdude: verifying ...
    avrdude: 8824 bytes of flash verified
    avrdude: Send: Q [51]   [20]
    avrdude: Recv: . [14]
    avrdude: Recv: . [10]

    avrdude done.  Thank you.


body:
I was having the same problem and got the same error message.  Turns out these boards don't come with a bootloader preinstalled.  If you have some jumper wires and another working arduino you can use this [tutorial][1] to install the bootloader and it should work great, mine did at least! :)

  [1]: http://www.instructables.com/id/How-To-Burn-a-Bootloader-to-Clone-Arduino-Nano-30/step3/Simple-few-steps/


body:
Had same issue and solution was as follows:

- identified my arduino as CH340/ATmega168P (written on PCB)
- went to IDE and picked from list not UNO but "Arduino Pro or Pro Mini"
- when this option is selected new menu "Processor" selection is available (just under Board selection)
- selected my processor ATmega168P there and upload worked like a charm!


body:
The Arduino IDE version 1.8.5 gave the same error every time I tried to connect it to my OSEPP Nano.  I tried with multiple nano boards with different versions of the IDE. I had the board set to "Arduino Nano".

The solution was: **Instead of Nano choose Arduino/Genuino Uno**. This worked for me.


body: If this doesn't work you will have to use spi to program the nano.  You'll need to look up the connection and use a uno since it has a serial chip at16u2 with a driver that recognizes all atmel products.  After connections setting uno as a programmer by flashing the uno as isp set the programmer as Arduino as isp and flash the chip.  Double check.  The benefit is it is less error prone than uart and has better timing but is a hassle to wire up.  Good Luck


body:
Know this is old but I ran onto it during my search for Nano(V3)'s not uploading so thought might help someone else.  Problem is the bootloader - Arduino IDE BUT I Found an easy solution (right under my nose).

I realized that my nano's had been uploading just fine then I had finally updated the Arduino AVR Boards from 1.6.20 to 1.6.21.  I didn't think there was any problems because it still showed my Nano and ATmega328 etc in the board manager after the change.

But the new boards manager has a new ATmega328 processor choice for the Nano. I changed processor: In the Arduino IDE select `TOOLS` > `PROCESSOR` > pulldown menu from ATmega328P to  `"ATmega328P (Old Bootloader)"`.

Since then, I have uploaded many programs to several different Nano's V3 (Prolofic interace Chipset) without issue.


body:
That problem, ocurred to me when I upgraded the Arduino IDE. I solved it by changing the processor to "old"

Tools->Processor->"ATmega328P (old bootloader)"
thanks!!!!


body:
I recently had the same issue with 3 Nano boards I just purchased from Amazon.  I can confirm that the suggested fix (changing to "old bootloader") solved my problem.

I think the main problem is the upload speed.  The "old bootloader" version successfully uploads at 57600, but the default "new" version tries to upload at 115200 and fails.


body:
Ok. I had the same `programmer is not responding` error on Arduino Nano on Atmel MEGA168PA, USB chip: CH340G. Macbook Pro under macOS 10.14.2.

It hand Blink example installed and the port wasn't visible in the list.

I was trying to figured out, whats wrong and connected my **Arduino Due** through the programming port. After 2 attempts the sketch was uploaded... Then I connected the Nano back, the port was visible this time (actually two of them: `/dev/cu.wchusbserial14120` and `/dev/cu.usbserial-14120`) and guess what, the upload had been successful!

Magic!


message:
Should I try to make my sketches as small as possible, even when I have enough room?

There has been a lot of talk about shrinking sketches recently, but if you don't need the room, should it be done? Will it speed up my program?

Take this code:

    int led = 13;
    int val;

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

    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

      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

      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

      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

      val = digitalRead(10);
    }
1,396 bytes on Arduino Uno. Now let's shrink it a bit:

    int led = 13;
    int val;

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

    void loop() {
      blink();
      val = digitalRead(10);
    }

    void blink() {
      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
    }
1,270 bytes. A 10% decrease! It could be shrunk even more. **I have the space... is it more efficient (as far as speed) to make it the most compact I can or leave it "uncompressed?"** I would imagine that it would be a little more work (not much) calling `blink();`, therefore slowing down my code. Is this true? Are there other advantages/disadvantages of making it as small as possible (besides storage/distribution of C++ files)?

body:
Generally speaking, smaller is better. However, there is a point where too small actually makes the program run slower.

My suggestion is if you are working on a sketch and it is blatantly obvious that you are repeating code over and over again, I would rip that out and put it into a function, not only does it make the program smaller, it makes it easier to read.

There is also some optimization going on behind the scenes as well during compilation, so even though the C/C++ code looks to be large, chances are the compiler/linker are determining that something are repeats and consolidating them... Or at least the AVR compiler I used previously did, cannot remember if Arduino does this.


body:
You second code may be smaller in size but due to the function call overhead the max execution speed is reduced.
Does this matter in your case? No, because you have huge delays anyway, but if the code was an actual series of repeated calculations that should be executed as fast as possible then it would make a difference.

As a general rule, smaller code is not necessarily faster too.

For code optimization (either size or speed) you can refer to this application note from Atmel [AVR4027: Tips and Tricks to Optimize Your C Code for 8-bit AVR Microcontrollers](http://www.atmel.com/images/doc8453.pdf)

I could repeat everything it says here but I don't think there is a point, you can read the original article directly.

----------

Regarding the compiler optimization level. Arduino IDE uses the avr-gcc compiler with a setting for **Os** optimization.
The avr-gcc available optimization levels are ([source1](http://www.network-theory.co.uk/docs/gccintro/gccintro_49.html) [source2](http://gcc.gnu.org/onlinedocs/gcc-4.3.3/gcc/Optimize-Options.html#Optimize-Options))

 - **O0 or no -O option**
    At this optimization level GCC does not perform any optimization and compiles the source code in the most straightforward way possible. Each command in the source code is converted directly to the corresponding instructions in the executable file, without rearrangement. This is the best option to use when debugging a program and is the default if no optimization level option is specified.

 - **O1 or -O**
    This level turns on the most common forms of optimization that do not require any speed-space tradeoffs. With this option the resulting executables should be smaller and faster than with -O0. The more expensive optimizations, such as instruction scheduling, are not used at this level. Compiling with the option -O1 can often take less time than compiling with -O0, due to the reduced amounts of data that need to be processed after simple optimizations.

 - **O2**
    This option turns on further optimizations, in addition to those used by -O1. These additional optimizations include instruction scheduling. Only optimizations that do not require any speed-space tradeoffs are used, so the executable should not increase in size. The compiler will take longer to compile programs and require more memory than with -O1. This option is generally the best choice for deployment of a program, because it provides maximum optimization without increasing the executable size. It is the default optimization level for releases of GNU packages.

 - **O3**
    This option turns on more expensive optimizations, such as function inlining, in addition to all the optimizations of the lower levels -O2 and -O1. The -O3 optimization level may increase the speed of the resulting executable, but can also increase its size. Under some circumstances where these optimizations are not favorable, this option might actually make a program slower.

 - **Os**
    This option selects optimizations which reduce the size of an executable. The aim of this option is to produce the smallest possible executable, for systems constrained by memory or disk space. In some cases a smaller executable will also run faster, due to better cache usage.


body:
Your refactor should be done simply because it's better code, not because it's smaller. The advantage is that it's easier to modify.

If making the code size smaller results in a loss of clarity (not so in your case), then you should probably view it as a [premature optimization](http://c2.com/cgi/wiki?PrematureOptimization).


body:
When your time has more worth more than the gains to be had, stop optimizing.

Are you writing for someone for pay? Then this should be their call. But in this case, readability and clarity of your code is paramount; someday, someone else will have to modify your code in your absence. If you deliver working, high performance code that someone else can't read and get a handle on, you will not have fulfilled your obligation (unless this was specifically agreed to).


body:
When considering optimization, think carefully about what resource is most valuable.

You can optimize for code size; this will let you put more code onto your processor. What will the rest of the space be used for? If your code doesn't fit onto your arduino, and your alternative is buying a larger chip, then this is worth the effort.

You can optimize for speed - you can run more code in the same amount of time. If you are sampling data once per second, and sleeping the rest of the time, then this won't help.

You can optimize for power usage - very important if you're on a battery, less important if you are on mains. This might also not just be power consumed by the arduino, but also sensors & motors - can they be turned off for a while?

There are two optimizations that a lot of programmers forget - optimizing for development time, and optimizing for readability.

Any optimization for one thing will tend to de-optimize for at least one (often several) other things. If you don't know which optimization is going to be most useful, then go for readability, then development time (because today's readability = tomorrow's development time x 10!)

Usually, the most expensive thing is the development time (i.e. YOUR time, especially if you are on the clock for a customer). Most other optimization has a threshold - so long as you are over (under?) a specific threshold, further optimization doesn't help. Code size and execution speed (except when shared between competing tasks) are like this - if your code fits on the chip, then it is small enough. If it needs to do something else later, you can optimize it then. If your program can do all it needs to (assuming it is real-time; calculating Pi is a different case), then that's as fast as it needs to be.


message:
What are some steps to attach an Arduino to an electric heater?

I have the below portable electric heater, but I would love to control it's start AND stop time using an Arduino. As-is, it does not come with a stop feature. SO, I have a burning question. How can I get an Arduino to start and stop this heater at specific times of the day?

As you can see, it does have a start time, but it does not have a stop time.
The power button is a simple push button. I suspect I would need to 'interject' into that and the board by using a switch? Apologies if the terminology is off, but I'm very green.
Where would a noob begin?

-EDIT-
The unit is always off when it's plugged back in. That likely means I cannot put a timer on the power cord.

![enter image description here][1]

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

body:
Would or should begin? Don't fiddle with the internals of the heater.

Set its switch to the always on position and control switching on and off with an external relay. Make a box that has plenty of room (you can reduce size at a later moment), a power cord, a mains adapter for your Arduino and a mains outlet in which you can plug your heater.

Use:

- an [RTC (real time clock) breakout](http://www.amazon.co.uk/s/?tag=duc08-21&url=search-alias=aps&field-keywords=rtc breakout) to keep accurate time
- optionally a [7 segment display](http://www.amazon.co.uk/MAX7219-8-Digit-Display-Segment-Digital/dp/B00IHSE6V6/ref=sr_1_6?ie=UTF8&qid=1395212225&sr=8-6&keywords=7+segment+display) to display date/time. Just make sure it has a driver chip on it so you don't need your Arduino to multiplex the individual LEDs
- couple push buttons to configure the device
- a [relay](http://www.amazon.co.uk/s/ref=nb_sb_noss_1?url=search-alias=aps&field-keywords=relay+5V&rh=i:aps,k:relay+5V) rated for the maximum power of the heater to turn it on/off, that can be driven from 5V. Possibly needs a transistor and flyback diode to be controlled from an Arduino GPIO line.

And be **very** careful when experimenting with mains power, it can be leathal.


body:
**I don't know if that heater will work for sure with this approach because the buttons are weird.** However, I am 99% sure this will work.

>![][1]

*(From http://keshavsaharia.com/2012/12/01/coffeeduino/)*

Basically here's what you do:

 1. Disassemble the control panel to find the PCB where the buttons are mounted. Find which button you want to simulate a press of.
 2. Find the solder joint where the button meets the PCB.
 3. Solder a wire to the two terminals that are connected. Some buttons have three or four terminals: look at the traces on the PCB to see which buttons are connected.
 4. Wire the relay with the two wires connected so the relay acts as a switch.
 5. Make the proper connections to the Arduino board to control the relay.

In code, you can just turn the relay on for a quarter of a second or so. Then, the IC on the heater will react like you pushed the button.

Make sure to seal all of this up and make sure you don't accidentally short out any of the wires. I would say to also isolate the Arduino and relay to make sure that you don't electrocute yourself at all if something goes wrong.

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


body:
Use the Arduino to set the start and stop time. Always leave the heater switched on and use something like the 'Mains Switch widget' from SF innovations to control the mains. This unit has a mains relay, is fused to protect against fire and is enclosed in a plastic case.
[http://www.sf-innovations.co.uk/mains-switch-widget.html][1]

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


body:
To be safe use a device like the power tail from spark fun(basically a sealed relay unit, ready for you to connect to the arduino)

Much easier and safer if you don't have any experience working with 120V/240V

uses a 3-12 input to switch 120v up to 15A
https://www.sparkfun.com/products/10747


body:
The following will work and meets the requirement that the heater does not auto turn on when powered up. You need to turn the heater on manually, so no different from existing, and this then allow you to either

 - Power it down at a preselected time of day, provided the Arduino is able to keep track of time, or

 - The Arduino will turn it off a set period after it has started to heat.

The latter is easier to do and meets the need well enough.
The only technical requirements are

 - Able to sense current drawn by heater.

 - Able to turn a heater control relay on/off

 - Able to set or select a time delay on Arduino.

Of these, the current detection is hardest and even then, not very hard. Possible means include:

 - Current transformer connected to heater lead.

 - Opto isolator with LED in series with lead with suitable parallel resistor across opto LED to drop enough voltage to trigger opto on voltage peaks when heater is on,  and backwards diode across opto LED for reverse mains cycles. This provides a series of pulses to Arduino when heater is on.

**Equipment:**

Arduino controlled external relay or solid state relay.

Some means of detecting that heater is drawing current - timer mode only.

Arduino.

__________

**Arduino cct can:**

 - Detect current draw.

 - Turn relay off/on

 - Be programmed to either stop time or run time.

 - Drives external relay or solid state relay.

 - Optional: Relay defaults on.

**Then:**

Set external Arduino timer to desired time.
Arduino sets relay ON.
Set heater to desired start time.
When heater start Arduino sees current and starts timing, or in time of day mode just turns off power at correct time.

This keeps all circuitry external.


message:
Most compact method of powering Arduino from wall socket

There are a lot of methods to power an Arduino from a large range of voltages:

- USB cable from PC or from a phone charger or an USB hub
- step down converters
- step up converters
- switching power supply
- batteries (connected to the power jack or USB or to Vin)

What I can't seem to find is a small 220V-5V converter. I'd like to put an Arduino in the wall, under a light switch, so size matters.

The last resort option is to open a 5V phone charger and replace the metal prongs that go in a socket with two wires, and replace the USB socket with another pair of wires that go the Arduino board, but still, an Arduino Pro Mini or an Arduino Nano is smaller than the phone charger.

body: What if you replace the nearest outlet with some kind of [USB Wall Socket](http://www.alibaba.com/product-detail/Nice-Dual-USB-Wall-socket-For_1518461365.html) and attach to that (either through a standard USB plug, or inside the wall) ?


body:
> The last resort option is to open a 5v phone charger and replace the metal prongs that go in a socket with two wires, and replace the usb socket with another pair of wires that go the arduino board, but still, an Arduino Pro Mini or an Arduino Nano is smaller than the phone charger.

You will probably have to do something like that.

<img src="https://upload.wikimedia.org/wikipedia/commons/thumb/7/7c/Wall_wart_opened.JPG/800px-Wall_wart_opened.JPG" >

Because of the nature of conversion between AC and DC, there has to be some large parts.* I'm not going to go into the specifics here. There is usually a diode bridge (because AC waveforms reverse the current ~60 times a second) and a transformer (to lower the voltage for the diode bridge). They almost always include a regulator and a capacitor to make sure voltage is exact and it outputs a "clean" power supply.

*[Switching power supplies](http://en.wikipedia.org/wiki/Switching_power_supply), although considerably more expensive, are a lot smaller and more power efficient.

[This adapter](http://www.amazon.co.uk/Xcessor-Compact-European-Wall-Charger/dp/B00DVLHZOE/ref=sr_1_1?s=electronics&ie=UTF8&qid=1395244016&sr=1-1&keywords=220v+usb+adapter) seems to be the most compact adapter I can find for 220V. You'll never get something near the size you are desiring, even with a switching power supply. I don't know the size of the Amazon adapter I gave a link for, but in the US (120V), iPhone chargers are very small and they should fit in a standard depth outlet box (with a little room left over for relays and such). If you *really* need to get everything smaller, I recommend using a ATtiny chip.

**How I recommend connecting this:**

I would avoid ripping this apart at all costs from a safety perspective. It would be really easy to send 220V to your Arduino if you're not careful. If you *absolutely have to*, you might want to coat it with some non-conductive epoxy or other coding. Note: this may act as a thermal insulator, therefore reducing the lifespan of the part. You should just coil some wire around the prongs, and then melt a little solder onto each of the terminals. Then, cover that with electrical tape and pigtail (with a wire nut) into a source power line. Note: you probably are doing wiring that could be illegal in your area. Check your local building codes before attempting this.

After that, attach a USB cord to the socket and to the Arduino or the ATtiny/ATmega328 chip 5V/GND input (of coarse, after cutting and stripping one end of the USB cord). I would also, after finalizing all the code and circuitry, seal that with some epoxy or somehow add it to an enclosure to make sure you don't fry your Arduino if a loose wire touches the Arduino circuitry.

## If you don't feel safe doing any of the above, *don't do it*. You can live without a Arduino light switch.
That being said, happy hacking! :P


body: The smallest is probably a plug-in USB charger such as Apple's tiny cube. The cheapest is bound to be a ~9v (output) wall-wart scrounged from the lost and found in a tourist's/traveller's hotel.


body:
I can suggest you to try this : [AC DC Step Down Converter][1]

It is as small as the Apple's tiny cube, and it can be placed inside of a wall easily. (I'm personally using this with an arduino micro)

  [1]: http://www.aliexpress.com/item/220V-to-5V-AC-DC-Step-Down-Converter-5V-800mA-Switching-Power-Supply-Module-AC-85/1488428284.html


body:
Nowadays, most smartphones come with a charger that is linked to the USB plug of the phone.

The charger for my HTC says: **5V**, **1A**, I guess this voltage must be regulated (but I haven't checked it has the charger is sealed).

![enter image description here][1]

The charger itself has a female USB socket on which you can plug any USB cord to link to your Arduino.

**IMPORTANT!** I have never tried it myself! I would not bet my life on it! It would be wise to check the output voltage is well regulated.

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


body: There are small board-mount AC/DC converters like this one http://www.digikey.com/product-detail/en/BP5063-5/BP5063-5-ND/658569


body:
This looks like the smallest and cheapest one from all of the above mentioned:
http://www.ebay.co.uk/itm/AC-DC-Power-Supply-Buck-Converter-Step-Down-Module-5V-700mA-for-Arduino-U-/121355318138


body:
An obvious answer has been omitted which is: transformerless power supply.
If your average power requirements are low (<10mA) then this is the most compact way to achieve the desired voltage.

For an in-depth study see: http://ww1.microchip.com/downloads/en/AppNotes/00954A.pdf

Another solution: jeelabs.org /2011/11/27/ultra-low-power-supply/

Some limitations:

- **safety - NONE** - your circuit might now be floating at line voltage
- heat dissipation - calculate here: www. daycounter.com/Circuits/Transformerless-Power-Supplies/Transformerless-Power-Supplies.phtml
- low current - no servos or relays
- voltage fluctuations on the line might affect the circuit


body:
wanted to do a similar thing and I found and just ordered these:

http://uk.farnell.com/recom-power/rac03-05scr-277/conv-ac-dc-3w-90-305v-in-5v-out/dp/2289701

A fully sealed power supply, disk-shaped, 5cm diameter and 11mm thick. THey are available in 3.3V, 5V, and 12V. They are designed to be put inside walls or behind switches.


body:
I use this one, 5V, 3W, very small, and only $3 on Aliexpress.
http://www.hlktech.net/product_detail.php?ProId=54


body: Try an LED driver. Their typical output is 11.8V DC, which is in perfect specs for the Arduino. You can find them nowadays in all shapes and sizes, round or square, low profile or boxy. A 500ma version (6W) is more than enough for your needs.


body:
Try something like [this][1]. It's 29x15mm and does 220V AC to 5V/3W DC.

  [1]: http://www.ebay.com/itm/1PCS-AC-DC-Isolated-Power-Supply-Module-220v-to-5v-Step-down-Power-module-/181777324025


body:
Nov 2016
Here is a list of compact PCB mounted power supplies that are small (~50mmx25mmx20mm) from Mouser:

http://www.mouser.com/Power/Power-Supplies/AC-DC-Power-Modules/_/N-dv0g5?Ns=Output+Current-Channel+1|0&No=25&P=1yxt7eu

These all take in 120-240VAC and provide outputs in the range of 3 - 5 vdc with varying options for current.

The 5V 1A from Meanwell (IRM-05-5) looks like a good deal at $8.52 each.
http://www.mouser.com/ProductDetail/Mean-Well/IRM-05-5/?qs=sGAEpiMZZMuWiaalG5TUgH52QN1%2bIKAVmGC9ENLDVf688EuOMfqROg==

Paul.


body: It's entirely dependent on whether or not you want to isolate the circuit from the mains. You could use a drop resistor a rectifier and a 5v zener diode but I do not recommend this if you are a hobbyist, in fact I don't recommend this at all, but it is done by some manufacturers with appropriate circuit protection.