body:
I need to communicate between two Arduinos using XBee. I am new to XBee and hardware. The two Arduino Unos need to send a message (number) to each other and light an LED or play a sound, when they come close within a 10 meter distance.

So my doubt is which XBee shield and XBee module I need to purchase. I read about XBee series 2, XB24 etc.

title: XBee shield communication

Answers: 3

body:
The "XBee" brand has two major types. Series 1 are the original ones, and are often NOT referred to by their series number. Series 2 are the newer mesh network brethren.

Most XBee's and their clones are pin compatible (there is even a Bluetooth replacement 'Bee), thus any XBee shield or adapter can be used for either series.

The difference is largely in their communication protocols. The Series 2 allow more robust mesh networking options. But for a beginner - the original (S1) provide simpler out-of-the-box networking.

There are retail packages available that include a pair of S1 XBees, an Arduino compatible breakout board, and a USB adapter to program them. This allows you to get "on the air" and setup the XBees quickly. For communication between two arduinos, a pair of shields will make physical connectivity much easier.

body:
Adding to Ron's answer, the Series 1 is a lot easier to use, because you have to flash firmware onto Series 2s and do all kinds of setup. The S1s work out of the box.

Another thing to keep in mind is that Xbees use 3.3v I/O pins, while the Arduino uses 5v. Most Xbee shields have a Logic Level Converter to handle this, but there are some that don't, and those could damage your Xbee.

body:
The only way I can think of accomplishing this without some sort of proximity sensor is to measure the signal strength of the XBees.

From [page 41 of the datasheet][1]:

> **DB (Received Signal Strength) Command**
>
> **AT Command:** ATDB
>
> **Parameter Range [read-only]:**  0x17-0x5C (XBee), 0x24-0x64 (XBee-PRO)
>
> <Diagnostics> DB parameter is used to read the received signal
> strength (in dBm) of the last RF packet received. Reported values are
> accurate between -40 dBm and the RF module's receiver sensitivity.
> Absolute values are reported. For example: 0x58 = -88 dBm (decimal).
> If no packets have been received (since last reset, power cycle or
> sleep event), “0” will be reported.

You can use this as a **rough** estimate of the distance between two sensors. You will have to correlate signal strength to actual distance and obstructions and other factors will cause the reported value to be off.

[How to measure XBee signal strength?][2]

This page has an example using Processing (on the computer): [XBee Signal Strength][3]

  [1]: https://www.sparkfun.com/datasheets/Wireless/Zigbee/XBee-Datasheet.pdf
  [2]: http://forum.arduino.cc/index.php?topic=151145.0
  [3]: http://www.makingthingstalk.com/chapter8/22/


body:
I have done various applications with the Ultrasonic [example project](https://github.com/alexmac131/NodeXbeeTank) but it is always using one pinger. I'd like to make a scanner resting on a servo sweep but to reduce sweep time use more than one censor.

the documentation is rather basic [ping sonic](http://www.parallax.com/sites/default/files/downloads/28015-PING-Sensor-Product-Guide-v2.0.pdf) that states the signal 40khz is used.

Down to the question now. Is there a means to tell one pinger to use 40Khz and another say  45Khz.

This would allow me to scan two areas (different directions) per cycle, reducing the time frame to complete area scan by half.

title: Using more than one Ping Ultrasonic Range Finder

Answers: 3

body: I don't think it would be very easy to change the frequency unless Parallax decides to release the firmware for the Ping. It is possible to use two, as long as you use a different data pin for each, but the ultrasonic signals may interfere.

body:
There is no way to change the frequency, however there are other ways of doing what you want to accomplish. I think the best thing to do is stagger the timing of the pings so they don't happen at the same time.

Example code, modified by me:

    #include <Servo.h>
    Servo servo; // create servo object to control a servo

    int pingPins[] = {7,8}; //The pins for the two sensors
    char *pingString[] = {"Ping1", "Ping2"};

    void setup()
    {
      servo.attach(10); // attaches a servo to pin 10
      Serial.begin(9600);
    }

    void loop()
    {
      unsigned long ultrasoundValue;
      for(int i = 0; i < ultraSoundSignalPins.length; i++)
      {
        ultrasoundValue = ping(i);
        Serial.print(pingString[i]);
        Serial.print(": ");
        Serial.print(ultrasoundValue);
        Serial.print("in, ");
        delay(50);
      }
      Serial.println();
      delay(50);
     }

    //Ping function
    unsigned long ping(int i)
    {
      unsigned long echo;

      pinMode(pingPins[i], OUTPUT);         // Switch signalpin to output
      digitalWrite(pingPins[i], LOW);       // Send low pulse
      delayMicroseconds(2);                 // Wait for 2 microseconds
      digitalWrite(pingPins[i], HIGH);      // Send high pulse
      delayMicroseconds(5);                 // Wait for 5 microseconds
      digitalWrite(pingPins[i], LOW);       // Holdoff
      pinMode(pingPins[i], INPUT);          // Switch signalpin to input
      digitalWrite(pingPins[i], HIGH);      // Turn on pullup resistor
      echo = pulseIn(pingPins[i], HIGH);    //Listen for echo
      return (echo / 58.138) * .39;         //convert to CM then to inches
    }

Sources:

 - https://stackoverflow.com/questions/20273971/arduino-multiple-ultrasonic-sensors-interference
 - http://forum.arduino.cc/index.php?topic=17898.0

body:
The Ping))) sensor uses a crystal for timing.
Some of the cheap knock-offs actually use a MAX3232 chip (which is an RS232 serial port/usart) to detect the return pulse, just for the carrier detection. If the parallax is similar, these have a fairly wide range of frequencies they work at, since you never know the baud rate to expect, from 9600 up to 1mhz, although they are deliberately not very fussy about accidentally picking up nearby frequencies.
Since there's probably some other logic on the other chips, and everything is probably run off the one crystal, I'd recommend going to lower frequencies, otherwise you're overclocking.
Also, make sure to send a longer trigger pulse because all the logic will be slower.
From the picture, it looks like a 16MHz crystal, which must be divided down to the 40KHz.
So solder in a 14MHz, and an 11MHz, lengthen the 5 uS trigger pulse accordingly, and you should be good to go.

