title: Attiny85 with arduino as ISP

text:
# Question
Title: Attiny85 with arduino as ISP
After serveral attempts, I can't make my arduino UNO to program an attiny85, no matter what I do. I've tried under windows 7 and also under ubuntu 14.04, to no avail. I've followed instructions on hi low tech site and similar ones on arduino site. Even some youtube video. Nothing. The wiring of my arduino is as described in those sites, so it should be correct. I'm using the 10uF capacitor too.

This is the output running avrdude manually, extra verbose:

```
    zop@mikasa:~$ sudo /usr/share/arduino/hardware/tools/avrdude -C/usr/share/arduino/hardware/tools/avrdude.conf  -q -pattiny85 -cstk500v1 -P/dev/ttyACM0 -b19200 -Uflash:w:/tmp/build2861466093518309047.tmp/Fade.cpp.hex:i -v -v -v -v -v -v -v -v

    avrdude: Version 6.0.1, compiled on Oct 21 2013 at 15:55:32
             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/zop/.avrduderc"
             User configuration file does not exist or is not a regular file, skipping

             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: Send: 0 [30]   [20]
    avrdude: Recv: . [14]
    avrdude: Recv: . [10]
             AVR Part                      : ATtiny85
             Chip Erase delay              : 4500 us
             PAGEL                         : P00
             BS2                           : P00
             RESET disposition             : possible i/o
             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     6     4    0 no        512    4      0  4000  4500 0xff 0xff
                 Memory Ops:
                   Oeration     Inst Bit  Bit Type  Bitno  Value
                   -----------  --------  --------  -----  -----
                   READ               31     VALUE      7      1
                                      30     VALUE      6      0
                                      29     VALUE      5      1
                                      28     VALUE      4      0
                                      27     VALUE      3      0
                                      26     VALUE      2      0
                                      25     VALUE      1      0
                                      24     VALUE      0      0
                                      23     VALUE      7      0
                                      22     VALUE      6      0
                                      21     VALUE      5      0
                                      20    IGNORE      4      0
                                      19    IGNORE      3      0
                                      18    IGNORE      2      0
                                      17    IGNORE      1      0
                                      16   ADDRESS      8      0
                                      15   ADDRESS      7      0
                                      14   ADDRESS      6      0
                                      13   ADDRESS      5      0
                                      12   ADDRESS      4      0
                                      11   ADDRESS      3      0
                                      10   ADDRESS      2      0
                                       9   ADDRESS      1      0
                                       8   ADDRESS      0      0
                                       7    OUTPUT      7      0
                                       6    OUTPUT      6      0
                                       5    OUTPUT      5      0
                                       4    OUTPUT      4      0
                                       3    OUTPUT      3      0
                                       2    OUTPUT      2      0
                                       1    OUTPUT      1      0
                                       0    OUTPUT      0      0
                   WRITE              31     VALUE      7      1
                                      30     VALUE      6      1
                                      29     VALUE      5      0
                                      28     VALUE      4      0
                                      27     VALUE      3      0
                                      26     VALUE      2      0
                                      25     VALUE      1      0
                                      24     VALUE      0      0
                                      23     VALUE      7      0
                                      22     VALUE      6      0
                                      21     VALUE      5      0
                                      20    IGNORE      4      0
                                      19    IGNORE      3      0
                                      18    IGNORE      2      0
                                      17    IGNORE      1      0
                                      16   ADDRESS      8      0
                                      15   ADDRESS      7      0
                                      14   ADDRESS      6      0
                                      13   ADDRESS      5      0
                                      12   ADDRESS      4      0
                                      11   ADDRESS      3      0
                                      10   ADDRESS      2      0
                                       9   ADDRESS      1      0
                                       8   ADDRESS      0      0
                                       7     INPUT      7      0
                                       6     INPUT      6      0
                                       5     INPUT      5      0
                                       4     INPUT      4      0
                                       3     INPUT      3      0
                                       2     INPUT      2      0
                                       1     INPUT      1      0
                                       0     INPUT      0      0
                   LOADPAGE_LO        31     VALUE      7      1
                                      30     VALUE      6      1
                                      29     VALUE      5      0
                                      28     VALUE      4      0
                                      27     VALUE      3      0
                                      26     VALUE      2      0
                                      25     VALUE      1      0
                                      24     VALUE      0      1
                                      23     VALUE      7      0
                                      22     VALUE      6      0
                                      21     VALUE      5      0
                                      20     VALUE      4      0
                                      19     VALUE      3      0
                                      18     VALUE      2      0
                                      17     VALUE      1      0
                                      16     VALUE      0      0
                                      15     VALUE      7      0
                                      14     VALUE      6      0
                                      13     VALUE      5      0
                                      12     VALUE      4      0
                                      11     VALUE      3      0
                                      10     VALUE      2      0
                                       9   ADDRESS      1      0
                                       8   ADDRESS      0      0
                                       7     INPUT      7      0
                                       6     INPUT      6      0
                                       5     INPUT      5      0
                                       4     INPUT      4      0
                                       3     INPUT      3      0
                                       2     INPUT      2      0
                                       1     INPUT      1      0
                                       0     INPUT      0      0
                   WRITEPAGE          31     VALUE      7      1
                                      30     VALUE      6      1
                                      29     VALUE      5      0
                                      28     VALUE      4      0
                                      27     VALUE      3      0
                                      26     VALUE      2      0
                                      25     VALUE      1      1
                                      24     VALUE      0      0
                                      23     VALUE      7      0
                                      22     VALUE      6      0
                                      21    IGNORE      5      0
                                      20    IGNORE      4      0
                                      19    IGNORE      3      0
                                      18    IGNORE      2      0
                                      17    IGNORE      1      0
                                      16   ADDRESS      8      0
                                      15   ADDRESS      7      0
                                      14   ADDRESS      6      0
                                      13   ADDRESS      5      0
                                      12   ADDRESS      4      0
                                      11   ADDRESS      3      0
                                      10   ADDRESS      2      0
                                       9     VALUE      1      0
                                       8     VALUE      0      0
                                       7    IGNORE      7      0
                                       6    IGNORE      6      0
                                       5    IGNORE      5      0
                                       4    IGNORE      4      0
                                       3    IGNORE      3      0
                                       2    IGNORE      2      0
                                       1    IGNORE      1      0
                                       0    IGNORE      0      0
                                      Block Poll               Page                       Polled
               Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
               ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
               flash         65     6    32    0 yes      8192   64    128  4500  4500 0xff 0xff
                 Memory Ops:
                   Oeration     Inst Bit  Bit Type  Bitno  Value
                   -----------  --------  --------  -----  -----
                   READ_LO            31     VALUE      7      0
                                      30     VALUE      6      0
                                      29     VALUE      5      1
                                      28     VALUE      4      0
                                      27     VALUE      3      0
                                      26     VALUE      2      0
                                      25     VALUE      1      0
                                      24     VALUE      0      0
                                      23     VALUE      7      0
                                      22     VALUE      6      0
                                      21     VALUE      5      0
                                      20     VALUE      4      0
                                      19   ADDRESS     11      0
                                      18   ADDRESS     10      0
                                      17   ADDRESS      9      0
                                      16   ADDRESS      8      0
                                      15   ADDRESS      7      0
                                      14   ADDRESS      6      0
                                      13   ADDRESS      5      0
                                      12   ADDRESS      4      0
                                      11   ADDRESS      3      0
                                      10   ADDRESS      2      0
                                       9   ADDRESS      1      0
                                       8   ADDRESS      0      0
                                       7    OUTPUT      7      0
                                       6    OUTPUT      6      0
                                       5    OUTPUT      5      0
                                       4    OUTPUT      4      0
                                       3    OUTPUT      3      0
                                       2    OUTPUT      2      0
                                       1    OUTPUT      1      0
                                       0    OUTPUT      0      0
                   READ_HI            31     VALUE      7      0
                                      30     VALUE      6      0
                                      29     VALUE      5      1
                                      28     VALUE      4      0
                                      27     VALUE      3      1
                                      26     VALUE      2      0
                                      25     VALUE      1      0
                                      24     VALUE      0      0
                                      23     VALUE      7      0
                                      22     VALUE      6      0
                                      21     VALUE      5      0
                                      20     VALUE      4      0
                                      19   ADDRESS     11      0
                                      18   ADDRESS     10      0
                                      17   ADDRESS      9      0
                                      16   ADDRESS      8      0
                                      15   ADDRESS      7      0
                                      14   ADDRESS      6      0
                                      13   ADDRESS      5      0
                                      12   ADDRESS      4      0
                                      11   ADDRESS      3      0
                                      10   ADDRESS      2      0
                                       9   ADDRESS      1      0
                                       8   ADDRESS      0      0
                                       7    OUTPUT      7      0
                                       6    OUTPUT      6      0
                                       5    OUTPUT      5      0
                                       4    OUTPUT      4      0
                                       3    OUTPUT      3      0
                                       2    OUTPUT      2      0
                                       1    OUTPUT      1      0
                                       0    OUTPUT      0      0
                   LOADPAGE_LO        31     VALUE      7      0
                                      30     VALUE      6      1
                                      29     VALUE      5      0
                                      28     VALUE      4      0
                                      27     VALUE      3      0
                                      26     VALUE      2      0
                                      25     VALUE      1      0
                                      24     VALUE      0      0
                                      23     VALUE      7      0
                                      22     VALUE      6      0
                                      21     VALUE      5      0
                                      20    IGNORE      4      0
                                      19    IGNORE      3      0
                                      18    IGNORE      2      0
                                      17    IGNORE      1      0
                                      16    IGNORE      0      0
                                      15    IGNORE      7      0
                                      14    IGNORE      6      0
                                      13    IGNORE      5      0
                                      12   ADDRESS      4      0
                                      11   ADDRESS      3      0
                                      10   ADDRESS      2      0
                                       9   ADDRESS      1      0
                                       8   ADDRESS      0      0
                                       7     INPUT      7      0
                                       6     INPUT      6      0
                                       5     INPUT      5      0
                                       4     INPUT      4      0
                                       3     INPUT      3      0
                                       2     INPUT      2      0
                                       1     INPUT      1      0
                                       0     INPUT      0      0
                   LOADPAGE_HI        31     VALUE      7      0
                                      30     VALUE      6      1
                                      29     VALUE      5      0
                                      28     VALUE      4      0
                                      27     VALUE      3      1
                                      26     VALUE      2      0
                                      25     VALUE      1      0
                                      24     VALUE      0      0
                                      23     VALUE      7      0
                                      22     VALUE      6      0
                                      21     VALUE      5      0
                                      20    IGNORE      4      0
                                      19    IGNORE      3      0
                                      18    IGNORE      2      0
                                      17    IGNORE      1      0
                                      16    IGNORE      0      0
                                      15    IGNORE      7      0
                                      14    IGNORE      6      0
                                      13    IGNORE      5      0
                                      12   ADDRESS      4      0
                                      11   ADDRESS      3      0
                                      10   ADDRESS      2      0
                                       9   ADDRESS      1      0
                                       8   ADDRESS      0      0
                                       7     INPUT      7      0
                                       6     INPUT      6      0
                                       5     INPUT      5      0
                                       4     INPUT      4      0
                                       3     INPUT      3      0
                                       2     INPUT      2      0
                                       1     INPUT      1      0
                                       0     INPUT      0      0
                   WRITEPAGE          31     VALUE      7      0
                                      30     VALUE      6      1
                                      29     VALUE      5      0
                                      28     VALUE      4      0
                                      27     VALUE      3      1
                                      26     VALUE      2      1
                                      25     VALUE      1      0
                                      24     VALUE      0      0
                                      23     VALUE      7      0
                                      22     VALUE      6      0
                                      21     VALUE      5      0
                                      20     VALUE      4      0
                                      19   ADDRESS     11      0
                                      18   ADDRESS     10      0
                                      17   ADDRESS      9      0
                                      16   ADDRESS      8      0
                                      15   ADDRESS      7      0
                                      14   ADDRESS      6      0
                                      13   ADDRESS      5      0
                                      12    IGNORE      4      0
                                      11    IGNORE      3      0
                                      10    IGNORE      2      0
                                       9    IGNORE      1      0
                                       8    IGNORE      0      0
                                       7    IGNORE      7      0
                                       6    IGNORE      6      0
                                       5    IGNORE      5      0
                                       4    IGNORE      4      0
                                       3    IGNORE      3      0
                                       2    IGNORE      2      0
                                       1    IGNORE      1      0
                                       0    IGNORE      0      0
                                      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
                 Memory Ops:
                   Oeration     Inst Bit  Bit Type  Bitno  Value
                   -----------  --------  --------  -----  -----
                   READ               31     VALUE      7      0
                                      30     VALUE      6      0
                                      29     VALUE      5      1
                                      28     VALUE      4      1
                                      27     VALUE      3      0
                                      26     VALUE      2      0
                                      25     VALUE      1      0
                                      24     VALUE      0      0
                                      23     VALUE      7      0
                                      22     VALUE      6      0
                                      21     VALUE      5      0
                                      20    IGNORE      4      0
                                      19    IGNORE      3      0
                                      18    IGNORE      2      0
                                      17    IGNORE      1      0
                                      16    IGNORE      0      0
                                      15    IGNORE      7      0
                                      14    IGNORE      6      0
                                      13    IGNORE      5      0
                                      12    IGNORE      4      0
                                      11    IGNORE      3      0
                                      10    IGNORE      2      0
                                       9   ADDRESS      1      0
                                       8   ADDRESS      0      0
                                       7    OUTPUT      7      0
                                       6    OUTPUT      6      0
                                       5    OUTPUT      5      0
                                       4    OUTPUT      4      0
                                       3    OUTPUT      3      0
                                       2    OUTPUT      2      0
                                       1    OUTPUT      1      0
                                       0    OUTPUT      0      0
                                      Block

             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] . [14] . [00] . [00] . [01] . [01] . [01] . [01] . [03] . [ff] . [ff] . [ff] . [ff] . [00] @ [40] . [02] . [00] . [00] . [00]   [20] . [00]   [20]
    avrdude: Recv: . [14]
    avrdude: Recv: . [10]
    avrdude: PAGEL and BS2 signals not defined in the configuration file for part ATtiny85, using dummy values
    avrdude: Send: E [45] . [05] . [04] . [d7] . [a0] . [01]   [20]
    avrdude: Recv: . [14]
    avrdude: Recv: . [10]
    avrdude: Send: P [50]   [20]
    avrdude: ser_recv(): programmer is not responding
    avrdude: stk500_recv(): programmer is not responding
zop@mikasa:~$

```

