# Question
Title: Using ArduinoISP on an Arduino Uno to program an ATmega328
I have an Arduino Uno R3 and would like to use it to program a blank ATmega328 on a breadboard. I've followed the instructions for the 8 MHz version on http://arduino.cc/en/Tutorial/ArduinoToBreadboard with an added 10K pullup resistor on the `RESET` pin of the ATmega328 on the breadboard; and I've uploaded the `ArduinoISP` sketch from the Arduino 1.0.5 distribution to my Uno.

I've also added the metadata for my setup: the following is the contents of `~/sketchbook/hardware/breadboard/boards.txt`:

```
atmega328bb.name=ATmega328 on a breadboard (8 MHz internal clock)

atmega328bb.upload.protocol=stk500v1
atmega328bb.upload.maximum_size=30720
atmega328bb.upload.speed=57600

atmega328bb.bootloader.low_fuses=0xE2
atmega328bb.bootloader.high_fuses=0xDA
atmega328bb.bootloader.extended_fuses=0x05
atmega328bb.bootloader.path=arduino:atmega
atmega328bb.bootloader.file=ATmegaBOOT_168_atmega328_pro_8MHz.hex
atmega328bb.bootloader.unlock_bits=0x3F
atmega328bb.bootloader.lock_bits=0x0F

atmega328bb.build.mcu=atmega328
atmega328bb.build.f_cpu=8000000L
atmega328bb.build.core=arduino:arduino
atmega328bb.build.variant=arduino:standard

```

I've also added the following section to my `~/.avrduderc` file:

```
part
    id          = "m328";
    desc        = "ATMEGA328";
    has_debugwire   = yes;
    flash_instr     = 0xB6, 0x01, 0x11;
    eeprom_instr    = 0xBD, 0xF2, 0xBD, 0xE1, 0xBB, 0xCF, 0xB4, 0x00,
              0xBE, 0x01, 0xB6, 0x01, 0xBC, 0x00, 0xBB, 0xBF,
              0x99, 0xF9, 0xBB, 0xAF;
    stk500_devcode  = 0x86;
    # avr910_devcode    = 0x;
    signature       = 0x1e 0x95 0x14;
    pagel       = 0xd7;
    bs2         = 0xc2;
    chip_erase_delay    = 9000;
    pgm_enable = "1 0 1 0 1 1 0 0 0 1 0 1 0 0 1 1",
         "x x x x x x x x x x x x x x x x";

    chip_erase = "1 0 1 0 1 1 0 0 1 0 0 x x x x x",
         "x x x x x x x x x x x x x x x x";

    timeout = 200;
    stabdelay   = 100;
    cmdexedelay = 25;
    synchloops  = 32;
    bytedelay   = 0;
    pollindex   = 3;
    pollvalue   = 0x53;
    predelay    = 1;
    postdelay   = 1;
    pollmethod  = 1;

    pp_controlstack =
    0x0E, 0x1E, 0x0F, 0x1F, 0x2E, 0x3E, 0x2F, 0x3F,
    0x4E, 0x5E, 0x4F, 0x5F, 0x6E, 0x7E, 0x6F, 0x7F,
    0x66, 0x76, 0x67, 0x77, 0x6A, 0x7A, 0x6B, 0x7B,
    0xBE, 0xFD, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00;
    hventerstabdelay    = 100;
    progmodedelay   = 0;
    latchcycles     = 5;
    togglevtg       = 1;
    poweroffdelay   = 15;
    resetdelayms    = 1;
    resetdelayus    = 0;
    hvleavestabdelay    = 15;
    resetdelay      = 15;
    chiperasepulsewidth = 0;
    chiperasepolltimeout = 10;
    programfusepulsewidth = 0;
    programfusepolltimeout = 5;
    programlockpulsewidth = 0;
    programlockpolltimeout = 5;

    memory "eeprom"
    paged       = no;
    page_size   = 4;
    size        = 1024;
    min_write_delay = 3600;
    max_write_delay = 3600;
    readback_p1 = 0xff;
    readback_p2 = 0xff;
    read = " 1 0 1 0 0 0 0 0",
           " 0 0 0 x x x a9 a8",
           " a7 a6 a5 a4 a3 a2 a1 a0",
           " o o o o o o o o";

    write = " 1 1 0 0 0 0 0 0",
            " 0 0 0 x x x a9 a8",
        " a7 a6 a5 a4 a3 a2 a1 a0",
        " i i i i i i i i";

    loadpage_lo = " 1 1 0 0 0 0 0 1",
              " 0 0 0 0 0 0 0 0",
              " 0 0 0 0 0 0 a1 a0",
              " i i i i i i i i";

    writepage = " 1 1 0 0 0 0 1 0",
            " 0 0 x x x x a9 a8",
            " a7 a6 a5 a4 a3 a2 0 0",
            " x x x x x x x x";

    mode        = 0x41;
    delay       = 20;
    blocksize   = 4;
    readsize    = 256;
    ;

    memory "flash"
    paged       = yes;
    size        = 32768;
    page_size   = 128;
    num_pages   = 256;
    min_write_delay = 4500;
    max_write_delay = 4500;
    readback_p1 = 0xff;
    readback_p2 = 0xff;
    read_lo = " 0 0 1 0 0 0 0 0",
          " 0 0 a13 a12 a11 a10 a9 a8",
          " a7 a6 a5 a4 a3 a2 a1 a0",
          " o o o o o o o o";

    read_hi = " 0 0 1 0 1 0 0 0",
          " 0 0 a13 a12 a11 a10 a9 a8",
          " a7 a6 a5 a4 a3 a2 a1 a0",
          " o o o o o o o o";

    loadpage_lo = " 0 1 0 0 0 0 0 0",
              " 0 0 0 x x x x x",
              " x x a5 a4 a3 a2 a1 a0",
              " i i i i i i i i";

    loadpage_hi = " 0 1 0 0 1 0 0 0",
              " 0 0 0 x x x x x",
              " x x a5 a4 a3 a2 a1 a0",
              " i i i i i i i i";

    writepage = " 0 1 0 0 1 1 0 0",
            " 0 0 a13 a12 a11 a10 a9 a8",
            " a7 a6 x x x x x x",
            " x x x x x x x x";

    mode        = 0x41;
    delay       = 6;
    blocksize   = 128;
    readsize    = 256;

    ;

    memory "lfuse"
    size = 1;
    min_write_delay = 4500;
    max_write_delay = 4500;
    read = "0 1 0 1 0 0 0 0 0 0 0 0 0 0 0 0",
           "x x x x x x x x o o o o o o o o";

    write = "1 0 1 0 1 1 0 0 1 0 1 0 0 0 0 0",
            "x x x x x x x x i i i i i i i i";
    ;

    memory "hfuse"
    size = 1;
    min_write_delay = 4500;
    max_write_delay = 4500;
    read = "0 1 0 1 1 0 0 0 0 0 0 0 1 0 0 0",
           "x x x x x x x x o o o o o o o o";

    write = "1 0 1 0 1 1 0 0 1 0 1 0 1 0 0 0",
            "x x x x x x x x i i i i i i i i";
    ;

    memory "efuse"
    size = 1;
    min_write_delay = 4500;
    max_write_delay = 4500;
    read = "0 1 0 1 0 0 0 0 0 0 0 0 1 0 0 0",
           "x x x x x x x x x x x x x o o o";

    write = "1 0 1 0 1 1 0 0 1 0 1 0 0 1 0 0",
            "x x x x x x x x x x x x x i i i";
    ;

    memory "lock"
    size = 1;
    min_write_delay = 4500;
    max_write_delay = 4500;
    read = "0 1 0 1 1 0 0 0 0 0 0 0 0 0 0 0",
           "x x x x x x x x x x o o o o o o";

    write = "1 0 1 0 1 1 0 0 1 1 1 x x x x x",
            "x x x x x x x x 1 1 i i i i i i";
    ;

    memory "calibration"
    size = 1;
    read = "0 0 1 1 1 0 0 0 0 0 0 x x x x x",
           "0 0 0 0 0 0 0 0 o o o o o o o o";
    ;

    memory "signature"
    size = 3;
    read = "0 0 1 1 0 0 0 0 0 0 0 x x x x x",
           "x x x x x x a1 a0 o o o o o o o o";
    ;
;

```

So I thought I'd be good to go: I've set the programmer type to `ArduinoISP` and the board type to `ATmega328 on a breadboard (8 MHz internal clock)` in the IDE.

However, when I try to either upload the Arduino bootloader, or use the `Upload using programmer` feature on the `Blink` example, I get this:

```
avrdude: Device signature = 0x000000
avrdude: Yikes!  Invalid device signature.
         Double check connections and try again, or use -F to override
         this check.

```

Full output:

```
/usr/share/arduino/hardware/tools/avrdude -C/usr/share/arduino/hardware/tools/avrdude.conf -v -v -v -v -patmega328 -cstk500v1 -P/dev/ttyACM0 -b19200 -Uflash:w:/tmp/build6008715511691559175.tmp/Blink.cpp.hex:i

avrdude: Version 5.11.1, compiled on Apr 28 2013 at 18:46:46
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2009 Joerg Wunsch

         System wide configuration file is "/usr/share/arduino/hardware/tools/avrdude.conf"
         User configuration file is "/home/cactus/.avrduderc"

         Using Port                    : /dev/ttyACM0
         Using Programmer              : stk500v1
         Overriding Baud Rate          : 19200
avrdude: Send: 0 [30]   [20]
avrdude: Send: 0 [30]   [20]
avrdude: Send: 0 [30]   [20]
avrdude: Recv: . [14]
avrdude: Recv: . [10]
         AVR Part                      : ATMEGA328
         Chip Erase delay              : 9000 us
         PAGEL                         : PD7
         BS2                           : PC2
         RESET disposition             : dedicated
         RETRY pulse                   : SCK
         serial program mode           : yes
         parallel program mode         : yes
         Timeout                       : 200
         StabDelay                     : 100
         CmdexeDelay                   : 25
         SyncLoops                     : 32
         ByteDelay                     : 0
         PollIndex                     : 3
         PollValue                     : 0x53
         Memory Detail                 :

                                  Block Poll               Page                       Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           eeprom        65    20     4    0 no       1024    4      0  3600  3600 0xff 0xff
                                  Block Poll               Page                       Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           flash         65     6   128    0 yes     32768  128    256  4500  4500 0xff 0xff
                                  Block Poll               Page                       Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           lfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
                                  Block Poll               Page                       Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           hfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
                                  Block Poll               Page                       Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           efuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
                                  Block Poll               Page                       Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           lock           0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
                                  Block Poll               Page                       Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
                                  Block Poll               Page                       Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

         Programmer Type : STK500
         Description     : Atmel STK500 Version 1.x firmware
avrdude: Send: A [41] . [80]   [20]
avrdude: Recv: . [14]
avrdude: Recv: . [02]
avrdude: Recv: . [10]
avrdude: Send: A [41] . [81]   [20]
avrdude: Recv: . [14]
avrdude: Recv: . [01]
avrdude: Recv: . [10]
avrdude: Send: A [41] . [82]   [20]
avrdude: Recv: . [14]
avrdude: Recv: . [12]
avrdude: Recv: . [10]
avrdude: Send: A [41] . [98]   [20]
avrdude: Recv: . [14]
avrdude: Recv: . [00]
avrdude: Recv: . [10]
         Hardware Version: 2
         Firmware Version: 1.18
         Topcard         : Unknown
avrdude: Send: A [41] . [84]   [20]
avrdude: Recv: . [14]
avrdude: Recv: . [00]
avrdude: Recv: . [10]
avrdude: Send: A [41] . [85]   [20]
avrdude: Recv: . [14]
avrdude: Recv: . [00]
avrdude: Recv: . [10]
avrdude: Send: A [41] . [86]   [20]
avrdude: Recv: . [14]
avrdude: Recv: . [00]
avrdude: Recv: . [10]
avrdude: Send: A [41] . [87]   [20]
avrdude: Recv: . [14]
avrdude: Recv: . [00]
avrdude: Recv: . [10]
avrdude: Send: A [41] . [89]   [20]
avrdude: Recv: . [14]
avrdude: Recv: . [00]
avrdude: Recv: . [10]
         Vtarget         : 0.0 V
         Varef           : 0.0 V
         Oscillator      : Off
         SCK period      : 0.1 us

avrdude: Send: A [41] . [81]   [20]
avrdude: Recv: . [14]
avrdude: Recv: . [01]
avrdude: Recv: . [10]
avrdude: Send: A [41] . [82]   [20]
avrdude: Recv: . [14]
avrdude: Recv: . [12]
avrdude: Recv: . [10]
avrdude: Send: B [42] . [86] . [00] . [00] . [01] . [01] . [01] . [01] . [03] . [ff] . [ff] . [ff] . [ff] . [00] . [80] . [04] . [00] . [00] . [00] . [80] . [00]   [20]
avrdude: Recv: . [14]
avrdude: Recv: . [10]
avrdude: Send: E [45] . [05] . [04] . [d7] . [c2] . [00]   [20]
avrdude: Recv: . [14]
avrdude: Recv: . [10]
avrdude: Send: P [50]   [20]
avrdude: Recv: . [14]
avrdude: Recv: . [10]
avrdude: AVR device initialized and ready to accept instructions

Reading | avrdude: Send: V [56] 0 [30] . [00] . [00] . [00]   [20]
avrdude: Recv: . [14]
avrdude: Recv: . [00]
avrdude: Recv: . [10]
avrdude: Send: V [56] 0 [30] . [00] . [01] . [00]   [20]
avrdude: Recv: . [14]
avrdude: Recv: . [00]
avrdude: Recv: . [10]
################avrdude: Send: V [56] 0 [30] . [00] . [02] . [00]   [20]
avrdude: Recv: . [14]
avrdude: Recv: . [00]
avrdude: Recv: . [10]
################################## | 100% 0.06s

avrdude: Device signature = 0x000000
avrdude: Yikes!  Invalid device signature.
         Double check connections and try again, or use -F to override
         this check.

avrdude: Send: Q [51]   [20]
avrdude: Recv: . [14]
avrdude: Recv: . [10]

avrdude done.  Thank you.

```

I've double-checked and triple-checked, I've rebuilt the whole circuit on another breadboard with another ATmega328, I've even checked the jumper cables one by one, they all work.

How do I use my Arduino Uno as an ISP to upload code to this blank ATmega328?

# Answer
> 3 votes
Feeling really stupid about it in retrospect...

One last thing I tried was taking the ATmega328P out from the Arduino Uno and plugging the blank ATmega328 in its place, thinking I could use the Uno programmer as such to burn the bootloader on the chip. That didn't work and I don't know if it's supposed to work.

However, to plug the new chip into the DIL on the Uno, I had to bend the DIP legs inwards slightly to give it a smaller straddle. After seeing that it didn't work, I plugged the ATmega328P back into the Uno and plugged the ATmega328 back into the breadboard. However, this time, because of the smaller straddle, it slipped in deeper into the breadboard, the plastic package actually touching the board. And with this setup, wiring it up again via the Arduino and using the `ArduinoISP` I was able to burn both the bootloader and (via the 'Upload with programmer' functionality) test programs to it.

TL;DR: I didn't have the blank ATmega328 properly plugged into the breadboard...

# Answer
> 2 votes
Do you have another UNO or similar? Try getting the boot loader upload working on a stock board just to confirm it is not the programmer. 0x000000 usually means it can't talk to the chip being programmed.

# Answer
> 0 votes
> ```
> avrdude: Device signature = 0x000000
> avrdude: Yikes!  Invalid device signature.
>          Double check connections and try again, or use -F to override
>          this check.
>
> ```

This is the clue to the solution. The signature is different between different versions of the ATmega328, for example:

* ATmega328-PU
* ATmega328P-PU

and so on...

You can google on "arduino signature error ATmega328P" to find the solution.

One hint is: http://forum.arduino.cc/index.php?topic=201920.0

I can be more specific if you post the version off the ATmega328 you have.

---
Tags: avr, isp
---


# Question
Title: Significance of the numbers used in the manual
i just bought the starter kit and am currently working my way through the examples in the book when i came across some numbers used in the manual that seems a little too specific.

For example, in project #3,the love-o-meter, i had to divide the sensor value by 1024.0, and the explanation for it was never given in the manual.

Furthermore, in project #4(which i'm currently at), the book states that i have to convert sensor readings from 0 - 1023, to a value between 0 to 255.Is the number 1024/1023 simply an arbitrary number/limit set by the sensor's manufacturers? Also, is they any significance or reason that analogueWrite only accepts positive values up to 255?

Thanks!

# Answer
> 4 votes
The range 0 - 1023 comes from the analog-to-digital converters (ADC) built-in to your Arduino. What they do is take a voltage reading (e.g. from your sensor) and compare it to the analog reference voltage (which is typically 5 volts, although it can be changed).

It converts that reading to a binary number. The ADCs on board a typical Arduino have 10 bits of precision. The maximum number you can represent with 10 binary bits is 1023. Therefore, a reading of 0V is converted to the number 0; a reading of 5V is converted to the number 1023; and so on (it handles all the in-between values too).

However, `analogWrite()` works quite differently. It's not actually producing a varying voltage on the output (i.e. it's not true digital-to-analog conversion). Instead, it's using Pulse Width Modulation (PWM) to do something similar.

That means it sends lots of 5V pulses on the output in quick succession. The 0 - 255 values you give it affect the duty cycle -- that is, how long each pulse is compared to the gaps between pulses. The longer the pulses are, the 'stronger' the signal is. This is very useful for applications such as controlling the brightness of an LED or the speed of a basic DC motor.

The PWM signal is controlled by timers built-in to the microcontroller. I suspect it's the capabilities of those timers which determine the input range for `analogWrite()`.

You can get more information from the online documentation for Arduino:

# Answer
> 2 votes
To clarify, analogRead() has a 10 bit range due to the arduino's Analog to Digital Converter, or ADC. 10 bits can store 1024 (2^10) different values; counting zero as a value gives the range 0-1023.

In arduino 0 is the reading when a pin is grounded, 1023 is the reading when an analog pin is connected to Vref, or 5v if there is nothing wired to Vref. The sensors provide a voltage somewhere between these values, but not the actual numbers your code gets.

analogWrite() accepts 8 bit numbers. That is 2^8 or 256 different values, called 0-255. It only simulates an analog voltage by pulsing a pin rapidly.

In short, the numbers are not arbitrary, but express the limits of the arduino chip's IO. They look random because they were written in decimal, but in binary they are very simple. If you are interested, you could look into replacing the decimal numbers in the code with hexadecimal numbers, which make their binary representations very obvious by way of 16 being 2^4.

# Answer
> 1 votes
More explanation: binary numbers are different than base 10 as you probably know. The meaning of those numbers is simple.

Start with 1 and double it. Keep doubling. You will soon hit 256 (computers start at 0 not 1, so you have to take that into account, 0-255 is 256 different values). Keep doubling and you will soon hit 1024 (0-1023).

So these numbers are not arbitrary, they are Base 10 (0-9 like you learned in school) representations of Binary Numbers, more specifically, the high limit a given length of binary digits can represent before having to add another digit.

1111111 is binary for 127, with 0 thats 128 different values those 7 digits can represent. To get to 255, you have to add a digit for 8 total digits, 11111111 = 255. 9 digits or 111111111 = 511 and ten digits or 1111111111 = 1023.

---
Tags: arduino-uno
---


title: Reading CMPS10 raw values

text:
# Question
Title: Reading CMPS10 raw values
I've got a cmps10 compass module hooked up to my arduino due through a logic level converter. I am writing code to convert the raw magnetometer readings into a bearing that I can use but have run into a huge problem. My bearings are all funky for some reason. They are totally unrelated to the actual bearing of the robot. I know the sensor is fine because I am able to get the tilt compensated reading from it and it works great. One thing I noticed is that the magnetometer reading on the X-axis is always positive could this be the problem? The X-axis high byte generally between 0x00 and 0x03. My code is below (i2cBus = &Wire)

```
i2cBus->beginTransmission(I2C_Address);
i2cBus->write(byte(10));
i2cBus->endTransmission();

i2cBus->requestFrom(I2C_Address, 4);
xMagHighByte = i2cBus->read();
xMagLowByte = i2cBus->read();
yMagHighByte = i2cBus->read();
yMagLowByte = i2cBus->read();

xMag = short(xMagHighByte<<8);
xMag |= xMagLowByte;
yMag = short(yMagHighByte<<8);
yMag |= yMagLowByte;

if(yMag!=0){
  magBearing = (atan2(xMag,yMag)*180.0)/3.141592654;
}
else if(xMag>0) magBearing=0.0;
else if(xMag<0) magBearing=180.0;
else magBearing = 1000;
if(magBearing < 0) magBearing+=360;
magBearing=360-magBearing;
return magBearing;

```

# Answer
> 1 votes
Compass modules are highly susceptible to interference from ferrous deposits underground and metals in or around your robot. To correct for them, you need to shift and scale both axis.

But first, test if the sensor's X axis is working by watching the value while moving a small magnet around the sensor. If should overpower any stationary field and bias in the sensor, if it can't then there may be a problem with the sensor.

To calibrate the compass, first find the min and max value for each axis. Do this by reading all the outputs of an axis when moving the sensor in a complete circle in the environment you will be using it in. Making the robot drive in a circle when first turned on to calibrate itself is not a bad idea. Anyway, the shift is the negative average and the scale is half the difference between maximums. what really matters is that this "distance" is the same on both axis, but normalizing both is easier. For example,

```
float Scale, Shift, Value;
Scale =  (max-min)/2;
Shift = -(max+min)/2;
Value = float(raw+Shift)/Scale;

```

Once both axis are corrected the atan2() function can work properly. If you were to plot the x and y points on a graph, they should trace a unit circle at the origin.

---
Tags: sensors, arduino-due, i2c
---


title: Include statement not working

text:
# Question
Title: Include statement not working
I am creating my own library for the Arduino and I have the following code:

```
#include <Arduino.h>
#include <Servo.h>

class ServoMotorController {
    public:
        ServoMotorController(int servoPin, int motorPin, int angle);
        void setAngle(int angle);
        void setSpeed(int speed);
    private:
        Servo servo;

        int servoPin;
        int servoAngle;
        int motorPin;
        int motorSpeed;
};

```

I am getting the error that `Servo` does not name a type; however if I do

```
#include <Servo.h>
#include <ServoMotorController.h>

```

in my actual Arduino code then I do not get the error. **Why is the include statement not working in my C++ lib?**

# Answer
> 2 votes
This is a symptom of the arduino IDE. libraries can't add other libraries to the include path, but the can use other libs if they have already been included. you can use an error directive so your compiler output is more informative at least

```
#ifndef Servo_h
    #error "ServoMotorController Lib requires Servo.h to be included first to function"
#else

```

Arduino 1.5.6 beta's new library format has a section for dependencies in the new library.properties file that should allow one library to add another to the include path, but I'm not entirely sure if the functionality is fully implemented yet (its beta after all).

---
Tags: c++, library
---


# Question
Title: Error while connecting Arduino to Macbook: “serial port already in use. try quitting any programs that may be using it”
I'm trying to connect to my Arduino board through a macbook pro with mac os x 10.9.3 installed. I'm following the instructions from the arduino guide and in the connection section:

> " Connect the Arduino board to your computer using the USB cable. The green power LED (labelled PWR) should go on. If you're using the Arduino Uno or Arduino Mega 2560, a dialog box will appear telling you that a new network interface has been detected. Click "Network Preferences...", and when it opens, simply click "Apply". The Uno or Mega 2560 will show up as "Not Configured", but it's working properly. Quit System Preferences.

I cannot see any ports that hold the USBModem port.

How to setup the connection in the right way?

I read some articles about making a lock folder and I followed them but they didn't work for me, I also tried following this article but the solution there didn't work as well.

# Answer
> 2 votes
Sorry about providing this as an answer, rather than comments; however, I do have *some* suggestions to troubleshoot the connection.

First, check the usb connections with `lsusb`

```
    lsusb |grep -i arduino

```

Similarly, you can try following the output of `dmesg`; though, I'm not sure about the version of `dmesg` your system's installation is running. Newer version of `dmesg` have a "follow" option available. On my Fedora system it's:

```
    dmesg -wH

```

Check the output as you plug in the arduino for messages related to the device, such as the resulting location of the `tty`. As a desperate measure, you can also look in the `/dev/` folder for the last modified device, and search your logs for those devices:

```
    ls -alrth /dev/

```

# Answer
> 0 votes
Under what circumstances does this happen? I see this message whenever I try to download to the Arduino but I've left my terminal program connected to that port. The fix in that situation is to disconnect it (after a \<face-palm\> to remind myself, yet again.... :-)

---
Tags: arduino-uno, serial, mac-os
---


# Question
Title: Arduino to Raspberry Pi wired communication
I am new to Raspberry Pi (just brought mine before writing this post), and I am looking to see what is the most ideal way for two way communication between an Arduino and a Raspberry Pi (USB, SPI or I2C).

The reason I am asking is because I need to build a small, semi-autonomous robot and plan on using both the Arduino and Pi to control it, using the pins of the Arduino for the motor control and sensors and the Pi for video processing and autonomous part. Both will be on the robot itself. I am pretty good with the Arduino but never used a Raspberry Pi before.

So my biggest question is what would be the best form of communication for the two boards taking into account speed and safety (there is a voltage difference between the Pi and the Arduino).

# Answer
Hands down, I can rule out the I2C. This post sums it all up:

> * SPI is faster.
> * I2C is more complex and not as easy to use if your microcontroller doesn't have an I2C controller.
> * I2C only requires 2 lines.

Since speed is your first priority, either do USB or SPI. I'd personally go with USB, just for the reason that it's simple. Nearly any programming language can inference with COM ports, but that's not the case with SPI. Also, for SPI, you would have to either use a level shifter, or do a voltage divider for the Arduino to RPi wires (for RPi to Arduino wires, Arduino can still sense 3.3V as HIGH.)

Also, serial can be pretty fast. Technically, the Arduino can go up to 2 Mbps (not very fast compared to a lot of things, but fast enough for what the Arduino can even handle). One thing to note, the writer of the post stated that this is the highest you can practically achieve with the poorly optimized libraries:

```
Serial.begin(500000);

```
> 1 votes

# Answer
Firsr of all, When you say "there is a voltage difference", I assume you are referring to the raspberry pi being a 3.3v device vs the arduino's 5v, and not to some kind of ground potential difference. If theres a ground potential difference(which there shouldn't be in a robot), neither i2c or spi or usb will work without extra circuitry.

My short answer would be USB all the way because its easy and built into the arduino and pi. The only issue is that if anything mechanically bumps the usb enough to lose connection, sometimes linux is a little unpredictable with regards to naming serial ports, and when it reconnects it might give the arduino a different serial port name. But this isnt an issue if your cable isnt a cheap worn out one with a flaky connection like the one that bothered me for a hour today.

USB does have about a millisecond of latency because devices are usually polled at 1khz iirc. Using the raspberry pi hardware serial might be a good idea if milliseconds count which I doubt they do.

But on the software side, raspi hardware serial and USB serial are the same. So there should be no problem switching between them if you need to.

I wouldnt bother with i2c or spi. Why fuss around when serial works so well?
> 0 votes

---
Tags: arduino-mega, i2c, spi
---


title: Interfacing Arduino through USB or I2C?

text:
# Question
Title: Interfacing Arduino through USB or I2C?
I am planning to connect multiple Arduinos to my Raspberry Pi. There are basically two ways I can achieve that:

1. Use an USB hub. Each Arduino will then be available through ordinary serial commands both for reading and writing. The USB hub I have is powered and can handle both communications and powering the Arduinos.
2. Use I2C, so that the Arduinos are I2C slaves of the Raspberry Pi.

Since USB is used for updating the Arduino, I don't have the best feeling about using this same connection for "management" tasks.

**Are there any known disadvantages to using the pre built USB socket on the Arduino in "production", any best practises or similar saying that I should not do this? Is this USB socket meant to be used for debugging and code deployment only?**

The plan is to let the computer send commands to the Arduinos using a serial protocol. The computer will automatically detect whenever an Arduino is connected and immediately send a "hello" command over serial. The Arduino is then supposed to send back its "name" and a list of capability keywords. A capability may be "motion-sensor". The computer will then know that it can ask the Arduino if it has detected motion. Other capabilities may be "temperature-sensor", "barometric-sensor", "lights".

It's for a generic open source home automation system/robotics system I am working on creating a framework for.

# Answer
> 2 votes
One complication you should be aware of is that in its default configuration, an Arduino Uno (and I assume that is what you’re talking about) will automatically reset whenever a serial connection is opened to it. This is easily bypassed with a capacitor between RESET and GND, but not taking it into account might make for hours of debugging fun.

The other complication is that just after a power up or RESET, an Arduino will delay for a second or two to listen for a programmer connection on the serial port, but that’s something you’ll have to take into account anyway.

# Answer
> 1 votes
I would go with USB rather than I2C for these reasons:

* The Arduino can be powered via USB so there is no need for extra power supplies.
* The system will work with PCs, making it easier to develop the code and the product more versatile.
* USB cables are commercially available with standardised sockets. I2C cables would have to be made to specification (e.g. this app note) and would require some kind of additional socket for robust termination.
* The Arduino Wire (I2C) library will hang if you disconnect the cable in the middle of waiting for a byte.

A good product will be robust and easy to use. One thing you may wish to consider is to create an internet of thing (IoT) type system. This involves the Arduinos sending sensor data to the web via the RPi. It could be that the RPi is a dumb conduit for the Arduinos, or it could collate the data and present itself as the end device. Check out Xively for details. I made a basic system to do the former, it is on github here.

# Answer
> 1 votes
In my opinion, think USB on the Arduino is stable enough for production use.\* There are ways to rename your Arduino if someone would connect it to a computer.

I think the real problem with this approach is people tampering with it. I know it's open source and all, but do you really want users (if it does get produced on a big scale, which is unlikely, but *possible*) without much tech knowledge plugging it into their computer?

If none of that sounds like a problem to you (and the delay/reset problems outlined by others isn't a big deal), I'd say go for USB. It's pretty easy to use, and it's universal, thus someone could connect the system to their computer if you developed the software for PC.

\*Assuming you're using a full Arduino in a production environment, you won't care about if it shows up to the computer as "Arduino Uno."

---
Tags: serial, i2c
---


# Question
Title: Why does increasing resistance make a capacitive sensor more sensitive?
From the Capacitive Sensor Page on the Arduino website, it states the following:

> The capacitiveSensor method toggles a microcontroller send pin to a new state and then waits for the receive pin to change to the same state as the send pin. A variable is incremented inside a while loop to time the receive pin's state change. The method then reports the variable's value, which is in arbitrary units.

AND

> Use a 1 megohm resistor (or less maybe) for absolute touch to activate. With a 10 megohm resistor the sensor will start to respond 4-6 inches away. With a 40 megohm resistor the sensor will start to respond 12-24 inches away (dependent on the foil size)...

However, as mentioned above, what I'm measuring is the time taken to change state, and I understand that more resistance = more time taken = higher value, how exactly does increasing the resistance make the sensor more sensitive, allowing it to respond without even touching it (i.e., inches away)?

Am I not simply increasing the time taken to change state by increasing resistance? How would that make it more sensitive?!?

# Answer
> 5 votes
A capacitor is created from two conductors with a dielectric between them. The capacitance of the capacitor is determined by the surface area of the conductors and the distance between them. The larger the conductive surface, the higher the capacitance. **The further apart the conductors, the smaller the capacitance. Using a higher resistance means that you can use a smaller capacitance, i.e. be further away from the sensor**, to get the same results.

---
Tags: arduino-uno, sensors, library
---


# Question
Title: How do I know if a board fits my requirements?
I'm new to Arduino and I saw on their website that there are many different kinds of boards. What are the differences, or to be more specific, how would I know which board meets my requirements? I understand that the shields can be connected to the board, but are some boards that do not support certain shields?

Another thing, is it possible to connect external sensors to an Arduino board or there are special sensors that can communicate with the board? I want to use weight sensors.

# Answer
> 8 votes
**Things to consider when picking an Arduino board:**

* Do I want native keyboard/mouse support? If yes: you'll need the Leonardo (or it's breadboard mountable equivalent) or the TRE (not released, dual MCU board).
* Do I want a small form factor and/or have it breadboard mountable? If yes, choose a board like the Mini/Micro/Nano/etc.
    + If you want to make it even smaller, either get a board without USB built in or try using an ATTiny