As an aside, you might also consider scanning further apart. If it's taking you 30 seconds, you're probably checking every degree; maybe try every 15 or 30 degrees (just make sure to give the servo time to move)


body:
I am trying to build a device that will allow me to control at least a couple hundred raising platforms. The goal of this is to create a real time editor for board games (*Dungeons and Dragons*).

Ideally:

 - All the platforms would move simultaneously
 - The platforms would be transparent to allow us to place LEDs inside them to color the platform so we can make colors like blue for water and brown for dirt.

In our current setup, we use some acrylic prisms that are 1 inch x 1 inch x 6 inch (width, length, height). We wanted to use a CNC motor like system to move something around and move a platform. Obviously, this can only raise/lower one item at a time. We calculated (on paper) quite a long update time (calculated approximately 1 sec per platform) to raise/lower a platform. A CNC linear drive type system is the only solution we found that had a reasonable cost/quality (a CNC motor for every platform also raised the power consumption very high). After a few weeks of looking around, planning and throwing stupid ideas away, we found [this](http://www.youtube.com/watch?v=lvtfD_rJ2hE).

Clearly, it's way better then our idea but I have no idea how they did this. They have 900 platforms and they all work simultaneously. We also don't need real time interaction. Loading from computer and staying static until we change it is good (though water movement would be really nice).

What would you guys recommend to raise simultaneously a thousand small platforms?
****
After looking at this [document](http://tmg-trackr.media.mit.edu:8020/SuperContainer/RawData/Papers/527-inFORM Dynamic Physical Affordances/Published/PDF) that the devs made, and doing a bit more research I found that the device they used to move the platforms cost approxomently $30; I don't think I need to say this, but I don't have $27,000.

Key difference between their implementation and our goal:

 - No real-time interaction with the table. Controlled by an Arduino is fine.
 - Size of the platforms will be closer to 1 inch^2
 - All sides of the platform should be light up, but I believe this is mostly a question of choosing the right material

title: How do I manipulate a large number of moving platforms?

Answers: 1

body:
In terms of cost, perhaps it would be best to build a 4x4 prototype.

My first thought was to use inexpensive servos with a flexible rod inside a sheath, perhaps a wire, like a bicycle brake/gear.  The amount of movement could then be governed by the size of the armature on an inexpensive servo.

Servos will position themselves after being given the command, so there's no need to wait and do them one-by-one.  Fire off the command, then use some sort of multiplexed output like multiple 74HC595 shift registers to connect to the next one.

If the tiles were spring loaded, such that they returned to the topmost position by themselves, only a simple pull-string is needed to adjust the tile height.  Even a very light filament (like fishing line) would be strong enough for the pull.  This would allow the servos to be positioned even some metres away from the table.


body:
I have a [Parallax 27800 2-Axis Joystick][1] wired up to a [AVR 14 Pin 20MHz 8K 12A/D - ATtiny84][2]. The joy stick sends out a x y analog signal. I have programmed the Attiny84 to read the signals and set one of the attiny84 pins (high or low) depending on the direction of the joystick. In this example, each pin is wired up to a LED. The problem I am having is there is about a 1 second delay for the LED to light. The Attiny84 has a built in 8MHz clock. Would connecting an external 20MHz crystal fix this issue?

  [1]: http://www.radioshack.com/product/index.jsp?productId=12345958
  [2]: https://www.sparkfun.com/products/11232

    int UD = 0;
    int LR = 0;

    int DWN = 0;
    int UP = 1;
    int LEFT = 4;
    int RT = 5;

    int LRMID = 0;
    int UPMID = 0;
    void setup(){

      pinMode(DWN, OUTPUT);
      pinMode(UP, OUTPUT);
      pinMode(LEFT, OUTPUT);
      pinMode(RT, OUTPUT);

      digitalWrite(DWN, LOW);
      digitalWrite(UP, LOW);
      digitalWrite(LEFT, LOW);
      digitalWrite(RT, LOW);

      //calabrate center
      LRMID = analogRead(3);
      UPMID = analogRead(2);
    }

    void loop(){

      UD = analogRead(2);
      LR = analogRead(3);
      // UP-DOWN
      if(UD < UPMID - 5){
       digitalWrite(DWN, HIGH);
      }else{
       digitalWrite(DWN, LOW);
      }

      if(UD > UPMID + 5){
       digitalWrite(UP, HIGH);
      }else{
       digitalWrite(UP, LOW);
      }
      // LEFT-RIGHT
      if(LR < LRMID-5){
       digitalWrite(LEFT, HIGH);
      }else{
       digitalWrite(LEFT, LOW);
      }

      if(LR > LRMID +5){
       digitalWrite(RT, HIGH);
      }else{
       digitalWrite(RT, LOW);
      }

      delay(100);

    }

title: Attiny84 and 2-Axis Joystick

Answers: 3

body:
- Are you absolutely sure your AVR is running at 8MHz, because default I believe it is scaling the 8MHz internal RC-oscillator down to 1MHz system clock. Change your F_CPU macro to 1MHz to see what happens.

<!--
- If the 8MHz (or 1MHz for that matter) clock is really the issue (which I doubt), then you can first try to set the fuses to use the internal 16MHz clock. Cheaper solution than adding an external clock circuit.
-->

body:
Several AVR devices including ATtiny 84, have a clock prescaler that can be used to lower the core frequency.

The divider can be controlled two ways.

The first way is the **CKDIV8** fuse that controls the default loaded value to CLKPR (Clock prescale register) to either

- **fuse disabled:**  Clock Division Factor 1 (clk/1)
- **fuse enabled:** Clock Division Factor 8 (clk/8)

The fuse is enabled by default and applies the clk/8 setting, it can be changed with a programmer.

The second way is by changing the prescaler value during runtime. All you need to do is to include the following header

    #include <avr/power.h>

and call one of following functions with the appropriate value you want to use

       clock_prescale_set(clock_div_1);    // Clock Division Factor 1
       clock_prescale_set(clock_div_2);    // Clock Division Factor 2
       clock_prescale_set(clock_div_4);    // Clock Division Factor 4
       clock_prescale_set(clock_div_8);    // Clock Division Factor 8
       clock_prescale_set(clock_div_16);   // Clock Division Factor 16
       clock_prescale_set(clock_div_32);   // Clock Division Factor 32
       clock_prescale_set(clock_div_64);   // Clock Division Factor 64
       clock_prescale_set(lock_div_128);   // Clock Division Factor 128
       clock_prescale_set(clock_div_256);  // Clock Division Factor 256

[power.h manual](http://www.nongnu.org/avr-libc/user-manual/group__avr__power.html)

Note that the above functions can be applied at any part of the program, for example you can lower the cpu frequency to reserve battery and then set it higher again for intensive tasks. Just be aware that all peripheral will work with the divided clock too so PWM, timers, SPI, UART etc will all be affected.

If the problem you are facing is caused by the clock divider being in the /8 setting then you can change it at runtime.

Add the header at the start of the sketch

    #include <avr/power.h>

And then set the prescaler value to 1 at the start of setup()

    void setup() {
                   clock_prescale_set(clock_div_1);  // set the clock prescaler to /1
    }

body:
While @alexan_e’s suggestion fixed your practical problem, I would argue that it did not address your root cause, which is that whatever board setting you’re working from in boards.txt assumes a clock rate of 8MHz, while in reality your fuses are set to boot the microcontroller at 1MHz. This caused your delay(100) to take 800ms, and was the entire reason for the slowdown.

Instead of fixing this at runtime, as aleman_e suggested, it seems more natural to me to bring your fuse settings into alignment with your compiler settings, using the “burn boot loader” Arduino command (which on Attinys generally does NOT burn a boot loader, but only sets the fuses to be in sync with the compiler settings).

If your application is not going to become much more complex, running at 1MHz might be a more efficient choice than running at 8MHz.


body:
I have a custom Arduino ATMega328 board that generally runs at 5V @ 8MHz (using the Arduino Pro 3.3V 8MHz profile and bootloader). The main reason I'm using this setup is so that I can put the board to sleep when main power is disconnected and it starts being run off of battery power (3V from a coin cell). The 5V and 3V sources are diode OR'ed together and the 5V input is tied to INT0. In code, when it detects that INT0 has fallen low, it initializes sleep mode and everything powers down with the exception of the watchdog timer that keeps a 1Hz cycle to keep an internal count and check it the chip should be woken back up. This works *beautifully* when 5V power is applied first, then the battery is inserted, *then* 5V is disconnected. It goes to sleep and when 5V is brought back it wakes up and I can see it hasn't lost count.

However, the problem comes when 3V is applied *first*. I'm honestly not sure if it's even booting. But what it is supposed to do is boot, check if INT0 (Digital 2) is low and, if so, go right to sleep. By watching the current draw I see that it powers up to a few mA for a couple seconds, then drops to about 0.3mA (still higher than it should be in sleep mode). But when I re-apply 5V, *nothing*. The power draw goes back up but it is unresponsive (over FTDI serial).

Is there maybe something I'm missing that it can't be booted on 3V... in theory it should run just fine.

**Update:** I dropped an LED onto D13 and tried the blink sketch. Works fine when starting from 3V or 5V. However, when I run my firmware and start it from 3V, the LED just starts flashing wildly. I have no idea what's causing it since I never even setup D13 as anything in my code. But it makes me thing it's something to do with the bootloader...

title: Bootup on lower power not functioning

Answers: 3

body:
I think the problem is with your bootloader, but not in the way you think.

When an Arduino starts up, a bootloader profiting several tasks, such as looking for a serial host or loading program data from flash is going to take a lot more energy than a sleeping Arduino.

I think the reason why your Arduino will not start is because the bootloader requires an accurate clock source, but applying 3v to it will mess up that clock and it will perhaps crash or wait for 3.3v to be applied for a stable source.

Looking at the datasheet:

![copyright ATMEL][1]

We see that current draw while waking up (running the bootloader) is probably going to be around 2mA, while sleeping current is about *0.8 microamps*. This could certainly lead to a blackout on startup without the proper current.

Perhaps you should only turn it on with 5v power, or maybe you need a higher current, higher voltage battery.

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

body:
Exactly what is happening and why cannot be determined based on the amount of info provided. However, I see at least one potential problem which would at least partially explain the symptoms described.

You said that you are using diodes to select the voltage supply, and one supply is a 3V battery. If you are using standard diodes that drop ~0.6V then the supply voltage to the MCU is only ~2.4V. If you are using Schottky diodes with a voltage drop between 0.15-0.45, the supply voltage is potentially as low as 2.5V. You have the BOD voltage set to 2.7 volts, so in theory the MCU will never boot with the battery.

As for why you can start it at 5v, drop to 3v, and bring it back up again- I'm not sure. You could be disabling the BOD in code...maybe… Not sure why it works, but it's likely not guaranteed to work.

I setup a diode switch circuit with 5v and 3.3v to see what it looks like on my oscilloscope when the voltages switch. When at 3.3v switching up to 5v, the voltage oscillates quite a bit initially. This may potentially cause some problems when the MCU tries to come out of sleep. Putting a cap between VCC and GND smoothed the signal very nicely. When switching from 5v to 3.3v, there really wasn't any oscillating, just a clean drop.

From this information, it seems that you should lower the BOD threshold or turn off the BOD, and put a decoupling cap between VCC and GND. You probably also should make sure you have a pull-down resistor on INT0, and read the MCU datasheet sections explaining the various sleep modes all the considerations for sleeping and waking – it’s pretty involved. Cheers

body: So... turned out what was happening was all in code. Turns out that I was initializing an interrupt on INT0, when it was low, at the very beginning of my code. Problem was that when it started up on 3V backup power, INT0 was always low because INT0 is tied to the 5V line (it's how it knows to go to sleep). Because INT0 was low and the interrupt was triggering on low it was causing a constant interrupt to occur, never giving the rest of the program any time to run. Switched to enabling that interrupt only once I've entered full waking mode and it works fine now.


body:
My hardware is 4 potentiometers connected to Arduino Analog 0-3, the output is an RGB led driver connected to Digital outputs 9,10,11. The output channels provide access to PWM control of those pins. So idea is the color and intensity can be controlled by the Arduino. I wrote a simple Sketch that reads the potentiometers and then outputs PWM to the RGB driver circuitry. This works great! So the hardware is working! Now comes the last potentiometer...

I want to make the last potentiometer a "mode select" control. It would function like this: If the last potentiometer (Pot4) is turned down all the way, then all lights are off. If the level is turned up a little, the Arduino then controls the RGB channels via Pots 1, 2 & 3. If Pot4 is turned up to just past halfway, the sketch enters a "strobe flash pattern" pulsing all channels on and off. And if the mode control Pot4 is turned up all the way, Arduino turns on all RGB channels.

How do I implement? Mode selection via a potentiometer?

title: How to implement multiple LED modes in a sketch with potentiometers?

Answers: 2

body: It would be relatively simple to do a threshold test on analogRead() to switch modes *(e.g. if the value is above 512 (analogRead() gives values between 0-1023)* then you switch modes (probably with a boolean variable that you can then use to decide whether to strobe the LEDs).

body:
Since you already know how to hook up a pot and read it's value, it's quite simple. You already have it hooked up in a voltage divider configuration and are getting a 10 bit (0-1023) value using [`analogRead()`][1], you just need to decide what to do with it.

Assume `potVal` has the value of the pot.;

    if (potVal < 256) {
        // Pot is one quarter turn or less
    } else if (potVal < 512) {
        // Pot is between 256 and 512, so its more than quarter but less than half
    } else if (potVal < 768) {
        // Pot is between half and 3/4ths of the way there
    } else {
        // Pot is greater than 3/4 of it's full range
    }

So I have broken it down into four quadrants for you, but you can do it however you like.

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


body:
I remember seeing [Primo](http://techcrunch.com/2013/11/24/primo/), this robot that is based on Arduino and serves to teach kids to program. My interest in the platform comes from there, but it is always nice to learn about other cool applications.

What other applications are there that utilise Arduino for K-12 education?

title: How has Arduino been used in the classroom?

Answers: 2

body:
I've used [Sparki][1] from Arcbotics as a robotics platform. It's uses Arduino Sketch to program and a modified Arduino IDE.

Sensors for line following , edge detection, distance and light level sensing are built in. Also the creators are focused on education so the material and projects are teaching oriented.

The Community seems pretty active and engaged too so the material should build over time.

  [1]: http://arcbotics.com/products/sparki/start

body:
We have been using Arduino's to teach basic microcontroller concepts in classes focused on environmental monitoring & instrumentation, rather than just electronics:

[An Arduino UNO based Datalogger for the Classroom](http://edwardmallon.wordpress.com/2015/12/22/arduino-uno-based-data-logger-with-no-soldering/)

The IDE abstracts away enough of the low level details that you can get students into programming quickly, while still exposing them to enough of hardware side of things. I am not sure what other platform would let us take true beginners so far, so quickly.


body:
I've been trying to get colours fade into each other for a project I'm working on.
I have achieved this with the rainbow effect that some from Adafruit's example code, however I want to be able to choose the colours (eg. dark blue into light blue).

I've got the colours changing and fading, however the fade turns off all the LEDs and starts to increase the brightness of the new colour. I need the colours to blend rather than fade out and increase in brightness.

Is anyone able to point me in the right direction?

    #include "LPD8806.h"
    #include "SPI.h"
    #define stripSize 64

    int nLEDs = 160;

    int dataPin  = 2;
    int clockPin = 3;

    // First parameter is the number of LEDs in the strand.  The LED strips
    // are 32 LEDs per meter but you can extend or cut the strip.  Next two
    // parameters are SPI data and clock pins:
    LPD8806 strip = LPD8806(64, dataPin, clockPin);

    // You can optionally use hardware SPI for faster writes, just leave out
    // the data and clock pin parameters.  But this does limit use to very
    // specific pins on the Arduino.  For "classic" Arduinos (Uno, Duemilanove,
    // etc.), data = pin 11, clock = pin 13.  For Arduino Mega, data = pin 51,
    // clock = pin 52.  For 32u4 Breakout Board+ and Teensy, data = pin B2,
    // clock = pin B1.  For Leonardo, this can ONLY be done on the ICSP pins.
    //LPD8806 strip = LPD8806(nLEDs);

    void setup() {
      // Start up the LED strip
      strip.begin();

      // Update the strip, to start they are all 'off'
      strip.show();
    }

    void loop() {
      //turnAllOn(strip.Color(30,30,30),4000);
      fade(0, 127, 0, 100); //red, green, blue, delay - fade up all pixels one color
      //turnAllOn(strip.Color(30,100,30),4000);
      fade(50, 127, 02,100); //red, green, blue, delay - fade up all pixels one color
      //turnAllOn(strip.Color(100,30,100),4000);
      fade(50, 127, 50, 100); //red, green, blue, delay - fade up all pixels one color
    }

    void fade(uint32_t r, uint32_t g, uint32_t b, uint32_t wait) {
      int i, j;
      for (j=0; j < 384; j++) {
        for (i=0; i < strip.numPixels(); i++) {
          strip.setPixelColor(i, strip.Color((r*j)/1000,(g*j)/1000,(b*j)/1000));
        }
      strip.show();
      }
      delay(wait);
    }

    void turnAllOn(uint32_t c, uint32_t wait) {
      int i;
      for (i=0; i < strip.numPixels(); i++) {
        strip.setPixelColor(i, c);  // turn all pixels on
      }
      strip.show();   // write all the pixels out
      delay(wait);
    }

    uint32_t Wheel(uint16_t WheelPos)
    {
      byte r, g, b;
      switch(WheelPos / 128)
      {
        case 0:
          r = 127 - WheelPos % 128;   //Red down
          g = WheelPos % 128;      // Green up
          b = 0;                  //blue off
          break;
        case 1:
          g = 127 - WheelPos % 128;  //green down
          b = WheelPos % 128;      //blue up
          r = 0;                  //red off
          break;
        case 2:
          b = 127 - WheelPos % 128;  //blue down
          r = WheelPos % 128;      //red up
          g = 0;                  //green off
          break;
      }
      return(strip.Color(r,g,b));
    }

title: Digital RGB LED animation

Answers: 1

body:
Currently, your fade function is starting at 0 and effectively interpolating up to the desired colour. To fade between colours, you would need the sketch to remember the previous colour it used, and start fading from that instead of from 0.

The approach I'd use is to start by calculating how much each component needs to change by on each step. For example, if you want to fade from 100 to 200 across 50 steps, then it needs to change by +2 on every step. If you wanted to do the same in reverse (200 to 100) then it would have to change by -2.

One of the problems is that each component will probably be changing by a different amount (red might go from 0 to 200, but blue might only go from 50 to 70). If you're using integers all the time then it could result in some uneven transitions, so I'd recommend using floating point instead. It's technically slower (less efficient), but probably not enough to worry about.

This is how I'd probably write it:

    void fade(uint8_t oldR, uint8_t oldG, uint8_t oldB, uint8_t newR, uint8_t newG, uint8_t newB, uint32_t numSteps, uint32_t waitPerStep)
    {
        // Guard against division by zero
        if (numSteps == 0) numSteps = 1;

        // Calculate how how much each colour needs to change on each step
        const float
            stepR = (newR - oldR) / (float)numSteps,
            stepG = (newG - oldG) / (float)numSteps,
            stepB = (newB - oldB) / (float)numSteps;

        // These values will store our colours on the way along
        float r = oldR, g = oldG, b = oldB;
        uint8_t byteR = oldR, byteG = oldG, byteB = oldB;

        // Go through each fade step
        const uint16_t numPixels = strip.numPixels();
        for (uint32_t step = 0; step < numSteps; ++step) {
            // Move one step towards the target colour
            r += stepR;
            g += stepG;
            b += stepB;

            // Round the colours to integers here so we don't have to do it repeatedly in the loop below
            byteR = (uint8_t)(r + 0.5f);
            byteG = (uint8_t)(g + 0.5f);
            byteB = (uint8_t)(b + 0.5f);

            // Apply the colour to each pixel
            for (uint16_t pixel = 0; pixel < numPixels; ++pixel) {
                strip.setPixelColor(pixel, byteR, byteG, byteB);
            }

            strip.show();
            delay(waitPerStep);
        }
    }

As you can see, you pass it the old colour (which you're fading *from*) and the new colour (which you're fading *to*). As I mentioned above, this means your sketch has to remember which colour it previously used, as I don't think the library provides a way to read the current colour back.

I've included some optimisations in there to make it run faster. There's more you could do to optimise it even further, if necessary.

To use this, you'd do something like this:

    // Fade from black to red and pause briefly
    fade(0, 0, 0,  255, 0, 0,  100, 10);
    delay(500);

    // Fade from red to purple and pause briefly
    fade(255, 0, 0,   255, 0, 255,  100, 10);
    delay(500);

    // Fade from purple to green and pause briefly
    fade(255, 0, 255,  0, 255, 0,  100, 10);
    delay(500);

I've made a couple of other changes compared to your own fade function function. First of all, I've made it so that you can set the number of steps to fade over. This can be quite useful because bigger colour changes will need more steps to look smooth.

I've also modified the `wait` parameter. In your code, you put the delay after the entire fade was complete, which seems like an odd approach. It makes more sense to allow a small delay between each step of the fade, so you can control how fast it goes.

In my example above, you can see the `100, 10` parameters at the end of each call to `fade()`. That means it will divide the colour change into 100 steps, with a delay of 10ms between each step. The result is that each fade will take roughly 1 second (not counting the time taken to actually update the LED strip).


body:
Uploading simple sketches seems to work when I run the Arduino program as root (`sudo`). I would like to run it as a regular user. Has anyone faced the same problem before and fixed it?

Here is what I obtained from `lsusb`:

    $ lsusb
    Bus 002 Device 022: ID 2341:0043 Arduino SA Uno R3 (CDC ACM)

And the Arduino program identifies it as `/dev/ttyACM0`. Here are its permissions:

    $ ls -l /dev/ttyACM0
    crw-rw---T 1 root dialout 166, 0 Mar 14 22:03 /dev/ttyACM0

Here is the output from `id`

    groups=1000(abhiram),20(dialout),24(cdrom),25(floppy),29(audio),
    30(dip),44(video),46(plugdev),105(scanner),110(bluetooth),112(netdev)

When I upload an sketch from the examples, as a regular user, I encounter this error:

    avrdude:stk500_recv(): programmer not responding

Any suggestions are welcome.

title: Arduino program only works when run as root

Answers: 3

body:
The easiest solution is to add yourself to the `dialout` group.

First make a note of the output from `id`. Save it in file (not in `/tmp` as that gets cleaned out on a reboot). If you look at the output, you'll notice that your user is signed up for several groups and those groups represent extra privileges on the system. By default your Arduino is assigned to the group `dialout` because it registers as a serial interface and in the old days these were often used to ... dial out, using a modem.

To add yourself to the `dialout` group, issue the following command:

    sudo usermod -a -G dialout $USER

Don't forget the `-a` flag (for appending groups rather than replacing) or you will have entirely different problems. This is the reason for making a copy of the `id` output to a file, so in case you do mess up at least you know what your user was configured like before.

Then log out and log in and it should work from that point.

Optionally you can double check the output for `id` against the output you saved before.

body:
The oft-repeated advice to "just do `sudo usermod -aG dialout <username>` never worked for me, and I finally figured out why. On my machine, `/dev/ttyUSB0` is of the group `serial` and not `dialout`, so adding my username to `dialout` did nothing.

    # ls -l
    # crw-rw---- 1 root serial 188, 0 Mar 31 20:52 /dev/ttyUSB0
                        ^^^^^^ (group-name)

Finally: `sudo usermod -aG <group-name> <username>` fixed it for me.

Embarrassingly, this is also explicitly mentioned [here](http://playground.arduino.cc/Linux/All#.UzoSq1VX-uZ) under "SET THE PERMISSION". Sigh.

body:
This happens to me.
In my case, I had upgraded the version of arduino and seems the preferences file was causing the problem.
Just delete ~/.arduino/preferences.txt file (with Arduino IDE closed).

Steps:

1. Close Arduino IDE
2. execute this:

    rm ~/.arduino/preferences.txt

3. Launch Arduino IDE

This worked for me, hope it works for someone else.
I am using Linux Mint 17 and I upgraded from Arduino 1.05 to Arduino 1.06 by extracting the Arduino IDE, I am not using the one in the repo.
(Of course, after adding your user to the corresponding group as mentioned by others, but if that wont help you try this)


body:
I downloaded Arduino code from this: https://github.com/BabyWrassler/MissionControl/ Github, and got the  error message below.

It is designed to work with a Raspberry Pi, and I installed the two Adafruit libraries.  I also have not hooked it up to either the Pi, or the two Adafruit devices, but that is partly because I cannot get it to run without the error message.

Update:
Here is what was highlighted:
`Adafruit_LEDBackpack matrixA = Adafruit_LEDBackpack();`
The orange bar says:
    Variable or field ‘matrixOff‘ declared void
I cannot tell what of the following was from before, but here is the entire console log:

        mcDesk.ino:2:53: error: Adafruit_LEDBackpack.h: No such file or directory
        mcDesk.ino:3:45: error: Adafruit_GFX.h: No such file or directory
        mcDesk:11: error: variable or field 'matrixOff' declared void
        mcDesk:11: error: 'Adafruit_LEDBackpack' was not declared in this scope
        mcDesk:11: error: expected primary-expression before 'buffer'
        mcDesk:12: error: variable or field 'ledOn' declared void
        mcDesk:12: error: 'Adafruit_LEDBackpack' was not declared in this scope
        mcDesk:12: error: expected primary-expression before 'buffer'
        mcDesk:12: error: expected primary-expression before 'cat'
        mcDesk:12: error: expected primary-expression before 'an'
        mcDesk:13: error: variable or field 'ledOff' declared void
        mcDesk:13: error: 'Adafruit_LEDBackpack' was not declared in this scope
        mcDesk:13: error: expected primary-expression before 'buffer'
        mcDesk:13: error: expected primary-expression before 'cat'
        mcDesk:13: error: expected primary-expression before 'an'
        mcDesk:14: error: variable or field 'dispMat' declared void
        mcDesk:14: error: 'Adafruit_LEDBackpack' was not declared in this scope
        mcDesk:14: error: expected primary-expression before 'buffer'
        mcDesk:17: error: variable or field 'threeDigitDisp' declared void
        mcDesk:17: error: 'Adafruit_LEDBackpack' was not declared in this scope
        mcDesk:17: error: expected primary-expression before 'buffer'
        mcDesk:17: error: expected primary-expression before 'cats'
        mcDesk:17: error: expected primary-expression before 'ans'
        mcDesk:17: error: expected primary-expression before 'number'
        mcDesk:18: error: variable or field 'digitDisp' declared void
        mcDesk:18: error: 'Adafruit_LEDBackpack' was not declared in this scope
        mcDesk:18: error: expected primary-expression before 'buffer'
        mcDesk:18: error: expected primary-expression before 'pos'
        mcDesk:18: error: expected primary-expression before 'cat'
        mcDesk:18: error: expected primary-expression before 'an'
        mcDesk:18: error: expected primary-expression before 'num'
        mcDesk:23: error: variable or field 'switchBars' declared void
        mcDesk:23: error: 'Adafruit_LEDBackpack' was not declared in this scope
        mcDesk:23: error: expected primary-expression before 'buffer'
        mcDesk:23: error: expected primary-expression before 'grphCats'
        mcDesk:23: error: expected primary-expression before 'grphAns'
        mcDesk:23: error: expected primary-expression before 'cmnd'
        mcDesk:23: error: expected primary-expression before 'offset'
        mcDesk:24: error: variable or field 'barDisp' declared void
        mcDesk:24: error: 'Adafruit_LEDBackpack' was not declared in this scope
        mcDesk:24: error: expected primary-expression before 'buffer'
        mcDesk:24: error: expected primary-expression before 'grphCats'
        mcDesk:24: error: expected primary-expression before 'grphAns'
        mcDesk:24: error: expected primary-expression before 'pos'
        mcDesk:24: error: expected primary-expression before 'offset'
        mcDesk:25: error: variable or field 'cBarDisp' declared void
        mcDesk:25: error: 'Adafruit_LEDBackpack' was not declared in this scope
        mcDesk:25: error: expected primary-expression before 'buffer'
        mcDesk:25: error: expected primary-expression before 'grphCats'
        mcDesk:25: error: expected primary-expression before 'grphAns'
        mcDesk:25: error: expected primary-expression before 'pos'
        mcDesk:25: error: expected primary-expression before 'offset'
        mcDesk:11: error: 'Adafruit_LEDBackpack' does not name a type
        mcDesk:12: error: 'Adafruit_LEDBackpack' does not name a type
        mcDesk:13: error: 'Adafruit_LEDBackpack' does not name a type
        mcDesk:14: error: 'Adafruit_LEDBackpack' does not name a type
        mcDesk:15: error: 'Adafruit_LEDBackpack' does not name a type
        mcDesk.ino: In function 'void decodeCommand()':
        mcDesk:193: error: 'matrixE' was not declared in this scope
        mcDesk:193: error: 'ledOn' was not declared in this scope
        mcDesk:199: error: 'matrixE' was not declared in this scope
        mcDesk:199: error: 'ledOff' was not declared in this scope
        mcDesk:204: error: 'matrixC' was not declared in this scope
        mcDesk:204: error: 'cBarDisp' was not declared in this scope
        mcDesk.ino: In function 'void allMatrixOff()':
        mcDesk:213: error: 'matrixA' was not declared in this scope
        mcDesk:213: error: 'matrixOff' was not declared in this scope
        mcDesk:214: error: 'matrixB' was not declared in this scope
        mcDesk:215: error: 'matrixC' was not declared in this scope
        mcDesk:216: error: 'matrixD' was not declared in this scope
        mcDesk:217: error: 'matrixE' was not declared in this scope
        mcDesk.ino: At global scope:
        mcDesk:220: error: variable or field 'matrixOff' declared void
        mcDesk:220: error: 'Adafruit_LEDBackpack' was not declared in this scope
        mcDesk:220: error: expected primary-expression before 'buffer'

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

title: Arduino error message that I don't understand

Answers: 1

body:
It seems to me that those Adafruit libraries were not correctly installed on your PC or your sketch.

In addition to downloading and installing the library onto the Arduino library directory (on Windows, that's normally `C:\Users\UserName\Documents\Arduino\libraries`), when you want to use that library with Arduino IDE, you must add the library for your sketch with the menu command "**Sketch -> Import Library...**"

**Important note**: it seems just adding `#include "library.h"` does not work with Arduino IDE, you absolutely need to use the menu.


body:
I have Arduino Leonardo board operating lots of AC relays in quite noisy environment. USB works unstable, which sometimes causes the board to hang, so I decided to use secondary serial connection as "debug console":

      Serial1.begin(115200);
      .....
      .....
      if (Serial1.available()) {
        char ch = Serial1.read();
        if ( isalnum(ch) ) {
          switch (ch) {
            case 'M': {
              turnOn_pin_Motor();
              break;
            }
            case 'm': {
              turnOff_pin_Motor();
              break;
            }
            .......

My problem is that noise affects Serial1 the same way it messes USB (but at least it doesn't cause it to freeze). I'd like to use some sort of error checking to prevent Leonardo from acting on "phantom" commands. I could, for example, prefix each keyboard command my Arduino should receive with special symbol, maybe "!".

So I must be reading one char, checking if it is "!" and reading second character.

Unfortunately, I can't modify my code so it would use 2-character buffer and shift its contents as characters arrive, without locking the main loop while waiting for the next char. Any hints on what should I do in this case?

title: Reading multiple bytes from *software* serial

Answers: 1

body:
Serial1 on the Arduino Leonardo is hardware serial, not software.

There are several ways to read in multiple bytes from Serial.

Instead of detecting `Serial.available()` (i.e. non-zero), change it to `Serial.available() >= 2`

    if (Serial.available() >= 2) {
      for (int i=0; i<2; i++) {
        buffer[i] = Serial.read();
      }
    }

Or you can leave it as it is, and read into the buffer one at a time.

    static int bufferIndex;

    if (Serial.available())
    {
     buffer[bufferIndex++] = Serial.read()
    }

You'll need to detect the contents of the buffer in another `if` statement, and also deal with the bounds of the index.

Honestly though, noise is your issue here - this is an example of an [XY problem][1]. There's nothing inherent in using a microcontroller with relays that should mean that serial won't work.

  [1]: https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem


body:
I made a working model of Bluetooth light control with arduino and Bluetooth. Everything worked fine and then after some time I connected the circuit again it didn't work and the pins 7,10,11,12 aren't working . I was using a Bluetooth shield but I tried the simple LED flash program and even that's not working .

Please suggest any good way of making it working again or at least explain what happened with it.

title: Is my Arduino destroyed or are the pins destroyed?

Answers: 1

body:
Try running the blink LED, on a different terminals.
If the LED is working properly, then most likely the pins are destroyed.
Why are they destroyed?
Most likely, you've withdrawn more current than the pins can actually provide.

According to the datasheet of the Arduino uno, the IO pins can handle up to 40mA.

![enter image description here][1]

The only possible way to solve this problem is to change the IC (Atmega328) by another one. It's not guranteed that it will work, but the microcontroller is reletively cheap.

The definite answer can not be determined unless you showed us a schematic of your connection.

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


body:
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

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

Answers: 3

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

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.


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

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

Answers: 1

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


body:
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/

title: What alternatives are there to the Optiboot bootloader?

Answers: 3

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


body:
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?

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

Answers: 2

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.


body:
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

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

Answers: 2

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


body:
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.**

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

Answers: 5

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/


body:
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?

title: Arduino Not Responding During Program

Answers: 3

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/


body:
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(){

    }

title: Unrecognizable Message From PROGMEM char*

Answers: 1

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.


body:
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

title: PROGMEM char* mangled text

Answers: 2

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.


body:
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?

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

Answers: 1

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.


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

title: Arduino USB Power vs External Power Supply

Answers: 2

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


body:
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

title: Arduino Mega not flashable with XBee PRO S2B

Answers: 1

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


body:
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

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

Answers: 1

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


body:
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

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

Answers: 5

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.