I don't know what else to try, so suggestions are very welcome.

Thanks.

PS: I had to strip out some of the output text because it was bigger than 30000 chars, I hope the info is good enough.

# Answer
Your log demonstrates that

* Your programmer settings were correct.
* You have the right sketch loaded on the Arduino
* You have the Arduino auto-reset properly disabled.

The failure occurs at the point at which you're trying to enter programming mode. The two most likely error sources are:

* Your ATtiny85 is not wired up correctly (e.g. you misidentified pin 5 as pin 1, you used a wrong pin on the Arduino, you crossed two signals, etc).
* Your ATtiny85 is in a mode that prevents ISP reprogramming (programming the `RSTDIBL` fuse is the toughest of these mode, but merely setting the clock source to something odd will also cause this). Does your chip have a past, or is it fresh out of the box?
> 3 votes

# Answer
I spent days with exactly the same problem (well, trying to program a 328p). Then I purchased a USBISP (aka USBICSP), and all my problems went away. I got one which had a "program slowly" jumper - setting this jumper will do the equivalent of -b19200, but without needing to explicitly set it, so you can do it from the Arduino IDE. Just my 2c worth.
> 0 votes

---
Tags: arduino-uno, attiny, isp
---


# Question
Title: How can I filter out noise from ADC lines without delay or signal change?
I'm working on a project with a joystick and I'm trying to keep everything a simple and low latency as possible. I am reading the pots with the onboard 10bit ADC on the ATmega 32u4 but may be upgrading to either a 16bit ADC or 24 bit ADC. **How can I filter noise out of the signals?**

# Answer
The Atmel ATmega328 datasheet, section 24.6.1, recommends that you drive the analog input pin with an output impedance of 10 KOhm or less. Also, it recommends that you remove high-frequency components with a low-pass filter. (That low-pass is sometimes called an antialiasing filter).

The simplest possible low-pass filter is a resistor and a capacitor.

```
  +5V                        +5V
   |                          |
(sensor)---resistor---+---(Arduino)
   |                  |          |
   |            capacitor        |
   |                  |          |
  GND----------------GND--------GND

```

Contrary to popular belief, it is not possible to make an antialiasing filter in software.

For an initial low-resolution prototype, a quick rule of thumb is to pick the RC time constant at least 10 times as long as the time between samples.

So if you are sampling at around 1000 Samples/second (i.e., a sampling interval of 1 millisecond), then 100 Ohms of resistance and (roughly) 100 uF ceramic capacitor may be adequate. (The RC time constant here is RC == 100 Ohms x 100 uF = 10 milliseconds).

Many joysticks already have a relatively high output impedance; you'll need to use a resistor with that much less resistance to compensate. (Sometimes you don't need any additional resistance; but you still need that capacitor between the Arduino analog input pin and the Arduino ground pin). (Many sensors have an output impedance more than 10 KOhm; people who use them are pretty much forced to use an op-amp chip to get clean signals).

Entire books have been written on signal filtering. In addition, there are many other techniques for getting higher resolution analog signals, higher speed data collection, and trading off between them -- but they are probably overkill for reading the position of a joystick.
> 5 votes

# Answer
One possible approach is to go for a completely software side solution.

Microsmooth is a signal processing library that I am working on that is specifically intended for low latency, low memory signal smoothing. It is still in development, but even now, most of the filters work in less than 100 microseconds per call while giving fairly good accuracy and smoothing. Also, the header file allows for simple configuration for certain filter parameters.
> 2 votes

# Answer
The noise from your joystick pots will drown out any resolution over eight bits regardless. They were designed for the very crude game port on a pc and use a copper wiper on a slab of carbon. Not a terrible recipe for a noise generator.
> -1 votes

---
Tags: pins, arduino-leonardo, signal-processing
---


# Question
Title: Powering LCD Displays without a Breadboard
I hope that this is not a silly question. I may be hoplelessly optimistic in asking, but is there any way to power & display information onto a LCD Display from an Arduino Uno.... Without the breadboard? I am working on a hardware project that has very strict space constraints, and the breadboard is simply not an option.

# Answer
> 2 votes
I presume you're looking at this page \- the breadboard is merely a convenience, you can just hard-wire the LCD directly - most don't even come with that header plug soldered on.

---
Tags: lcd, hardware, wires
---


# Question
Title: Error while sending message using gsm sim900a module interfaced with arduino uno
The code used for interfacing the gsm module with arduino for sending a message is as follows :-