* Am I computing large numbers with it? If yes: use the Due, Galileo, or TRE (not released yet)
* Do I want video/audio? If yes: TRE is the only way to go as of now (but it's not released yet).
* Do I need a USB host (and not want to have an external shield)? If yes, use the Mega ADK (limited support), Yun, TRE (again, not released yet), or Galileo.
* Do I need WiFi/ethernet built in? If yes; use the Yun, TRE (still, not released yet), Ethernet *board*, or Galileo.
* How many pins do I need (and how many of each type)?

+ Digital: simple ON or OFF. Use these for buttons, simple lights, some communication, etc.
        - Stay away from the Due if you don't want to mess with 3.3V logic. Most other boards are 5V. You can work around this with either voltage dividers (doesn't always work) or level shifters. As far as I know, you can't really do much if a sensor provides max 5V; level shifters AFAIK only work with digital signals.
    + UART Pins: these are the pins that you can use the serial library on. (Note: this doesn't include the software-serial library). One of these on most boards is connected to a USB chip.
    + SPI Pins: These are pins which are used by a form of communication (like on the Ethernet shield).
    + Inturupt Pins: These can trigger an event when the signal getting sent to the board changes. There are a couple of different settings, but this can be used for near-instant response time when low latency is critical.
    + PWM Pins: pins that go on and off to simulate a lower voltage. It does this by turning it on and off very rapidly. This is used often for dimming LEDs and controling the speed of a motor.
    + Analog pins: pins that can read a voltage and convert it into a number.
        - The Arduino Due has a much higher precision rate, as it has more possible values and it has less voltage, thus much more accuracy.

All of these types of pins can act as a digital pin. All of these, except the analog pins, are under the "digital pin" section of your Arduino board. I didn't go into the technical aspects of the pins; I explained then in the simplest way I could.

I left a lot of boards out of this list, but this should give you some things to think about when choosing a board. There's a lot of weird quirks with this list, so it's incomplete, especially with the types of pins. You'll just have to do research and figure out what you need and if a board can meet your needs. Just make sure to not plan two things on the same pin, especially when mixing different shields and sensors! Shields *do* take up pins.

---

Shields: they are pretty much compatible with every board except for if the board is 3.3V (newer shields can adapt automatically) OR if it's a breadboard mounted board, like the Nano. There are ways to work around this problem, but it's very difficult.

# Answer
> 2 votes
To start with arduino you need to have some factors in consideration, for example the board you will chose, arduino UNO being the starting board for most beginners, if you are already an experienced programmer in C++ you might want to try more powerful boards. You have a pretty good overview of all of them in this link : http://arduino.cc/en/Main/Products Also there are hundreds of shields out there, you will find some in the link above. Adafruit also has some interesting ones, https://www.adafruit.com/search?q=arduino, you can even find them on ebay, and you can always buy individual sensors, LEDs, buttons etc, and plug them in directly or in a breadboard. Sparkfun has a big variety of very interesting sensors. There is also a lot of open source shields out there, you can check a very simple one i designed myself : http://electropepper.org/projects/prototyping/item/proto-i-os-arduino-v1-0

# Answer
> 2 votes
The usual suggestion I give to people new to Arduino is to get a Starter Kit (either from the store or from a local reseller): it contains an UNO, plenty of sensors and actuators and a projects book.

# Answer
> 2 votes
There are some good answers already, but here are a some secondary considerations

1. Many Arduino boards use a ceramic resonator rather than a crystal as their timing source. This rules out using them in critical timing applications. For instance you might need to add a real time clock board if you need to keep track of time of day.
2. The boards based on the Atmega328 chip only have three timers, and one of these (Timer 0) is used by the delay() function, which is in turn used by other libraries. Timer 1 and timer 2 get used if you include the PWM and tone libraries. The boards based on the 2560 chip have 6 timers, which is a lot more generous.
3. If you want to count external inputs at speed (i.e. up to 4MHz), you need to access the Tn pin of the appropriate timer counter(s). On the UNO, only T0 is exposed to the outside world, and the timer is already in use. Even the Mega2560 boards only seem to expose T0 and T5.

---
Tags: sensors, shields, system-design
---


# Question
Title: How to create delays in AVR assembly language
Hi i'm new to AVR assembly language so i was trying to get delay function to create 1 ms , 100us, and 1us delays to do that i need to figure out what to replace nop's with below here (mainboard arduino uno r3 ATmega328 Thank you.

```
"delay_ms%=:    nop                 ; code to replace  nop  \n"
"delay_100us%=: nop                 ; code to replace  nop  \n"
"delay_1us%=:   nop                 ; code to replace nop  \n"
"               sbiw r30,1          ; decrement ms count (r31:r30)\n"
"               brne delay_ms%=     ; loop to delay_ms while > 0  \n"
"               ret                 ; return from subroutine      \n"

```

The rest is below.

```
word millisecs;
Serial.begin(9600);
}
void setup() asm volatile(
"          ldi r16,0x3F    ; r16 = 00111111\n"
"          out 4,r16       ; set pins 8-13 as outputs in DDRB\n"
::: "r16");
millisecs = 1000;            // 1s blink delay
Serial.begin(9600);
}
void loop()
{
long starttime = millis();        // make a note of the start time

asm volatile(
// jump to "blink" - ie jump around the delay_ms subroutine
"            rjmp  blink%=        ; relative jump to 'blink' \n"
"          ldi r16,0x3F    ; r16 = 00111111\n"
"          out 4,r16       ; set pins 8-13 as outputs in DDRB\n"
::: "r16");

registers used:
r31 - millisecond count (lo byte)
r30 - millisecond count (hi byte)
r17 - 100 microsecond count
r16 - 1 microsecond count
Overall delay (ms) = r30:r31 * r17 * r16
---------------------------------------------------------------------*/
"delay_ms%=:    nop                 ; code to replace  nop  \n"
"delay_100us%=: nop                 ; code to replace  nop  \n"
"delay_1us%=:   nop                 ; code to replace nop  \n"
"               sbiw r30,1          ; decrement ms count (r31:r30)\n"
"               brne delay_ms%=     ; loop to delay_ms while > 0  \n"
"               ret                 ; return from subroutine      \n"

```

# Answer
> 3 votes
AVR LibC already has macros that do this, provided `F_CPU` is set correctly.

```
// Note: The Arduino IDE gets the value for F_CPU from boards.txt
#define F_CPU xxxxxxxxxx

#include <util/delay.h>

 ...

_delay_ms(1);
_delay_us(100);
_delay_us(1);

```

---
Tags: avr, assembly
---


# Question
Title: Arduino servo acts weird with photocell (lightsensor)
I have a weird thing with my servo, I really dont know what is wrong with my code, I tried everything. Either it is my connection on arduino or my code. Please help me guys, this is my code.

```
#include <Servo.h>

int servoPin = 9;
Servo servo;
int angle = 0;
int photocellPin = 0;

void setup() {
  servo.attach(servoPin);
}

void loop() {
  int reading = analogRead(photocellPin);
  Serial.print("Reading = ");
  Serial.println(photocellPin);
  int newAngle = reading / 2;
  servo.write(newAngle);
  delay(80);
}

```

# Answer
> 3 votes
Servos accept a signal from 0 to 180, with 90 being the center point on the servo. analogRead() will output a number from 0 to 1023. The arduino "map" function makes a conversion easy to do. just replace

```
int newAngle = reading / 2;

```

with

```
int newAngle = map(reading, 0, 1023, 0, 180);

```

you can read more about the map function here: http://arduino.cc/en/reference/map

It is hard to tell from the picture that everything else is wired correctly, but this should fix up your code.

---
Tags: servo
---


# Question
Title: How do I avoid this error trying to connect arduino to pc with linux fedora 20
I used Arduino successfully on my old Linux Fedora 12 system. Now I have a brand new PC with Fedora 20, and have today installed Arduino on it. In my first attempt to use it I typed Arduino as follows at the root prompt, after the "yum install arduino" gave me "Complete!", as follows:

```
Complete!
[1344][root@localhost:/home/Harry]# arduino
WARNING:  RXTX Version mismatch
    Jar version = RXTX-2.2
    native lib Version = RXTX-2.2pre2

```

Subsequently I have loaded the "Blink" sketch, and that is running nicely, whether I start the IDE from the command line, which still gives me the same WARNING, or from the desktop icon, which does not give it.

So my question is: please, does this WARNING matter? If so, what should I do about it?

# Answer
The warning, as I'm sure you can tell, is about a mismatch in version of RXTX arduino is expecting, and what is installed on your system. If everything is functioning, I would not worry about it at all. The versions seem to only be slightly different, maybe just a few bug fixes are missing from the older one.

RXTX is a library for java to communicate with serial devices, but it is not under development anymore and only available from mirrors, not the original developer site. Arduino has moved on to a library called jSSC, which is currently being maintained, and a much better library IMHO. The change to jSSC is still only in the arduino beta version, 1.5.6r2 at time of writing, but it works very well. Anyway, if RXTX ever actually gives you trouble, you can download the beta version of arduino and not have to deal with it.
> 2 votes

---
Tags: arduino-uno
---


# Question
Title: How do I remotely acquire data from Arduino based portable device?
I am making a device which will have an Arduino board and a sensor attached to it. The sensor will acquire data every 10 minutes and the data will be uploaded to my server. The size of every upload is about 200 characters. I'd like this device to work anywhere in my city (US).

What are my options for uploading data to my server? Keep in mind that it will work without human intervention. FYI... this is NOT for reconnaissance device! ;)

# Answer
I can't guarantee *anywhere* in your city, but this hack will work pretty much wherever there is cell coverage for the carrier you choose.

You'll want the **GSM shield**.

>

*Picture from Arduino*

Anyway, it uses pins 2, 3, and 7 on it. It also has the ability to solder (on the bottom of it) a microphone and speaker connection. You'll need to buy a SIM card and a contract to connect your shield to a network. I don't know how often you would use this, but I've seen a pay-as-you-go plan that charges you $2 for unlimited talk/text/internet per day. If you're going to use this once a month, that would be the way to go. I didn't look to see if they supported the GSM shield (it was on TMobile's site). You would want to contact them for more details. Also, depending on where you live, I don't know if you would get good coverage. This goes with any cell phone provider, but make *sure* that you get coverage where you want to go (and don't always trust the maps they provide).
> 5 votes

---
Tags: uploading, networking
---


# Question
Title: error: no '' member function declared in class 'SonarSRF08'
Hi, I am a pretty novice coder and I am getting this error consistently with a library I have installed. Here is the code I am trying to run:

```
#include <Wire.h>
#include <SonarSRF02.h>
#include <SonarSRF08.h>

#define leftAddress ( 0xF2 >> 1)
#define rightAddress ( 0xE0 >> 1)
#define mainAddress ( 0xF8 >> 1)
SonarSRF02 LeftSonar;
SonarSRF02 RightSonar;
SonarSRF08 MainSonar;

char unit = 'c'; // 'i' for inches, 'c' for centimeters, 'm' for micro-seconds

void setup() {
    Serial.begin(115200);

    LeftSonar.connect(leftAddress);
    Serial.println("Left SRF02 US-Sensor ");
    Serial.println(LeftSonar.getSoft());

    RightSonar.connect(rightAddress);
    Serial.println("Right SRF02 US-Sensor ");
    Serial.println(RightSonar.getSoft());

    MainSonar.connect(mainAddress);
    Serial.println("Main SRF08 US-Sensor ");
    Serial.println(MainSonar.getSoft());
}

void loop() {
    float sensorReading = 0;

    sensorReading = LeftSonar.getRange(unit);
    // print out distance
    Serial.print("Distance from left: ");
    Serial.print(sensorReading);
    Serial.print(" ");
    Serial.print(unit);
    Serial.println();

    sensorReading = RightSonar.getRange(unit);
    // print out distance
    Serial.print("Distance from right: ");
    Serial.print(sensorReading);
    Serial.print(" ");
    Serial.print(unit);
    Serial.println();

    sensorReading = MainSonar.getRange(unit);
    // print out distance
    Serial.print("Distance from main: ");
    Serial.print(sensorReading);
    Serial.print(" ");
    Serial.print(unit);
    Serial.println();
}

```

My project is using an SRF08 sensor with an Arduino Mega 2560

# Answer
> 3 votes
**Please note that I did not try to run your code on my Mega because I don't have SRFs**

However, here is what I tried to recreate your error:

* I went to the arduino homepage and downloaded the 1.0.5 version.
* I downloaded the zipped library from this page SRF08 Ultra Sonic Range Finder
* I imported the library into the arduino IDE. For this, I had to unpack the .zip and rename the folder of the library because arduino complained about non-ascii characters. I just called the enclosing folder "arduinoSRFmaster" without dashes. After that it let me import the library the usual way:
* After that I copied your code into a new sketch and hit Ctrl + R to compile and verify. It compiled just fine:

(Picture updated for compiling against MEGA)

**Please provide more information, like yor OS, Arduino Version, where you got the SRF Library from etc. if that didn't help.**

---
Tags: arduino-mega, c++
---


title: Why does serial port stop sending data?

text:
# Question
Title: Why does serial port stop sending data?
I'm using an Arduino Leonardo to interface with two pressure sensors and Python on my laptop, a MackBook Pro.

I'm using arduino IDE V. 1.5.4, Python V. 2.7.6, and OSX 10.8.5.

One pressure sensor is digital, using the Wire lib, and the other is analog.

My sketch compiles, runs, and works until I try to get the data in Python using pyserial.

If I try to grab a bunch of data using the readlines method in the scrip it will only return blank data or hang, depending on the serial object timeout settings. My python code sometimes works from the repl when I initialize the serial object and wait before reading from it. If I don't wait the serial object will only partially fill a list and then any future reads will return an empty string. This continues even after closing the serial object and reopening it in Python, or closing the serial object in Python and then opening the Serial Monitor in the Arduino IDE. Once the serial port stops sending, I have to reset the Leonardo in order to read new data.

I could be running into some kind of buffering problem, but if that were the case I would expect future calls to return data. Another option is that the Wire protocol is getting stuck and halting the program.

Here's my sketch

```
#include <Wire.h>

int ADDRESS = 0x28;//I2C address of sensor
int REQUEST = 4;//# of bytes to request from sensor
int BAUD = 19200;//serial rate
int PRESSURE_PIN = 1;

void setup()
{
  pinMode(A1, INPUT);
  Wire.begin();        // join i2c bus (address optional for master)
  Serial.begin(BAUD);  // start serial for output
}

void loop()
{
  Wire.requestFrom(ADDRESS, REQUEST);    // request 6 bytes from slave device #2

  Serial.print(analogRead(PRESSURE_PIN));
  Serial.print(',');

  while(Wire.available())    // slave may send less than requested
  {
     Serial.print(((unsigned int)Wire.read() << 8) + Wire.read());
     Serial.print(',');
     Serial.println(((unsigned int)Wire.read()) << 3) + (Wire.read() >> 5);
  }

  delay(10);
}

```

and here is how I read it from python

```
import serial

serial_port = '/dev/tty.usbmodem1a1221'
ser = serial.Serial(serial_port, 19200, timeout=0)

vals = [val.split(',')[0:2] for val in ser.readlines(1001*14)]

```

# Answer
The leonardo doesn't reset when the serial port is opened.

To check it isn't python, run your Arduino code, then open the terminal and run

```
screen /dev/tty.usbmodem1a1221 19200

```

NOTE: to exit the screen session type Ctrl-A Ctrl=\ (see here). If you just close the window it will stay connected and lock up the serial port until you recycle the power on the Arduino.

If the Arduino program spits out just fine to screen, then python is the problem. One thing that can happen is a python/java/whatever program can lock up the serial port driver, *but recycling the Arduino power, not restarting the program,* is required to reinitialise the driver. So the Arduino is not necessarily problem, as the serial port will stay locked up for ALL programs. So "I would expect future calls to return data" is actually wrong. If I stuff up the serial port code in my java interface programs the same kind of thing happens.

Other ideas:

* Make the delay longer than 10ms.
* Make sure hardware flow control is off in the python serial
* Flash a LED in the Arduino loop to see if it is the main loop locked up or if that is running fine.
> 0 votes

# Answer
The Arduino forums talk the Arduino resetting when the serial port is opened. A solution as stated in the forums is to add a short delay. See if that works.
Source: http://forum.arduino.cc/index.php/topic,18371.0.html
> 0 votes

# Answer
My eventual workaround for the Leonardo was to set up a call-response loop on the Leonardo. Here's the code:

```
#include <Wire.h>

int ADDRESS = 0x28;//I2C address of sensor
int REQUEST = 4;//# of bytes to request from sensor
int BAUD = 19200;//serial rate

void setup()
{
  pinMode(A1, INPUT);
  Wire.begin();        // join i2c bus (address optional for master)
  Serial.begin(BAUD);  // start serial for output
}

void loop()
{
  if (Serial.available() > 0) {
    Serial.read();
    Wire.requestFrom(ADDRESS, REQUEST);    // request 4 bytes from slave device at 0x28
    while(Wire.available())    // slave may send less than requested
    {
       Serial.print(((unsigned int)Wire.read() << 8) + Wire.read());
       Serial.print(',');
       Serial.println(((unsigned int)Wire.read()) << 3) + (Wire.read() >> 5);
    }
  }
}

```

I was able to simplify a little.

There are two things to note:

* There is no built in delay and requests made too quickly will result in either an empty response or old data from the sensor. Have to take into account in requesting program.
* The sketch will respond a number of times equal to the number of bits sent. Use a single ASCII character for one response, 2 characters for 2 responses, etc... This is important if you use an API similiar to a write() and writeln() as the second sends extra characters.
> 0 votes

---
Tags: serial, python
---


title: Connecting a USB 3.0 Flash Drive

text:
# Question
Title: Connecting a USB 3.0 Flash Drive
Is it possible to connect the nine pins from a USB 3.0 memory drive to the corresponding GPIO pins of the arduino (intel Galileo is what I am using, but it is very similar) and access the drive's memory through the implementation of the USB's protocol? I have searched around and have not been able to get a clear idea on how to do this or if it is even possible.

# Answer
> 1 votes
Since this is going to be a long post, I'll post the summary above the fold to save some of you the effort of scrolling...

**tl;dr:** No, it's not possible to do so with GPIO pins. There is another way to do this, but IDK if the rest of the Galileo will be a bottleneck (and it's pretty pricey). The stereotypical AVR Arduino is simply too underpowered (both from a MCU and amperage standpoint) to host USB 3.0. You need a shield to host USB 2.0, and even with that, I doubt that you can use 2.0 at it's full potential.

---

## Basic corrections/things to note (before I begin):

* Note: I'm no expert on the Galileo, I'm just doing this all from what I remember from what I've read in the past. If you spot an error, feel free to post a comment with a little explanation and I'll fix my post. However, I doubt that there will be any major errors, and the overall content (i.e. the tl;dr) should be fine.
* These figures are maximum that I'm posting:

+ Speed: if speed is near maximums, or even 10%, what's the point of 3.0?
    + Power: you never know with this one, so account for it being near limits, unless externally powered. Still, don't risk it.
* If it's a USB thumb drive, you're going to either get a breakout board for 3.0 and/or break open your device and solder wires onto it. Note that there doesn't seem to be a USB 3.0 breakout board (from a very quick search on Google). I'm also concerned that the wires you would use might not be high enough grade for extreme data transmission.
* Only 7 of the 9 lines are used for data. The other two are 5V and GND.
* On a Galileo, you'll have to use the 5V selection for the IO pins.
* On a Galileo, there's a Mini-PCIe port (although I can't seem to find it in the photos myself). You could add a Mini PCIe to USB 3.0 card. However, that will cost you almost $50 to do so, and by that time it might be better just to seek out another solution.

Photo of it:

+ Ask yourself *do I really need the speed?*
        - No: don't waste the money and the headache.
        - Yes: consider either another platform or buying this product.
    + Keep in mind that, although it fits, it probably won't be able to get enough power for true USB 3.0 that your disk needs *and* drivers will be rare. You for sure will want to research this more before shelling out the cash to buy this card.
        - Galileo doesn't run a full OS, so I'm highly doubtful that there's drivers.