```
#include <GSM.h>

#define PINNUMBER ""

// initialize the library instance
GSM gsmAccess; // include a 'true' parameter for debug enabled
GSM_SMS sms;

// char array of the telephone number to send SMS
// change the number 1-212-555-1212 to a number
// you have access to
char remoteNumber[20]= "12125551212";

// char array of the message
char txtMsg[200]="Test";

void setup()
{
  // initialize serial communications
  Serial.begin(9600);

  Serial.println("SMS Messages Sender");

  // connection state
  boolean notConnected = true;

  // Start GSM shield
  // If your SIM has PIN, pass it as a parameter of begin() in quotes
  while(notConnected)
  {
    if(gsmAccess.begin(PINNUMBER)==GSM_READY)
      notConnected = false;
    else
    {
      Serial.println("Not connected");
      delay(1000);
    }
  }
  Serial.println("GSM initialized");
  sendSMS();
}

void loop()
{
// nothing to see here
}

void sendSMS(){

  Serial.print("Message to mobile number: ");
  Serial.println(remoteNumber);

  // sms text
  Serial.println("SENDING");
  Serial.println();
  Serial.println("Message:");
  Serial.println(txtMsg);

  // send the message
  sms.beginSMS(remoteNumber);
  sms.print(txtMsg);
  sms.endSMS();
  Serial.println("\nCOMPLETE!\n");
}

```

the error is found on the 3rd line GSM\_SMS sms; as GSM\_SMS is not a name type. what point am i missing here...??

thank you in advance.

# Answer
Update your IDE software. You need IDE 1.0.4 or later. I copied your code into my 1.0.5 IDE and compiled it without any error. So it is most probably your version of the Arduino IDE.
> 1 votes

---
Tags: arduino-uno, gsm
---


title: Stepper motor clock

text:
# Question
Title: Stepper motor clock
I am currently using an Adafruit motor shield on my arduino uno for the first time. The idea is turning the stepper motor with basicly 1RPM. But i just cant do it.

This is the first time working with this setup, and i dont know what to do. Can you people help me?

i'm using the Arduino Uno with ADAFRUIT motorshield. The steppermotor is 48steps / rev DATASHEET

The code i have at the moment:

```
#include <AFMotor.h>

AF_Stepper motor(48, 1);

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

  motor.setSpeed(1);

  motor.step(48, FORWARD, DOUBLE);
  motor.release();
  delay(10);
}

void loop () {
  motor.step(48, FORWARD, DOUBLE);
}

```

Greetings from Holland.

# Answer
If the stepper gives you 48 steps and an hour has 60, you need to provide 1,25 rounds in one hour given you only move the minute hand. Then with some gearing you should be able to move the hour hand every round there.

So the best way to do this is to is either to move the hand once and then delay 1 minute, 1 minute = 60 seconds **x** 1000 milliseconds.

You then need to figure out what it requires of the stepper motor to make 1 step, with some stepper motors you need to move forward 1 cycle and then back a half. to make a step. You should find all this in the documentation.

Please provide feedback in the comments below so we can improve the answer.
> 0 votes

# Answer
Unsure what you need help with, but this might help:

I believe that the 28BYJ-48 has a lot more steps per rotation, around 4000 I think. I had a few problems myself getting this to work. It also has four steps to cycle through, not 2.

Take a look at this library which has the 28BYJ-48 set to default. CustomStepper
> 0 votes

---
Tags: c++, motor, hardware, stepper
---


title: Code for four road junction

text:
# Question
Title: Code for four road junction
This is the Arduino code for a four road junction. In the below code, the `if` case must be tested after every road without delay. Can any one guide me?

```
int redLed1 = 7;
int yellowLed1 = 6;
int greenLed1 = 5;
int redLed2 = 4;
int yellowLed2 = 3;
int greenLed2 = 2;
int redLed3 =8 ;
int yellowLed3 =9;
int greenLed3 =10;
int redLed4 = 14;
int yellowLed4 = 15;
int greenLed4 =16;
int THRESHOLD=700;
int soundvalue=0;
void setup()
{
    pinMode(redLed1, OUTPUT);
    pinMode(yellowLed1, OUTPUT);
    pinMode(greenLed1, OUTPUT);
    pinMode(redLed2, OUTPUT);
    pinMode(yellowLed2, OUTPUT);
    pinMode(greenLed2, OUTPUT);
    pinMode(redLed3, OUTPUT);
    pinMode(yellowLed3, OUTPUT);
    pinMode(greenLed3, OUTPUT);
    pinMode(redLed4, OUTPUT);
    pinMode(yellowLed4, OUTPUT);
    pinMode(greenLed4, OUTPUT);
}

void loop()
{
    digitalWrite(redLed2,HIGH);
    digitalWrite(redLed3,HIGH);
    digitalWrite(redLed4,HIGH);
    digitalWrite(redLed1,HIGH);
    digitalWrite(yellowLed1,HIGH);
    delay(5000);
    digitalWrite(redLed1,LOW);
    digitalWrite(yellowLed1,LOW);
    digitalWrite(greenLed1,HIGH);
    if(analogRead(A0)>=THRESHOLD)
    {
        digitalWrite(greenLed2,LOW);
        digitalWrite(greenLed1,HIGH);
        delay(10000);
        digitalWrite(greenLed1,LOW);
    }
    delay(30000);
    digitalWrite(greenLed1,LOW);
    digitalWrite(redLed1,HIGH);
    digitalWrite(yellowLed2,HIGH);
    delay(5000);
    digitalWrite(redLed2,LOW);
    digitalWrite(yellowLed2,LOW);
    digitalWrite(greenLed2,HIGH);

    delay(30000);
    digitalWrite(greenLed2,LOW);
    digitalWrite(redLed2,HIGH);
    digitalWrite(yellowLed3,HIGH);
    delay(5000);
    digitalWrite(redLed3,LOW);
    digitalWrite(yellowLed3,LOW);
    digitalWrite(greenLed3,HIGH);

    delay(30000);
    digitalWrite(greenLed3,LOW);
    digitalWrite(redLed3,HIGH);
    digitalWrite(yellowLed4,HIGH);
    delay(5000);
    digitalWrite(redLed4,LOW);
    digitalWrite(yellowLed4,LOW);
    digitalWrite(greenLed4,HIGH);
    delay(30000);
    digitalWrite(greenled4,LOW);

    }
}

```

# Answer
I'm not sure what a “road” condition is, so I don't know where the “after every road” points in your code are located. However, you can write a properly-parameterized function to do tests, or a subroutine to do tests and perform actions. Then place a function or subroutine call whereever you need to perform the test.

Note, the first 14 lines of your code (which define 14 variables that you probably should have defined as constants) could be replaced by an `enum` statement (which defines integer constants) like

```
enum { redLed1=7, yellowLed1=6, greenLed1=5, redLed2=4, yellowLed2=3, greenLed2=2, redLed3=8, yellowLed3=9, greenLed3=10, redLed4=14, yellowLed4=15, greenLed4=16, THRESHOLD=700, soundvalue=0 };

```