* Like I mentioned before, I'm not quite sure about the Galileo supplying enough power... again you need to check into this and maybe add an external voltage regulator (if all the other issues are resolved). USB 3.0 can provide up to 2x the power per port of 2.0, so when I say almost an amp, it's technically almost two amps (although I think at this point you'll just have to remember not to use the second port and call it one amp).

---

## Technical problems:

I stated this before in the post:

> *The stereotypical AVR Arduino is simply too underpowered to host USB 3.0. You need a shield to host USB 2.0, and even with that, I doubt that you can use 2.0 at it's full potential.*

The Galileo has native 2.0 support, so I'd recommend just getting a fast USB drive and using that.

Anyway, think about it: the Galileo can handle roughly 400,000 instructions per second. USB 3.0 can send up to **5,000,000 bits in the same amount of time!** Like mentioned before, it is the maximums, but still. AFAIK on the AVR boards it it takes multiple instructions to read one GPIO pin (for some reason I want to say 3, but that seems too low). I'd imagine that it'd be the same situation on the Galileo. I'm not quite sure about the instructions it takes to read a pin, correct me if I'm wrong anyone. Anyway, assume it takes four instructions per pin, and your device only sends 1 Gbps. That's still 1,000,000 times that a pin needs to be read when you can only read 100,000 in that time. Even so, you can't even *use* the data, nor can you implement a loop or other code that combines bytes to read the data in the first place! Plus, you wouldn't have enough RAM!

I'm not a USB expert, but IIRC it only asks the device for data as needed, but still, that'd be pointless to create your code for this and spend the extra money for 3.0 cables and devices. This paragraph is all from memory, I don't really know; ***don't cite this paragraph.***

Also, you'd have to implement your own code for sending data to/from the device. No such code exists without hardware for 2.0, let alone 3.0.

---

## Conclusion:

It's near impossible to do so, and you'd need a lot of extra parts and have to read up on the USB 3.0 specs. I think it would take a great engineer 50+ years to accomplish this without developing an IC (which would cost money). Do you really *need* the speed? If not, you can buy USB 2.0 host shields and communicate via SPI. That isn't very fast, but still, it's possible.

---

## Sources:

Info and photos are scattered on the following sources:

---
Tags: serial, pins, arduino-galileo
---


# Question
Title: Button to optocoupler to fire camera 4 times
Ok, this is my first project where I've not had @forsvunnet close by to help.

I've got a camera connected to an optocoupler, that just fires HIGH then LOW.

I can't get a button working with it, so when I push a button, it fires opto 3 times.

This is my sketch.

```
 // Pin 13 has an LED connected on most Arduino boards.
// give it a name:
int opto = 12;
int buttonInput = 2;     // the number of the pushbutton pin
int buttonState = 0;         // variable for reading the pushbutton status

// the setup routine runs once when you press reset:
void setup()
{
// initialize the digital pin as an output.m
pinMode(opto, OUTPUT);
pinMode(buttonInput, INPUT);
digitalWrite(buttonInput, LOW);}

// the loop routine runs over and over again forever:
void loop()
{
  buttonState = digitalRead(buttonInput);
  if (buttonState == HIGH) {
      digitalWrite(opto, HIGH);
      delay(1000);               // wait for a second
      digitalWrite(opto, LOW);
      delay(1000);               // wait for a second
      digitalWrite(opto, HIGH);
      delay(1000);               // wait for a second
      digitalWrite(opto, LOW);
  } else {

  }

}

```

Anyone point me in the right direction? It's driving me mad.

# Answer
> 1 votes
**First of all, the loop (if it worked well) would only fire twice.** It should only fire when you turn it on/off in a cycle (unless it's a rising/falling edge circuit (i.e. a *pull down button*/a falling edge interrupt), but I won't get into that). In your code you toggle it twice. The third one? I suspect that your camera only fires when it's given a low signal. This means that, when you set it to low in `setup()`, it takes a photo. To fix this, switch all the `HIGH`s and the `LOW`s for the `opto` pin.

This is the code which I think should work for you:

```
// Pin 13 has an LED connected on most Arduino boards.
// give it a name:
int opto = 12;
int buttonInput = 2;     // the number of the pushbutton pin
int buttonState = 0;         // variable for reading the pushbutton status

// the setup routine runs once when you press reset:
void setup()
{
// initialize the digital pin as an output.m
pinMode(opto, OUTPUT);
pinMode(buttonInput, INPUT);
digitalWrite(buttonInput, HIGH);}

// the loop routine runs over and over again forever:
void loop()
{
  buttonState = digitalRead(buttonInput);
  if (buttonState == HIGH) {
      digitalWrite(opto, LOW);
      delay(1000);               // wait for a second
      digitalWrite(opto, HIGH);
      delay(1000);               // wait for a second
      digitalWrite(opto, LOW);
      delay(1000);               // wait for a second
      digitalWrite(opto, HIGH);
      delay(1000);               // wait for a second
      digitalWrite(opto, LOW);
      delay(1000);               // wait for a second
      digitalWrite(opto, HIGH);
      delay(1000);               // wait for a second
      digitalWrite(opto, LOW);
      delay(1000);               // wait for a second
      digitalWrite(opto, HIGH);
  } else {

  }

}

```

Without much info about your camera, I'd imagine that the `HIGH`/`LOW` discrepancy is the issue. Another note: this code doesn't protect against bouncing. It's fine if as it is because the delays will cause the bounces to not be picked up. If you do a "blink without delay" type of sketch using `millis()` and a loop, you might need to fix this. Like I said, it'll work fine now, but it's kind a crude fix since it could cause problems later if mixed with other code.

---
Tags: button
---


title: How to use String.substring?

text:
# Question
Title: How to use String.substring?
I have the following code in which `requestLine` is always empty and I can't figure out why. `request` contains a raw HTTP request, and I want to get the first line of the request which contains the method and the URL.

```
boolean parseRequest(String* request)
{
  int firstEOLAt = request->indexOf('\n');
  if (firstEOLAt < 0)
    return false;
  Serial.println(firstEOLAt);
  String requestLine = request->substring(0, firstEOLAt);
  Serial.println(requestLine);
  // ...rest of the parsing will go here...
  return true;
}

```

The first `println` returns 26 as you would expect for the string `"GET /ilyen_nincs HTTP/1.1"` (25 characters long), but then `requestLine` is always empty. I wonder why?

# Answer
> 2 votes
`GET /ilyen_nincs HTTP/1.1\n` is 26 characters long so string indices are from 0 to 25. Since, your second argument in `substring(0, firstEOLAt);` exceeds the end index of the string, you are running into unexpected behavior as per the documentation and getting an empty string.

> Caution: make sure your index values are within the String's length or you'll get unpredictable results. This kind of error can be particularly hard to find with the second instance of substring() if the starting position is less than the String's length, but the ending position isn't.

---
Tags: arduino-uno, string, pointer
---


title: 1 Wire temperature sensor

text:
# Question
Title: 1 Wire temperature sensor
I bought a waterproof temperature sensor from Ebay, I am fairly new to this and not sure what I need or need to do in order to get the sensor to output the current temperature to the serial monitor.

Does anyone have any information on where I can get some information on how to wire this? I have looked at various videos online but they are all for a dallas temp sensor and use the dallas library.

http://www.ebay.co.uk/itm/181393039374?ssPageName=STRK:MEWNX:IT&\_trksid=p3984.m1439.l2649

# Answer
> 1 votes
This probe has the Dallas (now Maxim) DS18b20 sensor in it so you're already on the right track. Search for DS18b20 at arduino.cc. You'll find libraries and lots of forum discussions about using these sensors. Also see page 6 of the DS18b20 datasheet; there are two schematics for wiring the device.

I'm using the parasitic mode (Figure 4 on that page) except I eliminated the transistor switch and connected the MCU pin for the strong-pullup directly to the one-wire bus.

---
Tags: arduino-pro-mini, temperature-sensor
---


# Question
Title: What's the most accurate way to time-stamp analogRead data?
I want to sample an Analog sensor as fast as possible, and time-stamp each sample that I take as accurately as possible.

Currently, I'm doing the following:

```
val = analogRead(SENSOR_PIN);
clocktime = micros();

writeData(val, clocktime); // writes the values to an SD card

```

I'm wondering if there is a more-accurate way of time-stamping the data from the analogRead call. Put another way, I would like to record the exact time that the analogRead data was collected. My guess is that this is basically impossible on an Arduino, so what technique will let me get as close as possible?

# Answer
For "as fast as possible", I'd

1. Rewrite your sampling code in assembly language (just those two statements, not the whole program); and
2. Buffer the raw data pairs in memory if you have enough of it, then store it to the card after the measurement burst. If you need more data space, consider that the timing of a tight assembly loop will be consistent (and fast!) and can be measured. You may not need to read the clock at all. Note that you can get the same timing consistency using C/C++ if you read the analog and clock ports directly, and maybe as fast. It's just that with assembly language, WYWIWYG (what you write is what you get); the compilers' code-generators and optimizers won't mess with it.

A possible issue with your code as you've written it is that writeData probably buffers the data on most calls, but whenever a call results in a full buffer, writes the whole buffer to the card, introducing jitter into your sampling.

Addressing your edit of June 3, 2014, "I would like to record the exact time that the analogRead data was collected":

Since you proposed using micros() (as opposed to a real-time clock), I assume you are satisfied with the relative time. Once you know your data collection code is completely predictable, then the offset from reading data to reading time is constant, and since we're using relative time anyway, can be discounted, or at least, corrected for.

It isn't *completely* predictable of course, since in this case, you're using an interrupt-maintained clock, and can expect that sometimes the interrupt will occur between the data read and the clock read, stretching the offset for that tuple. To get even more accurate, you'd need to keep interrupts off, read the timer yourself in an invariant way. f/ex, you might run the timer at such a rate that you could expect to take two or more samples between overflows of the low-order byte, read and store only the low order byte as your time sample, and post process the time data to reconstruct the high order byte by detecting wrap-around in the low-order.

With no interrupts running, and once you know the rate at which you can sample data without reading the clock, you could read and save the clock once immediately prior to taking the first sample, and infer the times of each subsequent sample based on the known sample rate.
> 3 votes

# Answer
There is no more accurate way of getting time on the arduino, but I would suggest you use millis() instead.

micros() returns microseconds, or millionths of a second, since the arduino was turned on. The issue is that the 32 bit unsigned integer used to store time on the arduino can only count about 70 minutes worth of micros before overflowing and resetting to 0. (see http://arduino.cc/en/reference/micros)

millis() is in thousandths of a second since the arduino turned on, and it will not reset for about 50 days. If you think one thousandths of a second is good enough resolution, it will probably be the better choice.

If you need time to be absolute, as in the current day/hour/minute, you will need to buy a real time clock to plug into the arduino. They are about 20 bucks, and available from all the standard arduino accessory stores like sparkfun, adafruit, ect.

On your question of the order, both commands run so quickly, I can think of no reason it would matter.
> 5 votes

---
Tags: time, analogread
---


title: Best way to interact arduino and python

text:
# Question
Title: Best way to interact arduino and python
So, i've worked with the pySerial module for python, where I communicated with my arduino via serial. However, this module only works for 32bits and I would like to make my project work on both architectures (I know the person could just install the 32-bits version on the 64-bits architecture). Also, the connection fails a lot of times and I wasn't able to correct it.

I think I can use the true USB power of the arduino Leonardo to connect to the python in a different way, but I don't know where to start. But I think this approach will be more professional.

Im really intersted in learning, so if you guys could at least indicate documents so I can understand how to make this connection between Leonardo and Python, I'll be happy. I've read the arduino page about the CDC but couldn't find useful information.

Thank you so much.

Update:

When i used serial, I had problems with messages getting acumulated at the buffer, and then after some seconds i was reading 10s delayed messages. Also, when I sent a string like: "12345678", it was really easy to get one number less, like: "1345678". This happened frequently to me. So I think I need to implement a protocol to deal with these problems.

# Answer
I did some work in Java using USB some years ago and I can share some experiences:

* Things are not neary as straightforward as using serial.
* Your code will probably be platform specific, windows being a bit more weird about handling usb. (unless using something to abstract that away, like PyUSB which wraps libUSB or openUSB, this however does not guarantee platform independency because these libraries also have their weirdnesses).
* If you drop down to USB level programming, things can get very messy (again, this can be abstracted away). USB is (at least in my opinion) a complicated protocol, especially for beginners.

So unless you really need something that only USB can provide, a nice and dandy serial communication will give you much less headaches. Thats why serial did not die until now.

As for debugging why your communication is not reliable I would try several things:

* See if your application might send something that is interpreted as a control character
* Drop your baud rate to something lower and see if it still loses data. If so, you might overflow the buffer of your receiver (and you would need flow control in this case)
* Check your hardware! I've had bad wires or solders on numerous occasions
> 1 votes

---
Tags: serial, i2c, python
---


# Question
Title: Is volatile needed when variable is accessed from > 1 ISRs, but not shared outside ISRs?
It's clearly documented that when global data is shared with an ISR and the main program, the data needs to be declared `volatile` in order to guarantee memory visibility (and that only suffices for 1-byte data; anything bigger needs special arrangements to guarantee also atomicity). Here we have good rules:

* Variables only used outside an ISR should not be volatile.
* Variables only used inside an ISR should not be volatile.
* Variables used both inside and outside an ISR should be volatile.

But is `volatile` needed when the variable is accessed from \> 1 ISRs, but not shared outside ISRs? For example, I have a function that maintains internal state using a `static` variable:

```
void func() {
    static volatile long counter; // volatile or not?
    // Do stuff with counter etc.
}

```

That function is called in two ways: from pin interrupt, and from TimerOne library:

1. `attachInterrupt(0, func, CHANGE);`
2. `Timer1.attachInterrupt(func);`

There are no atomicity problems, since when an ISR is entered, interrupts are automatically disabled, but this `volatile` is more of a compiler question: what is cached and what is not.

Better safe than sorry, of course...

# Answer
`volatile` only informs the compiler's code generator that the variable may be modified by something other than the code being generated, so not to assume any copy of it remains accurate.

ISR code must be written/generated under the assumption that it has no context at entry, and preserve the CPU's context around its (ISR's) own operation. So, as with the indivisbility of non-atomic operations, volatility depends, *in this case\**, on whether or not interrupts are allowed to nest. If non-nesting is guaranteed, the shared variable can not change by other than this ISR during its own execution. If your ISR might someday be used in an environment where interrupts are allowed to nest, then that constraint will no longer hold.

* *in this case*:
I'm assuming a software-maintained variable here. If we're talking about a variable that can be updated by a hardware event, a timer register for example, all bets are off: the variable is volatile no matter what.
> 9 votes

---
Tags: interrupt, timers, isr
---


# Question
Title: Do I need to use a resistor if I am using a potentiometer to control an LED's brightness?
I am currently tinkering with an arduino, and am using a potentiometer to change the brightness of an LED.

I understand that usually, a resistor is added to the circuit to limit the current flowing through the circuit in order to prevent the LED from burning out.

However, as I am currently using a potentiometer to adjust the LED's brightness, **AND** as a potentiometer is basically a variable resistor, would I still need a resistor to prevent the LED from burning out? Currently, I do not see a difference between using a 220 ohm resistor and not using it, as the LED seems unaffected.

My code:

```
const int pot=A0;
const int led=11;
int potValue;

void setup(){
  Serial.begin(9600);
  pinMode(pot,INPUT);
  pinMode(led,OUTPUT);
  analogWrite(led,100);
}

void loop(){
  potValue = analogRead(pot);
  potValue=map(potValue,0,1023,0,255);
  analogWrite(led,potValue);
  Serial.println(potValue);
}

```

PS: My LED is hooked up to the arduino's PWM pin, and connected to ground on a breadboard.

# Answer
Without a good quality picture of your setup or some schematics, it's hard to tell what's going on, but from your description, what you're doing is **potentially harmful for the LED and the output pin D11**.

Yes, LEDs almost always need series resistors to limit their current. They don't limit currents and will burn if you don't do it for them.

If you had the pot in series with the LED, which seems to be what you think is going on, you'd still need a series resistance so that when the pot is all the way to one side, effectively behaving like a 0Ω resistor or a short, you'd still be limiting the current with the 2nd resistor. One would usually use Ohm's Law to calculate that 2nd resistance so that it lets the maximum current the LED can take when the pot is at 0Ω position, usually 20mA for common LEDs.

**But that's not how your circuit seems to be wired**. The pot is indirectly controlling the LED through an analog input and a PWM output via MCU. So it's not limiting the LED current, in the traditional sense. The pot seems to be wired between 5V and GND with the middle lead (the cursor) hooked up to the analog input A0. That's a variable voltage divider configuration that let's you select a continuous voltage between 0 and 5V that is in turn converted to a value between 0 and 1023 by the MCU ADC (Analog to Digital Converter) - that's the result of the `analogRead()` call.

That value is then fed to a PWM analog output, through the `analogWrite()` call, that will output a square wave to the LED. The relative position of the pot will determine the duty cycle of the PWM, i.e., how long the square wave is HIGH or LOW. The problem here is that this circuit where the LED is wired should have its own series current limiting resistance.

To me, if you didn't burn the LED or the D11 pin yet, is pure luck. If you were to turn the pot all the way to maximum brightness (**don't do it**), the PWM output would act like a digital output put in HIGH level (5V continuously), and without a current limiting resistor, the D11 pin would exceed it's 40mA absolute maximum source current and burn. Unless there's another factor limiting the current that I don't know of, that is.