or (because `enum` will advance by 1 unit when a value isn't specified) you could say

```
enum { greenLed2=2, yellowLed2, redLed2, greenLed1, yellowLed1, redLed1, redLed3, yellowLed3, greenLed3, redLed4=14, yellowLed4, greenLed4, THRESHOLD=700, soundvalue=0 };

```

For a short sketch like this, the compiler can detect that some of your variables actually are constants, but in general using constants as constants and variables as variables will produce smaller and safer code.
> 1 votes

# Answer
NOTE: all the code below is thrown together; it is there to show you what to do. It will probably require some fixing before it works. The intent should be clear.

From what I read in your code, mostly what you are doing is setting the traffic lights in particular combinations, several times over, with delays in between.

In general, any time you do the same thing, conceptually, several times, it should either be in a loop, or in a function.

In this case, the first thing that (to me) looks like it belongs in a function is: `set all the lights in a particular pattern, and wait for a while`. I would call this function something like `set_lights_and_delay` (or, perhaps `setLightsAndDelay` depending on your coding style). It would take 5 parameters: the state of each light (red, green, or yellow/red, which I would just call yellow), and the time to delay (which may be 0). In this function, you would set ALL the pins, high or low, as appropriate (since your function shouldn't assume the previous state), then delay the appropriate amount of time.

```
enum colors {yellow, red, green, yellowred};

void loop()
{
    set_lights_and_delay(yellow,red,red,red,5000);
    if(analogRead(A0)>=THRESHOLD)
    {
      set_lights_and_delay(green,red,red,red,40000);
    } else {
      set_lights_and_delay(green,red,red,yellowred,30000);
    }

```

... and so forth (or whatever light combinations you want).

Now, how would you write this function? This function does the same thing for each light, so it sounds to me like you would want to make a function that takes a color, and the 3 pins to use:

```
void setLightsAndDelay(color northlight, eastlight, westlight, southlight; int delaytime)
{
    setOneLight(northlight, redLed1, yellowLed1, greenLed1);
    setOneLight(eastlight, redLed2, yellowLed2, greenLed2);
    setOneLight(westlight, redLed3, yellowLed3, greenLed3);
    setOneLight(southlight, redLed4, yellowLed4, greenLed4);
    delay(delaytime);
}

```

Now, setOneLight is pretty simple to write:

```
void setOneLight(color thisLight; int redled, yellowled, greenled)
{
    if (thisLight==green) // always do the easiest one first.
    {
        digitalWrite(greenled,HIGH);
    } else {
        digitalWrite(greenled,LOW);
    }

    if (thisLight==yellow) || (thislight==yellowred)
    {
        digitalWrite(yellowled,HIGH);
    } else {
        digitalWrite(yellowled,LOW);
    }

    if (thisLight==red) || (thisLight==yellowred)
    {
        digitalWrite(redled,HIGH);
    } else {
        digitalWrite(redled,LOW);
    }
}

```

In practice, there would be a lot of other things I'd do: I'd put all the things I know about a single traffic light into a struct; this means I could pass the struct to a function, in one go. I'd put the four traffic lights in an array; this means I could go through them in a loop, rather than calling the same function 4 times individually (great when your city ends up with 1,000 traffic lights!). I would probably put the pattern of lights (green/30000, yellow/10000, red/30000, yellowred/10000) into an array (made a little more difficult by the sensor).
> 1 votes

---
Tags: arduino-mega
---


# Question
Title: Using both TMRpcm and VirtualWire libs with ATmega328, despite the conflict on TIMER1
I wanted to use both TMRpcm and VirtualWire with ATmega328 in an Arduino-like board I'm making, but both libraries use TIMER1. I wanted to use each lib for the following purposes:

* TMRpcm: play a WAV sound from an SD Card;
* VirtualWire: to receive commands from an RF remote control.

TMRpcm Advanced Features Wiki has a section on how to use TIMER2 instead, but I couldn't get it to work. They also say:

> Notes:
>
> 1. This is usually not the best solution.

So, before I spend any more time on this, I would like to hear what you guys have to say.

So, my question is: **is there a workaround to solve this conflict on the use of TIMER1, so I can use both libs in my project?**

If not, **what other alternatives do I have?**

My circuits for reading the SD card and driving the speaker are similar to the schematic in this Instructable: Playing Wave file using Arduino. And I'm using one of those 433MHz Receiver modules for the RF part (standard, working circuit).

Both features, the RF receiver and SD card WAV playing, work correctly, when run separately (with separate sketches).

# Answer
> 0 votes
I ended up working around the issue by building a board with two ATmegas in it. One MCU handles the sound while the other handles the RF receiver, each using its own TIMER1, both communicating via I2C.

It's kind of a low tech dual core controller board. Not the most efficient solution, but it worked great for me.

# Answer
> 2 votes
You could edit the VirtualWire.cpp source to use Timer2 instead of Timer1. For VirtualWire 1.18 the relevant section starts on line 512 with `#else // ARDUINO`.

On line 515 change `(uint16_t)-1` to `(uint8_t)-1` since Timer2 is only 8 bit. Then change all the TCCR1A, TCCR1B, OCR1A, TIMSK1 and OCIE1A to their Timer2 equivalent (hint: swap the 1's for 2's). Line 533 should be the last. On line 778 you also need to make a change to use TIMER2\_COMPA\_vect for VW\_TIMER\_VECTOR.

I hope that it helps.

# Answer
> 1 votes
the virtual wire library has been obsoleted, and you should now use the RadioHead library. In this RadioHead Library, you can edit the RH\_ASK.cpp file, and uncomment the #define RH\_ASK\_ARDUINO\_USE\_TIMER2 near the top.

---
Tags: timers, sd-card, virtualwire, tmrpcm
---


# Question
Title: How to return a message when calling by a TCP connection?
I am working on a communication between Android and Arduino board.

The Android makes a TCP connection with the board and successfully sends some strings to the board.

The problem is, there is an int in my Arduino code (e.g. `int distance`) and I would like to pass that back to my Android device.

I have handled the Android side already, but I do not know how to return a message from Arduino.

```
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

                //in this while the client listens for the messages sent by the server
                while (mRun) {
                    serverMessage = in.readLine();

                    if (serverMessage != null && mMessageListener != null) {
                        //call the method messageReceived from MyActivity class
                        mMessageListener.messageReceived(serverMessage);
                    }
                    serverMessage = null;

                }

```

This is the Android side code but I think that it is not a specific Android problem, there should be some way for Arduino to make a response of an integer variable (without concern what is the source device)?

What I should do in Arduino for making that response?

# Answer
I'm assuming that you are using an Ethernet shield, as nothing about this is stated. But solution is really similar between many network solution.

Once a TCP connection has been established, it can be used like you would use the Serial;

you'll probably end up having something similar to:

```
EthernetClient client = server.available(); //accept a new connection
if (client) { //if valid connection
  client.print(distanceValue);
  client.close(); //close connection
}

```

look at the official API reference for a more detailed list of available command.
> 1 votes

---
Tags: arduino-uno, programming, string, networking, tcpip
---


# Question
Title: How to accept user input (array, variables,...)
I am working on a project using my Arduino mega2560 that triggers a solenoid (maximum of three solenoids), my camera and my flash (maximum of two flashes). The core routine is there, and working.

Now I want to refine this by adding a menu and 16x2 LCD with 6 buttons (up/down/left/right/select/reset). This is meant to be so the user can change the default values for:
\- the amount of solenoids to be used (max 3),
\- the amount of drops per solenoid (max 3),
\- the time between drops and
\- the time between active solenoids.
The layout of the menu is there, but not yet coded.

My default values for solenoids used, droplet size, droplet timing, solenoid timing, camera delay and flash(es) delay(s) are put in an array. Through the menu the default values will be presented to the user. He can accept (select button) or change the value within certain limits using the up/down buttons.

The question is, what is an easy (for a beginner like me) to program way to accept user input and store this in the array, overwriting the presented default value? I also would like to have the possibility for the user to back out of a menu option and leave the default setting of the specific submenu value.

I was thinking of creating a shadow array with blanks, to be filled in by the user and copy all the values to the array that will be used by the core routine. Another line of thinking leads me to just abandoning the array and making use of a bunch of variables. As you will probably see, I need some advice here.

Thanks very much for reading and your advice, happy to answer questions that may help clarify the issue.

Regards, Kiezel

# Answer
Your hardware side for the user to use can be based on an ADC type keypad pictured below, this only uses one pin and is pretty reliable. Note that not all code is given or design as it would be useless for learning and I also put effort into the code this came from, logic helps with the rest of each part...

The code is pretty simple:

You would write a function like so~

```
char keypad(int in){

if(in < 949){
    if(in > 935){
        return 's'; //select
    }
}

//......

else return = 0;
}

```

Next would be the code for the menu, you could hold the default values in an array and then modify them in the code, with set positions for defaults, considering

> My default values for solenoids used, droplet size, droplet timing, solenoid timing, camera delay and flash(es) delay(s) are put in an array.

***Example from one of my projects***

```
//Menu levels
#define level0 0
#define level1 1
#define level2 2
//master level of current point
#define mlevel 6
#define msub_level 7
//\\\\\\\\\\\\\\\\\\\\
#define sub_level1 0
#define sub_level2 1
#define sub_level3 2
#define sub_level4 3
#define sub_level5 4
// default level on boot
uint8_t current_level = mlevel;

```

Next would be to push the data to

```
int navigate(char key){
if(key == 'u'){
        if(current_level == mlevel){
        if(count == 3){ //roll-over

            count = 0;
            //update LCD....
        }
        else count++;
        //update LCD....
    }

    if(current_level == msub_level){

        if(count == 5){//roll-over

            count = 0;
            //update LCD....
        }
        else count++;
        //update LCD....
    }
}

//..... other ones here

    return count;
}

```

You would use the returned count to find the relative place in your array. e.g:

`int default[n] ={x,y,z,...};`

> get the key \> put into `navigate()` \> put into dafault\[`count`\];

You would also change the default after

* It has been changed or,
* The key has been debounced, i.e. use logic to determine if the key has changed state or,
* The user has chosen 'accept'

Update of the LCD can be done at the points you want it done
> 1 votes

---
Tags: arduino-mega, lcd, variables
---


# Question
Title: Storing data (strings) if ethernet fails to send it
Flow goes something like:

Read sensors Send data If send fails store the data in eeprom/flash/sd If sent check if any previous ones have failed and send those

So my question is what's the best storage option to save the data? Is there an easy way to save strings or am I going to have to write it byte by byte?

# Answer
> 1 votes
In my opinion SD would be the best way because it is cheap, small, relatively fast and easily portable on a PC, using FAT (but it uses a lot of resources) or even raw; but then you have to use some more trick to get to the raw data from a OS, its not just "plug n read".

The SD library uses FAT under the hood, and it gives you a nice and easy interface. Just remember that SD works at 3.3V, and connecting them directly to arduino will break them fast, even if often not immediately.

# Answer
> 0 votes
Other than SD (see @lesto's answer), you can also store the data locally on your Arduino's EEPROM. You can store a byte at a time. The amount of storage varies from chip to chip, the AtMega328p that powers Arduino UNOs has 1kb. The eeprom is persistent over resets, I suspect not if you're reprogramming it, so think how you're going to get the data off before you start storing valuable info.

At 1kb, size is at a premium, so you probably don't want to use text strings, just the raw data. Remember that, if your chip resets, you will lose any memory variables with info about e.g. where you're up to. I would probably include some sort of checksum of each record, to test if the data is yours or not. I would include a counter or timestamp, so when you are starting up, you can read all memory to find the newest (valid) record; the next record is one greater, and at the next memory address. When you get to the end of the memory, restart at 0. If you store a one-byte counter, a one byte checksum, and 2 bytes of data, you can store 256 records. You could mark records off as you send them, or keep a counter in memory of which ones you have already sent - if your chip is reset, it may resend old records (very rarely), which your server would need then need to handle.

If using eeprom, try to spread your writes - you get a certain number of writes PER MEMORY LOCATION, so if you always write to address 15, then 15 will wear out before the others. I think I saw a reference to "100,000 writes", but am unable to find that now to confirm. 100,000 writes at 1 write per second to the same address will have your eeprom fail after about 27 hours; 4 writes per second spread over 1K will cause a fail after about 10 months.

Test what happens when you write past the end of memory - some possible scenarios include failed write, write to a different location (e.g. trying to write to address 1024+1 will write to address 1024), not writing at all and reading it back will return 0, 255, or another number (consistent or otherwise)

See http://arduino.cc/en/Reference/EEPROM on how to write to eeprom.

To find out how many bytes of memory your EEPROM has, use E2END. Addresses run from 0 to E2END, so E2END might be 1023 (0 to 1023=1024 bytes).

---
Tags: ethernet, flash, eeprom
---


title: How do I get an accurate time?

text:
# Question
Title: How do I get an accurate time?
I've made a clock using an Arduino, but the time seems to drift. I am aware of the rollover issue; the clock seems to drift by about 15 minutes over the course of a week.

I'm using a custom PCB with this resonator from Digi-key. The code reads the millis() function at the beginning of each loop, and works from that value.

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

# Answer
*Note: although my answer was accepted and has a higher vote score, make sure you read Edgar Bonet's great answer on how to make your Arduino keep time without an RTC.*

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

Below are some of its features:

* It uses IC interface for communication with Arduino, making it easy to program using the right libraries (available on the Net).
* It is connected to Arduino through the SCL and SDA pins (analog A4 and A5 respectively), thus only using 2 pins.
* It requires very little external components to run.
* IT can be connected to a coin cell battery so it will keep time even while the Arduino is turned off. In its low power mode, the coin cell battery lasts for years.
* It drifts very little (in my case it only drifts a few seconds per week).
* It's not very expensive.

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

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

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

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

1. Get a 32768 Hz watch crystal: either buy it or disassemble an old clock. These crystals, specifically designed for time keeping, have an *extremely* small temperature drift. You would also need one of those if you wanted to use an RTC chip.
2. Configure the fuses of your ATmega to run off the 8 MHz RC oscillator. This will make your `millis()` function horribly inaccurate, and also free the XTAL1 and XTAL2 pins.
3. Connect the watch crystal to the TOSC1 and TOSC2 pins. These are the same pins as XTAL1 and XTAL2 (9 and 10 on the 328P). The different names are used to mean different functions.
4. Configure the Timer/Counter 2 for asynchronous operation, normal counting mode, prescaler set to 128, and enable the timer overflow interrupt.

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

I did exactly this to build my 24-hour one handed wall clock. This link points now to the English translation of the original documentation in French.

## Quartz calibration

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

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

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

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

ISR(TIMER2_OVF_vect)
{
    static uint32_t unaccounted_time;

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

```

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

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

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

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

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

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

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

---
Tags: time, millis
---


title: delayMicroseconds- error?

text:
# Question
Title: delayMicroseconds- error?
running a very short program on a mega, just to generate a 8 microsecond wide clock pulse on pin 18, every 250 microseconds- closest 'delay' values I can get are delayMicroseconds(3), and (83) off, gives a 7.5 microsecond wide pulse every 249 microseconds- any suggestions on a better way?

here is whats running:

```
int i=0;
int req=18;

void setup(){
Serial.begin(115200);
 DDRD = DDRD | B10000010;
 interrupts();
pinMode(req,OUTPUT);
}

void loop(){
i=1;
digitalWrite(req, HIGH);
delayMicroseconds(3); //gives 7.5 microsecond pulse?
digitalWrite(req, LOW);

while(i<83){//gives 249 microseconds start of pulse to start of next pulse?
 delayMicroseconds(1);
 i=(i+1);}
 }

```

# Answer
This a very partial answer. I do not know your requirements, whether or not PWM can do the job, etc... I just wanted to point out that you can make a pulse exactly 8 µs long with this:

```
#include <util/delay.h>
#include <util/atomic.h>

// Pulse PD3 (digital 18 on Mega 2560)
// for exactly 8 us (128 clock cycles @ 16 MHz)
static void pulse() {
    ATOMIC_BLOCK(ATOMIC_RESTORESTATE) {
        PORTD |= 1 << 3;
        _delay_us(8 - 0.125);
        PORTD &= ~(1 << 3);
    }
}

```

The `_delay_us()` function from avr-libc is actually cycle-accurate inline assembly. The 0.125 µs I subtracted is the time needed by the actual port writes: both the sbi and cbi instructions take two cycles (0.125 µs), but that delay should only be counted once. `digitalWrite()` should always be avoided in time-critical code.

The 242 µs delay between pulses would be harder to generate without PWM. A timer interrupt at 4 kHz seems like the simplest option, but it is not cycle-accurate.

**Edit**: here is the scope trace, showing a quite accurate timing:
> 2 votes

# Answer
Unless you want program PWM timer as suggested in comment then for short delays you need calculate how many instruction cycles are needed to make such a delay based on clock/crystal frequency and make that delay in inline assembler to have code under control. To manipulate digital output use writing data to PINx (which is equal to xoring PORTx).

To satisfy exact 250ms you need compensate errors because of rounding. Arduino's delay/tick functions do it. For the long delays you need a simple scheduler not to spend all the CPU time for pulse generating.
> 1 votes

---
Tags: arduino-mega
---


title: Arduino ADC read bad value

text:
# Question
Title: Arduino ADC read bad value
I have an Arduino device and I'm trying to read two voltages. The first one is the Arduino Vcc by using the bandgap value 1.1V (this requires raw access to registers since it's not implemented in analogRead). The other one is checking the battery voltage using the badgap as a reference. I want both of them because I'm doing a study on the battery life when using a step-up converter.

I'm using these pieces of code:

```
// Read bandgap with Vcc as reference - this will give use the Vcc
ADMUX = DEFAULT << 6 | 14;
delayMicroseconds(250);
bitSet(ADCSRA, ADSC);
while(bit_is_set(ADCSRA, ADSC))
    ;
word x = ADC;
Serial.println(x);

// Read A1 with 1.1V bandgap as reference - this will give battery voltage
ADMUX = INTERNAL << 6 | 1;
delayMicroseconds(250);
bitSet(ADCSRA, ADSC);
while(bit_is_set(ADCSRA, ADSC))
    ;
word x = ADC;
Serial.println(x);

```

The problem that I have is that separately they seem to work well, however when using them together the first piece of code ruins the reading for the second one. The culprit is the line `ADMUX = DEFAULT << 6 | 14`. This sets up the default reference (chip voltage) and reads channel 14 (which is the 1.1V). I can't figure out why after using this line changing back with `ADMUX = INTERNAL << 6 | 1` doesn't work.

# Answer
The datasheet says:

> The first ADC conversion result after switching reference voltage source may be inaccurate, and the user is advised to discard this result.

Then you could try to take each reading twice, looping over four ADC readings:

1. Read bandgap with Vcc as reference, discard the value.
2. Re-take the same, keep the value.
3. Read A1 with 1.1V bandgap as reference, discard the value.
4. Re-take the same, keep the value.
> 3 votes

---
Tags: voltage-level, analogread, battery
---


# Question
Title: How to fix error line number offset in Sublime Text when compiling for Arduino
When compiling for Arduino via the Stino plugin line numbers are not represented correctly in the output. For example, I have an error on line 117 however the output is: `sketch_name.ino.cpp:136:1: error:`

# Answer
> 1 votes
The `#line` preprocessor directive is used to tell GCC both what the next line should be numbered as and what filename should be reported, and the plugin is not generating them properly. This is therefore a Stino bug.

---
Tags: debugging, gcc
---


# Question
Title: Continuous servo not setting speed correctly
I have two continuous servos connected to my Uno, and I'm running this code on it:

```
leftServo.write(91);
rightServo.write(102);
delay(3000);

leftServo.write(112);
rightServo.write(81);
delay(3000);

leftServo.write(91);
rightServo.write(102);
delay(3000);

int i;
while(1) {
  i++;
}

```

When I run the code, the wheels stop for three seconds (91 and 102 are the zero values for these servos) then they spin for three seconds, then the left servo stops, but the right one only slows down about half way, it doesn't stop, even though the exact same number is used as before.

I can't figure out why this is?

# Answer
Issue was fixed by adding a delay of 100ms between servo writes, smaller values may work, but I haven't tried yet
> 2 votes

---
Tags: arduino-uno, continuous-servo
---


title: arduino - millis()

text:
# Question
Title: arduino - millis()
Copied from the Arduino reference - millis()

> ***Tip****: Note that the parameter for millis is an unsigned long, errors may be generated if a programmer tries to do math with other datatypes such as ints.*

What kind of math? What kind of other type of processing is excluded while working with millis?

Could someone clarify this statement and/or give some example?

# Answer
> 8 votes
Whenever you write an equation in C/C++, the data types being operated on have a very real effect on the equation's output.

Each type like `int`, `float`, and `unsigned long` have different behaviors, and take a certain amount of space in memory to store.

`int` (on arduino) is store in 16 bits, with half of its values being given to negative numbers, half-1 given to positive values, and one value given to 0. That gives it a range of -2^15 (-32,768) to +2^15-1 (32,767).

`unsigned long` (on arduino) is 32 bits, but none are designated as negative. its range is then 0 to 2^32-1 (4294967295).

> What kind of math? What kind of other type of processing is excluded while working with millis?

The crux of the issue is that it the time millis returns ever got past 32767 and you tried to store it in an int, the arduino couldn't do it, because an `int` can't hold that big of a number. The type of math this is off limits is math happening to smaller data types, not any specific operations. Maybe these examples will help:

```
  int i = 32767;
  Serial.println(i);
  //No problems here; it fits just fine

```

> 32767

```
  i = 32767 + 1;
  Serial.println(i);
  //Oh no, the value didn't fit

```

> -32768

```
  unsigned long fake_millis = 42000;
  i = fake_millis;
  Serial.println(i);
  //This is an example of millis going past an int

```

> -23536

```
  i = -10;
  unsigned int j = i;
  Serial.println(j);
  //no way to put a negative number in an unsigned value

```

> 65526

```
  uint32_t k = fake_millis;
  Serial.println(k);
  //unsigned long is a uint32_t on arduino; this works great!

```

> 42000

The way this is implemented is really quite genius; If you are interested in where these numbers come from and why they spill over in the way they do you should look into same explanations of two's complement number representations.

# Answer
> 7 votes
`millis()` returns a `unsigned long`, which is a 32-bit unsigned integer on the Arduino. When you then try to do something like `unsigned int time = millis() - 1000`, you try to store that in a 16-bit unsigned integer `unsigned int`. A 16-bit integer can never hold a 32-bit value.

According to the C specification, paragraph 6.3.1.3, the upper 16 bits are discarded.

If possible, keep the `millis()` output in a `unsigned long` and only use data types with less bits when you're absolutely sure you will not lose bits.

There's more information on explicit casts in C here: https://stackoverflow.com/a/13652624/1544337

# Answer
> 2 votes
When you want to do stuff with millis() just remember to initialize your variable with type "uint32\_t"

So do something like "uint32\_t last\_millis" where you will store the output of the "millis()" function.

Otherwise like the others said, it would overflow when going past 31,000 which will happen pretty quickly.

---
Tags: millis, data-type
---


# Question
Title: Powering fans and arduino pro mini from single 12v supply
So, I have a 5V Arduino Pro Mini, which is running the logic behind a multi-DHT22 sensor array, and using that input to control a 12v 24mm fan (12v, 0.16 A).

This is currently a working board on an Arduino Nano with two separate power supplies (1 to USB, 1 to fan). I want to simplify it and make a more permanent installation.

What I'm keen to do is something like the following:

```
Wall Wart (12v, 500mA) ------------------------> Relay -> Fan
                \ (1) -> Arduino Pro Mini @5V -> /

```

In order to power the Arduino efficiently at 5V, and avoid drawing power all the time (i.e. when the Arduino is asleep), is the best way to apply a Linear (or Switching) Regulator with minimal burn when idle at `(1)` in the diagram, and power the Pro via its VCC line, or is it better to just run via the internal regulators and RAW?

Will this actually just generate a high burn whenever the arduino is on to convert the 12v-5v? What is the most power efficient approach here?

# Answer
> 2 votes
If you want to minimize power usage, the best thing would be to start with **devices that use more power!** :D

It's time for math! I'm going to use the generic L7805CV 5V, 1A linear regulator. Poking in the datasheet, we find that the quiescent (standby) current is max of 6 mA. I'm assuming this power drawn is 12V, not 5V.

Since a linear regulator is basically a variable resistor, we can figure out that the efficiency is:

```
Vout / Vin

```

...thus, our efficiency in this application is...

```
5V / 12V = 0.416666667% efficiency

```

... Read more here.

So, we can use the inverse of the efficiency function (`Vout / Vin``Vin / Vout`) to establish the amount of power it'll use. Final equation:

```
Power Used (W) = (12V / 5V) * Current Draw + (0.006A * 12V)

```

...which simplifies to:

```
Power Used (W) = 2.4 * Current Draw + 0.072 W

```

So, all we need to find is the power consumption of the Arduino. This forum post states the power consumption of different sleep modes:

* SLEEP\_MODE\_IDLE: 15 mA
* SLEEP\_MODE\_ADC: 6.5 mA
* SLEEP\_MODE\_PWR\_SAVE: 1.62 mA
* SLEEP\_MODE\_EXT\_STANDBY: 1.62 mA
* SLEEP\_MODE\_STANDBY : 0.84 mA
* SLEEP\_MODE\_PWR\_DOWN : 0.36 mA

Let's give the Arduino a generous 15mA to sleep:

```
Power Used (W) = 2.4 * 0.025 + 0.072 W = 0.132 W

```

So, 132 milliwatts, idle. A bit further, we can calculate that, if your wall wart has an efficiency of 10%, it will actually draw 1.32 W from your wall socket. Using a general cost per killawatt hour ($0.125), we can calculate that it will cost you about $1.45 a year for that Arduino to be ran in sleep mode 24/7 (given that we used the maximums for everything).

It's pretty cheap, so I wouldn't worry about that power. A good switching regulator will cost more than to run it for a few years with a linear regulator. I'd use the onboard one.

If you still want to optimize things, the wall wart or the fan should be looked at first. Consider getting a switching wall wart instead; this will give you a higher return on your investment since both the fan and the logic use this.

---
Tags: power, arduino-pro-mini
---


# Question
Title: Using ethernet, how do I navigate to a page on my local server
I want to access the following page on my local using my Arduino with ethernet shield" 192.168.1.2/zombie/arduino.php. My arduino is conencted to a PC through a router. The system keeps timing out

I am using the following code:

```
#include <Ethernet.h>
#include <SPI.h>

byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
byte ip[] = { 192,168,1,3 };
char server[] = "192.168.1.2/zombie/arduino.php";

EthernetClient client;

void setup()
{
  Ethernet.begin(mac, ip);
  Serial.begin(9600);

  delay(1000);

  Serial.println("connecting...");

  int res = client.connect(server, 80);

  Serial.println(res);

  if (res) {
    Serial.println("connected");
    client.println();
  } else {
    Serial.println("connection failed");
  }
}

void loop()
{
  if (client.available()) {
    char c = client.read();
    Serial.println("data:");
    Serial.println(c);
  }else{
    Serial.println("NA");
  }

  if (!client.connected()) {
    Serial.println();
    Serial.println("disconnecting.");
    client.stop();
    for(;;)
      ;
  }
}

```

# Answer
> 1 votes
I discovered the answer after some testing.

The server var:

```
char server[] = "192.168.1.2/zombie/arduino.php";

```

should only contain the ip address. So it should look like this:

```
byte server[] = { 192,168,1,2 };

```

The additional URL elements should be added using:

```
client.println("GET /zombie/arduino.php");

```

after a connection has been established

The final code should look like this:

```
#include <Ethernet.h>
#include <SPI.h>

byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
byte ip[] = { 192,168,1,3 };
byte server[] = { 192,168,1,2 };

EthernetClient client;

void setup()
{
  Ethernet.begin(mac, ip);
  Serial.begin(9600);

  delay(1000);

  Serial.println("connecting...");

  int res = client.connect(server, 80);

  Serial.println(res);

  if (res) {
    Serial.println("connected");
    client.println("GET /zombie/arduino.php");
    client.println();
  } else {
    Serial.println("connection failed");
  }
}

void loop()
{
  if (client.available()) {
    char c = client.read();
    Serial.println("data:");
    Serial.println(c);
  }else{
    Serial.println("NA");
  }

  if (!client.connected()) {
    Serial.println();
    Serial.println("disconnecting.");
    client.stop();
    for(;;)
      ;
  }
}

```

---
Tags: ethernet
---


# Question
Title: How do I send a string to master using i2c
I want to write an Arduino program that simply recieves a string (via the I2C wire library) from a master Arduino, then waits for a request, and sends that string back.

Here is my code:

```
#include <Wire.h>

void setup()
{
  Wire.begin(4);
  Wire.onReceive(receiveEvent);
  Wire.onRequest(requestEvent);
}

String data = "";

void loop()
{

}

void receiveEvent(int howMany)
{
  data = "";
  while( Wire.available()){
    data += (char)Wire.read();
  }
}

void requestEvent()
{
    Wire.write(data);
}

```

I read in the API that the write() function accepts a string, but I keep getting a "No matching function for call" error. I tried to simply replace

```
Wire.write(data);

```

with

```
Wire.write("test");

```

and that worked without error. Why is this the case?

# Answer
`data` is a `String`. `"test"` is a `char*`. `Wire.write()` has no prototype that takes a `String`.

```
Wire.write(data.c_str());

```
> 12 votes

---
Tags: i2c, string
---


# Question
Title: How does the Arduino send more than 6 bytes via I2C
I have been working with the wire library (I2C) to send data from one Arduino to another. I read that the Arduino can only send 6 bytes per cycle, but I have been able to transfer much larger strings. This code works without error:

```
  Wire.beginTransmission(4); // transmit to device #4

  for(int i = 0; i < 20; i ++){
    char rand = random(65, 100);
    Wire.write(rand);
  }

  Wire.endTransmission();    // stop transmitting

```

How is this possible? It seams that 32 characters can be sent without trouble.

I read this here: http://arduino.cc/en/Tutorial/MasterReader

> Arduino 1, the Master, is programmed to request, and then read, 6 bytes of data sent from the uniquely addressed Slave Arduino.

Now that I look at this again (after reading the responses) I think that the limit was set in the code sample.

# Answer
There is no reason to believe there is a 6 byte limit.

The Arduino Reference makes no mention of a 6 byte limit.

The Wire.cpp defines 'txBuffer\[BUFFER\_LENGTH\];' where BUFFER\_LENGTH = 32 (defined in Wire.h). The maximum is 32 bytes, just as you noticed.
> 3 votes

---
Tags: i2c
---


# Question
Title: Trying to track down macro or #define values, possibly in arduino preprocessor
In reading various code I stumble across symbols that seem to be the result of #define or other macro like symbols that I cannot find just by tracking through the code ( including its chain, if any, of includes ).

Can someone offer some reasonably simple, but complete, guidance on how the arduino ide works with especially emphasis on automatically included files ( and their location ) and any other automagically appearing stuff.

# Answer
> 4 votes
It might help to point out the use of `-D` switches of `gcc` here. If you turn on verbose output of the Arduino IDE (I am using a pretty old version):

you will see, when you compile a sketch, that the compiler is not only called with a switch `-m` (e.g. `-mmcu=atmega328p`) which describes the target (i.e. the ATMEL AVR instruction set or MCU type) for which the code is compiled, but also with a number of `-D` switches.

The `-D` switches predefine a name as a macro and also that depend on the target.

You might see for example

```
-DF_CPU=16000000L -DARDUINO=100

```

where `F_CPU` is used to pass information about the target's clock speed (16 MHz in this case) to code that depends on this, e.g. the `delay` function or the `Serial` library.

## 3 ways to define macros

In general, the confusion might come from the fact that including files in the Arduino build chain depends a lot on compiler flags, and there are several ways to define these:

1. `#define`
2. using `-D` switches
3. from the target specification (compiler built-in, `-m`)

The last point means that the above mentioned `-matmega328p` defines the macro `__AVR_ATmega328P__` which is e.g. used in `io.h` to include the appropriate file with pin mappings, RAM sizes etc. (Google for `avr-mcus.def` to find a full list of these predefined macros for AVR targets.)

Finally, note that the Arduino IDE also sets include paths depending on the target. The appropriate set of pin definitions is selected by passing an include path like this to `avr-g++`:

```
-I/usr/share/arduino/hardware/arduino/variants/standard

```

where `standard` is replaced by `leonardo`, `micro`, `mega` etc.

## Short answer / summary / how to debug

First, to **generate a list of the current `#define` directives**, use the `-dM` option like this (compiling an empty program that is specified to be C with `-x c`):

```
echo | avr-gcc -x c -E -dM -mmcu=atmega328p - | sort

```

Change `-mmcu=atmega328p` to your needs (you can also leave it out).

Second, you can use the option `-g3` to include the macro definitions in the output. Keep the intermediate files by using `-save-temps`. You can append these to the compiler call by the IDE:

```
avr-g++ -c -g -Os -Wall -fno-exceptions -ffunction-sections -fdata-sections -mmcu=atmega168 -DF_CPU=8000000L -DARDUINO=100 -I/usr/share/arduino/hardware/arduino/cores/arduino -I/usr/share/arduino/hardware/arduino/variants/standard /tmp/build5017602110288.tmp/SerialManual.cpp -o/tmp/build5017602110288.tmp/SerialManual.cpp.o -save-temps -g3

```

which will create a long output file `*.ii` (here `SerialManual.ii`) that lists among others the `define`s and `typedef`s and, most importantly, **from which files they come**.

Sample output:

```
# 1 "/tmp/build501760211028815624.tmp/SerialManual.cpp"
# 1 "/tmp/1//"
# 1 "<built-in>"
#define __STDC__ 1
#define __cplusplus 1
#define __AVR_ATmega168__ 1
#define __CHAR16_TYPE__ short unsigned int
...
# 1 "<command-line>"
#define F_CPU 8000000L
#define ARDUINO 100
...
# 1 "/usr/lib/gcc/avr/4.5.3/../../../avr/include/avr/iom168.h" 1 3
# 34 "/usr/lib/gcc/avr/4.5.3/../../../avr/include/avr/iom168.h" 3
#define _AVR_IOM168_H_ 1
#define SPM_PAGESIZE 128
#define RAMSTART (0x100)
#define RAMEND 0x4FF
#define XRAMEND RAMEND
#define E2END 0x1FF
#define E2PAGESIZE 4
#define FLASHEND 0x3FFF
...

```

---
Tags: programming, ide
---


# Question
Title: How to pass value of a function from the RFID-RC522 library into a variable then be sent into either serial or ethernet?
I'm using an RC522 RFID reader with an Arduino UNO. There is a function?? (or whatever it's called :)) in Miguel Balboa's new MFRC522.h library which is mfrc522.uid.uidByte\[i\] that prints the bytes of the unique ID. The repetition of the function results in 8 piece of HEX digits that are from the 2 numbers that each function outputs (2+2+2+2=8). Whenever I use the line of codes that are commented out, the serial monitor outputs them successfully. So for example, 12345678 is the unique id, each array displayed 12, then 34, then, 56, then 78 which is 12345678 in the serial. which is fast and unnoticeable besides that there are no spaces included when on output. The thing is, I want to output all of these into a single variable.(Please help me also on how to concatenate) How can I do this? An attempt was done below (not commented out) but it outputs only the number 16, consistently, which is I think due to a data type problem. The variables are initialized as int. The "function" which I found in the library is initialized as byte (correct me If I'm wrong). But when the variables are initialized as byte, I cannot upload the sketch since there are errors. Please help. :( (The reason I need it to be saved into a single variable is because I am placing it in the GET method of an Ethernet Client. I don't think the bare function can do that. (Or if it can, can you please help with the code? :)) Thanks

```

// Dump UID
        //Serial.print("Card UID:");

            //Serial.print(mfrc522.uid.uidByte[0], HEX);
            //Serial.print(mfrc522.uid.uidByte[1], HEX);
            //Serial.print(mfrc522.uid.uidByte[2], HEX);
            //Serial.print(mfrc522.uid.uidByte[3], HEX);

            serNum0={mfrc522.uid.uidByte[0], HEX};
            serNum1={mfrc522.uid.uidByte[1], HEX};
            serNum2={mfrc522.uid.uidByte[2], HEX};
            serNum3={mfrc522.uid.uidByte[3], HEX};
            Serial.print(serNum0);
            Serial.print(serNum1);
            Serial.print(serNum2);
            Serial.print(serNum3);

```

# Answer
As far as I can understand, you expect to receive byte data from the RFID reader, you would like to store this data into a single variable, and eventually print its content, or manipulate it in some way. You could do this maintaining a byte array (or uint8\_t array).

Let's suppose, for example, to receive a unique ID of length 4 from the RFID reader. In this case you could simply store it into a **serNum\[serNum\_size\]** array, where **serNum\_size** is just the number of data you are expecting to receive, and later access its content for whatever manipulation you would like to do.

```
int serNum_size = 4;        // reader data size
byte serNum[serNum_size];   // reader data content

for(int i = 0; i < serNum_size; i++){
 serNum[i] = mfrc522.uid.uidByte[i]; // store reader data block
 Serial.print(serNum[i], HEX);       // hexadecimal form
}

```

As far as the print is concerned, you can simply print the byte entry and apply the HEX format. In this way, the stored value will be considered as its hexadecimal value.
> 2 votes

---
Tags: variables, rfid, data-type
---


# Question
Title: Arduino Yun USB host - reading usb MIDI data and passing forward to another device
I am starting simple, but for some reason I cannot find any examples online and I stuck with my task.

I have a usb midi keyboard, Arduino Yun, and a synthesiser that can accept midi via usb. The problem is that the synth doesn't send a voltage through its usb and the keyboard has only one usb that is used to send midi data and it's powered via it at the same time.

My idea is to use my Yun's USB host (which sends voltage too) to power my midi keyboard and grab all incoming midi data from the keyboard, then simply pass it unchanged through to my synth.

Where do I start? Do I need some python code for it or everything can be done with sketch code? I've done few arduino projects but I am new to usb host functionality . This is my first step, later I would like to also convert usb-midi to 5-din-midi (old school connection), but that's different story.

Can you guys help me and point into the right direction? Anyone done something similar on Yun? I've seen some examples done on different boards, but it's all overcomplicated, I need simple read/pass usb solution. Thanks!

# Answer
You need the USB Audio kernel driver and the `aconnect` utility:

```
$ opkg update
$ opkg install kmod-usb-audio
$ opkg install alsa-utils-aconnect

```

Then just connect the ports:

```
$ aconnect -lio
client 0: 'System' [type=kernel]
    0 'Timer           '
    1 'Announce        '
client 14: 'Midi Through' [type=kernel]
    0 'Midi Through Port-0'
client 40: 'SC-8820' [type=kernel]
    0 'SC-8820 Part A  '
    1 'SC-8820 Part B  '
    2 'SC-8820 MIDI    '
client 44: 'My Little Keyboard' [type=kernel]
    0 'My Little Keyboard MIDI 1'
$ aconnect "My Little Keyboard" SC-8820
$

```

(This is plain Linux and does not need to run anything on the ATmega.)
> 1 votes

---
Tags: arduino-yun, usb, midi
---


# Question
Title: Atmel Studio and Arduino IDE compiles the same code different
Before going in details I need to say I am trying to program Arduino Nano board with atmega328p. Here is my code in Atmel Studio;

```
#include <avr/io.h>
#include <string.h>
#include <avr/interrupt.h>

int received;
int pinState = 0;

ISR(USART_RX_vect)
{
    //cli();
    while(!(UCSR0A&(1<<RXC0))){};
     //clear the USART interrupt
    received = UDR0;
    UDR0 = received;
    //sei();
}

int main(void)
{
    //DDRB |= (1 << PORTB3);
    //DDRD |= (1 << PORTD3);

    DDRD = 0xFF;
    DDRB= 0xFF;

    #define F_CPU 16000000

    TCCR2A = _BV(COM2A1) | _BV(COM2B1) | _BV(WGM21) | _BV(WGM20);
    TCCR2B = _BV(CS22);

    TCCR0A |= _BV(WGM00) | _BV(WGM01) | _BV(COM0A1);
    TCCR0B |= _BV(CS02);

    #define USART_BAUDRATE 9600
    #define UBRR_VALUE (((F_CPU / (USART_BAUDRATE * 16UL))) - 1)
    UBRR0H = (uint8_t)(UBRR_VALUE>>8);
    UBRR0L = (uint8_t)UBRR_VALUE;
    UCSR0B |= (1 << RXEN0) | (1 << TXEN0) | (1 << RXCIE0);   // Turn on the transmission, reception, and Receive interrupt
    UCSR0C |= (1<<UCSZ01)|(1<<UCSZ00);
    //DDRB |= (1 << DDB1)|(1 << DDB2);

    sei();
        while(1)
    {

    }
    return 0;
}

```

And here is the code in Arduino IDE;

```
#include <avr/io.h>
#include <string.h>
#include <avr/interrupt.h>

int received;
int pinState = 0;
ISR(USART_RX_vect)
{
    //cli();
    while(!(UCSR0A&(1<<RXC0))){};
     //clear the USART interrupt
    received = UDR0;
    UDR0 = received;
    //sei();
}
void setup() {
 DDRD = 0xFF;
    DDRB= 0xFF;

    #define F_CPU 16000000

    TCCR2A = _BV(COM2A1) | _BV(COM2B1) | _BV(WGM21) | _BV(WGM20);
    TCCR2B = _BV(CS22);

    TCCR0A |= _BV(WGM00) | _BV(WGM01) | _BV(COM0A1);
    TCCR0B |= _BV(CS02);

    #define USART_BAUDRATE 9600
    #define UBRR_VALUE (((F_CPU / (USART_BAUDRATE * 16UL))) - 1)
    UBRR0H = (uint8_t)(UBRR_VALUE>>8);
    UBRR0L = (uint8_t)UBRR_VALUE;
    UCSR0B |= (1 << RXEN0) | (1 << TXEN0) | (1 << RXCIE0);   // Turn on the transmission, reception, and Receive interrupt
    UCSR0C |= (1<<UCSZ01)|(1<<UCSZ00);
    //DDRB |= (1 << DDB1)|(1 << DDB2);

    sei();
}

void loop() {
           // wait for a second
}

```

As you can see these codes are exactly the same (except the setup-loop format) Now I am using exact same parameters for AVRdude;

**-CF:\arduino-1.0.6\hardware/tools/avr/etc/avrdude.conf -v -v -v -v -patmega328p -carduino -P\\.\COM9 -b57600 -D -Uflash:w:** and following the hex file that is created after compile. But when I examine the verbose output of avrdude.exe they are different.

Arduino program works but the program uploaded using Atmel Studio does not. For more information everything about avrdude and parameters are working and it uploads and doesnt give any errors.

I chose atmega328p in Atmel Studio which is correct because I am using arduino nano board.

# Answer
> 1 votes
I found the solution (or what the problem is). Avrdude not only requires MCU model but also programmer parameter. If you are using any of Arduino based boards you need to add **-c programmer id** do avrdude input parameters.

---
Tags: arduino-nano, avrdude, atmel-studio
---


# Question
Title: Vibrating motors with different intervals
For my project, I have 3 ultrasonic sensors and 3 vibrating motors; the motors need to buzz for a small amount of time, then wait for a specific time that corresponds whith the range of the ultrasonic sensor, then muzz again.

The problem I'm having is that I used delays at first but that would cause the third motor only to buzz after the first two already waited.

I basically need something like "digitalWrite(motorPin\_1, HIGH) for X amount of time;" and at the same moment it has to start "digitalWrite(motorPin\_2, HIGH) for X amount of time;".

Sadly I can't get the motors to vibrate any softer or harder, so I use these intervals.

# Answer
> 0 votes
Like Edgar commented, you need to check out Blink Without Delay (http://arduino.cc/en/Tutorial/BlinkWithoutDelay). Learn what they are doing and you will get this just fine.

Also, I recommend you learn to use libraries. This library can do exactly what you are asking for: http://playground.arduino.cc/Main/LibraryList#Timing --\> click on the "Timer" library by Simon Monk & J Christensen. Follow the examples there. This library works great!

Here is a complete set of code to answer your question. It should work perfectly for you.

```
/*
buzz3Motors.ino
By Gabriel Staples
http://electricrcaircraftguy.blogspot.com/
7 March 2015

To help this person here: http://arduino.stackexchange.com/questions/9089/vibriting-motors-with-different-intervals
*/

#include "Timer.h"

Timer t;

boolean buzzMotor1Now = false, buzzMotor2Now = false, buzzMotor3Now = false;
unsigned int buzzTime = 1000; //ms
byte buzzPin1 = 11;
byte buzzPin2 = 12;
byte buzzPin3 = 13;

void setup()
{
  //set pins to outputs
  pinMode(buzzPin1, OUTPUT);
  pinMode(buzzPin2, OUTPUT);
  pinMode(buzzPin3, OUTPUT);
}

void loop()
{
  //UPDATE YOUR BUZZMOTOR BOOLEANS HERE, and set to true if necessary

  /**
   * This method will generate a pulse of pulseValue, starting immediately and of
   * length period. The pin will be left in the !pulseValue state
   */
  //Function format: int8_t pulseImmediate(uint8_t pin, unsigned long period, uint8_t pulseValue);
  //see here: https://github.com/JChristensen/Timer/blob/master/Timer.h

  if (buzzMotor1Now==true)
  {
    buzzMotor1Now = false; //reset
    t.pulseImmediate(buzzPin1,buzzTime,HIGH);
  }
  if (buzzMotor2Now==true)
  {
    buzzMotor2Now = false; //reset
    t.pulseImmediate(buzzPin2,buzzTime,HIGH);
  }
  if (buzzMotor3Now==true)
  {
    buzzMotor3Now = false; //reset
    t.pulseImmediate(buzzPin3,buzzTime,HIGH);
  }

  t.update(); //update all timer events
}

```

Note that only 10 timer events can be ongoing at any given time. If you want to have more you must increase the MAX\_NUMBER\_OF\_EVENTS value in the Timer.h (https://github.com/JChristensen/Timer/blob/master/Timer.h) file.

PS. Also look into the "oscillate", "after", "every", and "pulse" functions, that the library also supports.

**If this answer meets your needs please mark the green check beside it to indicate accepted answer. Thanks.**

---
Tags: programming, motor
---


title: Timer1 arduino makes Serial not work

text:
# Question
Title: Timer1 arduino makes Serial not work
Running the code below, when I send any character in the Serial arduino is not printing "a" back. I think it's something wrong with the timer1 code but it should work cause this code was given by my teacher in C class.

```
ISR(TIMER1_COMPA_vect){

}

void setup() {

    Serial.begin(115200);

    //http://www.instructables.com/id/Arduino-Timer-Interrupts/?ALLSTEPS
    noInterrupts();
    TCCR1A = 0;// set entire TCCR1A register to 0
    TCCR1B = 0;// same for TCCR1B
    TCNT1  = 0;//initialize counter value to 0
    // set compare match register for 1000000hz increments with 8 bits prescaler
    OCR1A = 1;// = (16*10^6) / (1000000*8) - 1 (must be <65536)
    // turn on CTC mode
    TCCR1B |= (1 << WGM12);
    // Set CS11 bit for 8 prescaler. Each timer has a different bit code to each prescaler
    TCCR1B |= (1 << CS11);
    // enable timer compare interrupt
    TIMSK1 |= (1 << OCIE1A);
    interrupts();

}

void loop() {

    if (Serial.available()) {

     Serial.println("a");

    }

}

```

# Answer
> 2 votes
This is a more complicated question than the standard Arduino questions, so I took a lot of time to look into it and find out the exact answer--since I was also curious. **I have posted a very thorough answer to your question here on Stack Exchange, so please look there: https://stackoverflow.com/questions/28880226/timer1-arduino-makes-serial-not-work/28887781#28887781**

I should also note that Gerben's comment is spot-on. I recommend a value no less than 20, since you configured the counter to increment once per 0.5us. This way, a value of 20 only calls the ISR every 10us, which should keep the ISR from occurring so often that it locks up your code. As you'll see in my link above, the other main problem is you forgot to define your ISR function that is required when you enable the interrupt.

**If this meets your needs, please put a green check next to my answer to mark it as correct.**

---
Tags: arduino-uno
---


# Question
Title: How do you call a class method with named parameters?
I have a C++ class constructor like:

```
Motors(int p1=0, int p2=0);

```

However, when I attempt to instantiate it with named parameters like:

```
Motors motors(p1=123, p2=456);

```

the Arduino C/C++ compiler gives me the errors:

```
src/motors.ino:3: error: ‘p1’ was not declared in this scope
src/motors.ino:3: error: ‘p2’ was not declared in this scope

```

The compiler doesn't seem to support named parameters and thinks I'm referring to variables. I thought named parameters was a pretty widely supported feature, even in C++. What am I doing wrong?

# Answer
> 5 votes
C++ doesn't support named parameters, and I doubt it ever will.

It has strict calling conventions which mean you couldn't re-order the parameters at call-time without adding an unnecessary layer of data duplication/indirection (which would hurt performance). It would also need a significant change to compiler architecture, as variable/parameter names are usually stripped out long before the linker is invoked.

If you want to achieve a similar effect though, you could use comment blocks instead, e.g.:

```
Motors motors(/*p1*/ 123, /*p2*/ 456);

```

---
Tags: c++, compile
---


# Question
Title: How best to power down an Arduino for ~5 minutes at a time?
Reading over the datasheet it appears the longest it can shutdown for is 8s so should I just keep a counter in the loop method that checks if it's run 38 times and then execute the code I want? Would this wakeup every 8s hurt battery life much if it's doing nothing but incrementing a counter?

# Answer
> 10 votes
Yes, if you want to wake an ATMEGA (the chip in the Arduino) spontaneously (no outside trigger) from Power Down mode at periodic intervals, the you will need to rely on an interrupt generated by the watchdog timer, which has a maxim timeout of 8s.

Your goal should be to wake, increment and check the timer, and get back to sleep as quickly as possible since the amount of time you are awake will dominate your average power usage while asleep.

Some things to keep in mind...

1. The arduino uses a power regulator which always draws current. If you are going for long battery life, you will need to replace or eliminate this regulator. Much better to have an ATMEGA connected *directly* to a battery.
2. Turn off as much of the chip as possible before going to sleep. Take a look at the power control registers.
3. Make sure you are not driving any unnecessary loads with the GPIO pins when sleeping.

BTW, common wisdom has been that it is best to wake up and run at as fast a clock speed as possible to get your work done and get back to sleep as quickly as possible. However, Jack Ganssle recently published an article that makes a great case for doing the opposite. You will actually get longer battery life if you wake up to a slow clock speed, since this means you can run down the battery to lower voltage (this assumes you don'y need higher voltages for some other part of your circuit). Lots of other great info for designing long running battery-powered systems here...

http://www.ganssle.com/tem/tem275.html

Here is another relevant article about long running Arduinos...

http://www.openhomeautomation.net/arduino-battery/

# Answer
> 1 votes
Looks like you've got some great answers already. For a great deal more info and details on the matter, check out what Nick Gammon has written here too: http://www.gammon.com.au/forum/?id=11497 \- Power saving techniques for microprocessors

---
Tags: battery, sleep
---