There are some exceptional cases in which you can control the LED voltage closely so you don't need to limit the current (multiplexing, constant-current supply etc.), but these are really advanced configurations for us newbies. So, from know on, do it like I do it: ALWAYS put a series resistor, until you become familiar with these advanced configurations.

Finally, below are some links that you may find helpful about the topic:
> 4 votes

---
Tags: arduino-uno, pwm, current
---


title: Connect two Arduinos using I²C (wiring)

text:
# Question
Title: Connect two Arduinos using I²C (wiring)
Altough having found a lot of documentation concerning wiring of I²C buses, I'm still not sure about the following question:

If both devices use separate power sources, is it a good idea to connect VCC/GND of those two devices?

I have two lines for SCL and SDA, connected to SCL/SDA pins on both devices A and B. The master device's VCC is connected to both lines using a pull-up resistor. Now as far as I understood, VCC/GND of the two devices should not be disconnected but I'm afraid I'd damage something if I'd connect them. As two separate power sources will never provide exactly the same voltage that would result in high currents, won't it? Or should I just connect them using some resistor to avoid high currents but provide the same voltage level?

# Answer
> 3 votes
The VCC lines aren't directly connected - you just have a shared data line with some voltage on it, which is always lower than VCC because of the resistor. Each device "talks" to the I2C bus by briefly connecting those lines to GND, which is common between both devices. Current is limited by the pull-up resistor, so it never gets too high. This makes it safe to directly link devices running at slightly different voltages.

# Answer
> 3 votes
Here's what you need to do:

* Leave the VINs disconnected. I'm not sure that it's a bad idea, but it is pretty much pointless. Like sburlappp said, the resistors lower the voltage between them (and reduce the current). With a resistor, it wouldn't *hurt it*, but there's really no need.
* Connect the grounds *directly*. Here's the problem: voltage is relative; it is measured very much like gravitational potential energy. It's the difference between the amount of electricity in both parts that determines the voltage. I'm pretty sure that if you don't, with the extra power, it could *fry* a component. That would happen when there is a lower concentration of electrons in "ground" on one of the boards than the other. That could result in many volts being passed along to the board. I haven't had this happen to me, nor have I really heard about this happening, but I guess it is a possibility.

---
Tags: i2c, wires
---


title: Non-blocking strobing code?

text:
# Question
Title: Non-blocking strobing code?
I'm trying to figure out how to create some non-blocking code to strobe some RGB leds with analogwrite 7 times a second; I'm really not to sure how to go about this. If anybody could give me some help that'd be great! :)

# Answer
> 1 votes
What you want can be achieved with your MCUs timers and their associated interrupts. Timers are basically counters that run inside your hardware and they run decoupled from your code. Since one usually knows how fast these timers tick (e.g. how long it takes to count from one to two and so on) you can specify events that happen when a certain amount of timer ticks passed.

I suggest you have a look at SimpleTimer and Timer1 (the second page is only for ATmega168/328)

Both pages include some code samples where they specify some method that will be called every x milliseconds.

# Answer
> 0 votes
Timers are the best way to go, (much) less overhead and you don't have to worry about it elsewhere in your code (other than managing variable use between your main loop and your ISRs).

But I do have a habit of doing things the hard way in code first and then move to timers once I've got it the way I'd like.

Here is sample code to flash the on board LED X times per second, I have calculated it to mean, ON 7 times per second and OFF 7 times as well (meaning, there is a change of state 14 times per second).

This code isn't efficient, it doesn't take into consideration that the value is already set or not, it just writes the value that it should be right now.

Finally, to go to analogWrite and use PWM, just change:

```
digitalWrite(LED, HIGH);

```

to

```
analogWrite(NEW_PIN, PWM_VALUE);

```

code:

```
#define LED               13
#define TIMES_PER_SECOND  7

const int M1 = 1000 / TIMES_PER_SECOND;
const int M2 = 1000 / TIMES_PER_SECOND / 2;

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

void loop(){
  if(millis()%M1<M2){
    digitalWrite(LED, HIGH);
  } else {
    digitalWrite(LED, LOW);
  }
}

```

Remember there is overhead with digital (and analog) writes, so (as I mentioned) you could check to see if the value is set already or not and skip the write.

---
Tags: analogwrite
---


# Question
Title: Executing multiple functions/commands on Arduino
I am using an RFduino and an iOS application to control some RGB LEDs.

This is how I'm sending a string command to the module:

```
- (IBAction)fadeButtonPressed:(id)sender {
    [rfduino send:[@"fade" dataUsingEncoding:NSUTF8StringEncoding]];
}

```

These command(s) are coming back just fine on the RFduino side:

```
void RFduinoBLE_onReceive(char *data, int len) {
  if (strncmp(data, "fade", 4) == 0) {
    // begin fading chosen LED colour
  }
}

```

Is there a better way of executing multiple functions on Arduino? It seems to me that there should be a better way of doing what I'm trying to do.

Originally for example I was getting an issue where the "fade" string was coming back as "fadek" so I used `strncmp(data, "fade", 4)` instead of `strcmp(data, "fade")` and this fixed the issue.

I guess I'd like a way of cleaning up my code and perhaps make it easier to introduce new bits of functionality depending on which strings are coming back.

The functions I would like to be able to do would be controlling of the RGB colours and then *Fading* or *Blinking* that particular chosen colour.

What if I wanted to introduce faster blinking? Rather than setting another command integer and adding another condition is there a cleaner approach?

The selection of the colours is set by selection of a color wheel within my iOS application. This is working fine. The problem is that the Blinking and Fading does not blink/fade the selected colour (`command 0`).

Here is my entire sketch so far:

```
#include <RFduinoBLE.h>

// Pin 2 on the RGB LED.
int rgb2_pin = 2; // red
int rgb3_pin = 3; // green
int rgb4_pin = 4; // blue
int brightness = 0;
int fadeAmount = 5;

// Command properties.
int command = 0;

void setup() {
  // debug output at 9600 baud
  Serial.begin(9600);

  // Setup the LEDs for output.
  pinMode(rgb2_pin, OUTPUT);
  pinMode(rgb3_pin, OUTPUT);
  pinMode(rgb4_pin, OUTPUT);

  // This is the data we want to appear in the advertisement
  // (the deviceName length plus the advertisement length must be <= 18 bytes.
  RFduinoBLE.advertisementData = "rgb";

  // Start the BLE stack.
  RFduinoBLE.begin();
}

void loop() {
  if (command == 1) { // Fade in/out chosen colour.
    analogWrite(rgb2_pin, brightness);
    analogWrite(rgb3_pin, brightness);
    analogWrite(rgb4_pin, brightness);

    // Change the brightness for next time through the loop:
    brightness = brightness + fadeAmount;

    // Reverse the direction of the fading at the ends of the fade:
    if (brightness == 0 || brightness == 255) {
      fadeAmount = -fadeAmount ;
    }

    // Wait for 30 milliseconds to see the dimming effect
    delay(30);
  } else if (command == 2) { // Blink
    digitalWrite(rgb2_pin, HIGH);
    digitalWrite(rgb3_pin, HIGH);
    digitalWrite(rgb4_pin, HIGH);
    delay(200);
    digitalWrite(rgb2_pin, LOW);
    digitalWrite(rgb3_pin, LOW);
    digitalWrite(rgb4_pin, LOW);
    delay(200);
  }
}

void RFduinoBLE_onConnect() {}

void RFduinoBLE_onDisconnect() {}

void RFduinoBLE_onReceive(char *data, int len) {
  Serial.println(data);

  // Each transmission should contain an RGB triple.
  if (strncmp(data, "fade", 4) == 0) {
    command = 1;
  } else if (strncmp(data, "blink", 5) == 0) {
    command = 2;
  } else { // Change colour.
    // Reset other functions.
    command = 0;

    if (len >= 3) {
      // Get the RGB values.
      uint8_t red = data[0];
      uint8_t green = data[1];
      uint8_t blue = data[2];

      // Set PWM for each LED.
      analogWrite(rgb2_pin, red);
      analogWrite(rgb3_pin, green);
      analogWrite(rgb4_pin, blue);
    }
  }

  Serial.println(command);
}

```

# Answer
> 1 votes
Ended up going with something like this:

```
#include <RFduinoBLE.h>

// State properties.
int state = 1;
char command;
String hexstring;

// RGB pins.
int redPin = 2;
int grnPin = 3;
int bluPin = 4;

// Setup function to set RGB pins to OUTPUT pins.
void setup () {
  pinMode(redPin, OUTPUT);
  pinMode(grnPin, OUTPUT);
  pinMode(bluPin, OUTPUT);

  // This is the data we want to appear in the advertisement
  // (the deviceName length plus the advertisement length must be <= 18 bytes.
  RFduinoBLE.deviceName = "iOS";
  RFduinoBLE.advertisementInterval = MILLISECONDS(300);
  RFduinoBLE.txPowerLevel = -20;
  RFduinoBLE.advertisementData = "rgb";

  // Start the BLE stack.
  RFduinoBLE.begin();
}

void loop () {
  switch (command) {
    case 1:
      // Blink.
    break;
    case 2:
      // Fade.
    break;
  }

  //RFduino_ULPDelay(INFINITE);
}

// Converts HEX as a String to actual HEX values.
// This is needed to properly convert the ASCII value to the hex
// value of each character.
byte getVal (char c) {
  if (c >= '0' && c <= '9') return (byte)(c - '0');
  else return (byte)(c - 'a' + 10);
}

// Process each function/command.
void processCommand (int command, String hex) {
  switch (command) {
    case 'b':
      command = 1; // Set blink mode.
    break;
    case 'f':
      command = 2; // Set fade mode.
    break;
    case 'c':
      // We put together 2 characters as is
      // done with HEX notation and set the color.
      byte red = getVal(hex.charAt(1)) + (getVal(hex.charAt(0)) << 4);
      byte green = getVal(hex.charAt(3)) + (getVal(hex.charAt(2)) << 4);
      byte blue = getVal(hex.charAt(5)) + (getVal(hex.charAt(4)) << 4);

      // Set the color.
      setColor (red, green, blue);
    break;
  }
}

// Sets the color of each RGB pin.
void setColor (byte red, byte green, byte blue) {
  analogWrite(redPin, red);
  analogWrite(grnPin, green);
  analogWrite(bluPin, blue);
  delay(200);
}

// This function returns data from the radio.
void RFduinoBLE_onReceive (char *data, int len) {
  for (int i = 0; i < len; i++) {
    stateMachine(data[i]);
  }
}

// Main state machine function, which processes
// data depending on the bytes received.
void stateMachine (char data) {
  switch (state) {
    case 1:
      if (data == 1) {
        state = 2;
      }
    break;
    case 2:
      if (data == 'b' || data == 'f' || data == 'c') {
        command = data;
        hexstring = "";
        state = 3;
      } else if (data != 1) { // Stay in state 2 if we received another 0x01.
        state = 1;
      }
    break;
    case 3:
      if ((data >= 'a' && data <= 'z') || (data >= '0' && data <= '9')) {
        hexstring = hexstring + data;
        if (hexstring.length() == 6) {
          state = 4;
        }
      } else if (data == 1) {
        state = 2;
      } else {
        state = 1;
      }
    break;
    case 4:
      if (data == 3) {
        processCommand(command, hexstring);
        state = 1;
      } else if (data == 1) {
        state = 2;
      } else {
        state = 1;
      }
    break;
  }
}

```

---
Tags: led
---


# Question
Title: Can I use arduino and mobile phone screen to make a touch board?
I'm new to Arduino, I want to use Arduino and a mobile phone screen to make a simple touch board.

This phone screen I mean, is like this:

Can I connect it to Arduino, and when my fingers touch the screen, Arduino can get the events?

# Answer
First, find a suitable phone screen! Good luck. Most of the touch screens that I have found are resistive, and will never feel like an iPhone. Try googling "Arduino touch screen". Adafruit have a promising one.

Once you find your screen, you will need to interface to it. With luck it will come with a pre-built library. Otherwise you will be up for quite a lot of coding.
> 1 votes

---
Tags: events
---


# Question
Title: Zigbee Relay board communication with Arduino
I have bought this wireless ZigBee relay board.

I was wandering about an arduino sketch to get started, I have searched for 2 days now but with no results.

What I was thinking of is to have an Arduino with ZigBee module to send signal to another ZigBee device on top of the relay, to be able to open/close relay.

So, **can anyone share a sample sketch for that board?**

# Answer
Take a look at this library : https://code.google.com/p/xbee-arduino/

This is the XBee Library for Arduino, you will find simple sketch that are perfect bases for the application you're trying to do.
> 2 votes

---
Tags: arduino-uno, xbee
---


title: Processing Input

text:
# Question
Title: Processing Input
How to make an input from computer using processing (like a password form) and trigger pin in arduino? If you let some link to read more that would be very helpful.

# Answer
> 3 votes
On the processing side you need to communicate with the arduino using the Serial class. To set up use something like the following. It is a bit of guess work to find which of the serial ports to use

```
Serial myPort;
void setup() {
  // List all the available serial ports:
  println(Serial.list());

  // Open the port you are using at the rate you want:
  myPort = new Serial(this, Serial.list()[6], 9600);
  myPort.buffer(2); // sets the size of the buffer, I send two bytes at a time
}

```

You can read a write using the `Serial.read()` and `Serial.write()` see https://processing.org/reference/libraries/serial/index.html for the processing serial references.

# Answer
> 0 votes
You need to have a look at the Serial commands: http://arduino.cc/en/Serial/read

http://arduino.cc/en/Tutorial/ReadASCIIString

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


title: MMA7660 accelerometer with ATTiny85

text:
# Question
Title: MMA7660 accelerometer with ATTiny85
I'm trying to make the ATTiny85 work with the MMA7660 accelerometer, so far, without any success. Google search for "ATTiny85 MMA7660" gives poor results, and I'm not sure it has been done at all, at least publicly, so I thought I'll try my luck here.

What I've tried is using the TinyWireM library, in different combinations. The last one is based on the MMA7660 Arduino library, specially adjusted to the TinyWireM, and taken from this post in Arduino forums (direct link to download).

The SCL is connected to PB0 and SDA to PB2, with 5k ohm pull-ups (I know that the recommended is 4.7k but this is what I have available, and I assumed it shouldn't make much difference).

I am using the Arduino IDE v1.5.6, which works successfully with other non-I2C attiny projects I have.

As for the final code I am using the .pde example that comes with the MMA7660, altered to use SoftwareSerial:

```
#include <TinyWireM.h>
#include <MMA7660.h>
#include <SoftwareSerial.h>

SoftwareSerial mySerial(-1,4);

void setup()
{
  mySerial.begin(9600);
  MMA7660.init();
}

void loop()
{
  int x,y,z;
  delay(100); // There will be new values every 100ms
  MMA7660.getValues(&x,&y,&z);
  mySerial.print("x: ");
  mySerial.print(x);
  mySerial.print(" y: ");
  mySerial.print(y);
  mySerial.print(" z: ");
  mySerial.println(z);

}

```

The current problem with the above code is that the pointers just dump some memory without making any sense. If I try to see what TinyWireM.receive() command returns, values are 216 for all three variables. This is true even when I disconnect the MMA7660 from the prototyping board...! so I assume the problem is with the I2C itself, not working properly. The actual I2C address for the MMA (0x4C) and other relevant code is in MMA7660.cpp.

Any ideas?... Unfortunately I don't currently have another I2C device to examine the health of this protocol with my ATTiny85, so any experience you might have with this sort of configuration will be blessed.

**EDIT: I marked dvlabsllc's answer as accepted answer since it gave me the right direction to pinpoint the issue further down the library path. I have opened a new question regarding TinyWireM library here.**

# Answer
I have run into similar frustrations using standard libraries and I2C. I would have to look into the code and try it out on my own before confirming anything about this particular code; however, in the meantime you might want to try a tool such as I2cScanner that simply scans the I2C bus for all possible addresses and reports addresses that are "alive". This (or something similar as I am not sure if you are using Arduino API) might be a good start to just see if the I2C is working and that you have the correct address.
> 1 votes

---
Tags: attiny, accelerometer
---


title: Keyboard/mouse libraries with UNO

text:
# Question
Title: Keyboard/mouse libraries with UNO
I have an Arduino Uno Rev. 3 and I'm trying to make it so that the Arduino can send a key press / mouse action to the computer. However, these libraries are restricted to a few other versions of the board. Is there another alternative method to doing this without actually pressing any buttons/interacting with the arduino other than USB? Thanks! Link

# Answer
> 1 votes
It is actually possible, but not easy.

The main MCU on the Uno, the ATmega328, is not capable of using the USB connection at a low enough level to make this possible. The other MCU on the Uno R3, the ATmega16U2, is. You can reprogram it to act as almost any arbitrary USB device.

Since the '16U2 has no connection to digital pins 2 and up or to any of the analog pins, you would have to program it to communicate with the '328 (or an external chip) via UART, and then have another program running on the '328 that would communicate with the other pins.

Note that you will need an external programmer for this, since once the '16U2 is reprogrammed you will lose the ability to program the '328 until you restore the original programming. Using another board running ArduinoISP will work for this.

---
Tags: arduino-uno
---


title: Arduino/Arduino clone board suggestions

text:
# Question
Title: Arduino/Arduino clone board suggestions
I am planning to buy a Arduino board. I am also considering Arduino clones, too. My requirements are that the board should inbuilt communication modes like Ethernet, WiFi and a SD card slot, too. Also the board should have a decent amount of memory and the processor must be a a little more powerful than the Uno. The board must be capable of running a OS if possible!

I was looking at the Yun and Due. The Yun has all the communication modes but runs on a low end processor. The Due on the other hand runs on a ARM processor but has none of the communication modes. So now I am in a fix.

**Which board should I choose?**

# Answer
I would go with a Yun. Despite having a low end CPU, it runs at 400MHz and the disk space can be expanded using the uSD card (see this blog post).

If you don't plan to make CPU intensive tasks (such as real time video streaming and manipulation), the Yun is a nice tool. Otherwise, the Tre fits better (however, at the time of writing, it still has to be released).
> 2 votes

---
Tags: arduino-due, arduino-yun
---