# Question
Title: Arduino millis() fuction execution problem
I am new to Arduino development. I want to use `millis` function instead of `delay` because delay is blocking further execution of program.

Program description: In this code I want to control 2 solenoid valves with DS3231 RTC alarm and also with infrared remote control button pressed. But when I press one button for valve ON program does not turn valve on.

Please check this program and correct my mistake.

```
#include <DS3231.h>
#include <IRremote.h>
#include <IRremoteInt.h>
#include "IRremote.h"
#define LED1 2
int receiver = 6;
IRrecv irrecv(receiver);     // create instance of 'irrecv'
decode_results results;      // create instance of 'decode_results'
#define VALVE1 7
#define VALVE2 12
DS3231  rtc(SDA, SCL);
Time  t;
//-------------millis timer----------------------------------
unsigned long last1 = millis();

void setup()
{
  irrecv.enableIRIn(); // Start the receiver
  rtc.begin();
  Serial.begin(9600);
  pinMode(VALVE1, OUTPUT);
  pinMode(VALVE2, OUTPUT);
}

void loop()
{
  t = rtc.getTime();   // Get data from the DS3231
  delay(200);
  if (irrecv.decode(&results)) // have we received an IR signal?
  {
    translateIR();
    irrecv.resume(); // receive the next value
  }

  //------ALARM FOR AUTO WATERING GARDEN----
  //MORNING Routine FOR VALVE========
  if (t.hour == 16 && t.min == 15 && t.sec == 00)  //Open valve1 8AM morning
  {
    void G_valve1On();
  }

  if (t.hour == 16 && t.min == 20 && t.sec == 00)  //close valve1 8:10AM morning
  {
    void G_valve1Off();
  }

  //---------FUNCTIONS-----------------------------
  //IR COMMAND FUNCTIONS
  void translateIR()
  {
    switch (results.value)
    {
      case 0x843509F6:         //valve 1 turn on for 10minute delay
        if (millis() - last1 > 600000) //when remote button pressed valve turn on for 10min
        { G_valve1On();
          Serial.println("valve ON");
        }
        G_valve1Off();
        Serial.println("valve off");
        delay(250);
        break;
      case 0x84350AF5:                 //2nd button for 15 min delay
        G_valve2On();

        //Serial.println("valve on 15minutes...");
        //Help me to use MILLS FUNCTION.

        G_valve2Off();
        //Serial.println("valve off");
        delay(250);
        break;
    }
    delay(300);
  }
}

  //----VALVES- FUNCTION------

  void G_valve1On()
  {
    digitalWrite(VALVE1, HIGH);
    Serial.println("...turning valve1 on...");
  }
  void G_valve1Off()
  {
    digitalWrite(VALVE1, LOW);
    Serial.println("...turningvalve1 off...");
  }
  void G_valve2On()
  {
    digitalWrite(VALVE2, HIGH);
    Serial.println("...turning valve1 on...");
  }
  void G_valve2Off()
  {
    digitalWrite(VALVE2, LOW);
    Serial.println("...turningvalve1 off...");
  }

```

***UPDATE:***

Thanks for the replies. I have made some changes in the program that user ratchet freak provided below, but it is giving error.

Program:

```
#include <DS3231.h>
#include <boarddefs.h>
#include <IRremote.h>
#include <IRremoteInt.h>
#include <ir_Lego_PF_BitStreamEncoder.h>
#include "IRremote.h"
#define LED1 2
int receiver = 6;
IRrecv irrecv(receiver);     // create instance of 'irrecv'
decode_results results;      // create instance of 'decode_results'
#define valve1 13
#define valve2 12
DS3231  rtc(SDA, SCL);
Time  t;

struct valve_state {
  bool on;
  unsigned long on_timestamp;
  unsigned long on_time;
}
valve_state valve1;
valve_state valve2;
void setup()
{
  irrecv.enableIRIn(); // Start the receiver
  rtc.begin();
  Serial.begin(9600);
  pinMode(valve2, OUTPUT);
  pinMode(valve1, OUTPUT);
}

void loop() {
  t = rtc.getTime();

  //read ir
  //read rtc
  if (irrecv.decode(&results))
  {
    if (ir.value == 0x843509F6 ||                              //VALVE 1ON OFF
        (rtc.hour == 16 && rtc.min == 15 && rtc.sec == 00)) {
      valve1.on = true;
      valve1.on_timestamp = millis();

      valve1.on_time = 10 * 60 * 1000;
    }
    if (valve1.on && (millis() - valve1.on_timestamp > valve1.on_time)) {
      valve1.on = false;
      digitalWrite(valve1, LOW);

      if (ir.value == 0x843509F6 ||                                      //VALVE 2 ON OFF
          (rtc.hour == 16 && rtc.min == 15 && rtc.sec == 00)) {
        valve2.on = true;
        valve2.on_timestamp = millis();
        digitalWrite(valve2, HIGH);
        valve1.on_time = 10 * 20 * 1000;
      }
      if (valve2.on && (millis() - valve2.on_timestamp > valve2.on_time)) {
        valve1.on = false;
        digitalWrite(valve2, LOW);

      }

```

But the Arduino IDE gives following errors:

```
:\Users\ABHI's\AppData\Local\Temp\arduino_2447f9e2b3111c537660c536aa9c2330\sketch_nov11a.ino:23:13: note: in expansion of macro 'valve1'

 valve_state valve1;

             ^

sketch_nov11a:12: error: expected unqualified-id before numeric constant

 #define valve2 12

                ^

C:\Users\ABHI's\AppData\Local\Temp\arduino_2447f9e2b3111c537660c536aa9c2330\sketch_nov11a.ino:24:13: note: in expansion of macro 'valve2'

 valve_state valve2;

             ^

C:\Users\ABHI's\AppData\Local\Temp\arduino_2447f9e2b3111c537660c536aa9c2330\sketch_nov11a.ino: In function 'void loop()':

sketch_nov11a:43: error: 'ir' was not declared in this scope

     if(ir.value == 0x843509F6 ||
sketch_nov11a:44: error: 'class DS3231' has no member named 'hour'

    (rtc.hour == 16 && rtc.min == 15 && rtc.sec == 00)){

sketch_nov11a:44: error: 'class DS3231' has no member named 'min'

        (rtc.hour == 16 && rtc.min == 15 && rtc.sec == 00)){
                            ^
sketch_nov11a:44: error: 'class DS3231' has no member named 'sec'

        (rtc.hour == 16 && rtc.min == 15 && rtc.sec == 00)){

sketch_nov11a:45: error: request for member 'on' in '13', which is of non-class type 'int'

         valve1.on = true;

sketch_nov11a:46: error: request for member 'on_timestamp' in '13', which is of non-class type 'int'

         valve1.on_timestamp = millis();                ^

sketch_nov11a:55: error: request for member 'on_time' in '13', which is of non-class type 'int'

         valve1.on_time = 10*60*1000;

sketch_nov11a:57: error: request for member 'on' in '13', which is of non-class type 'int'

     if(valve1.on && (millis() - valve1.on_timestamp > valve1.on_time)){

sketch_nov11a:57: error: request for member 'on_timestamp' in '13', which is of non-class type 'int'
     if(valve1.on && (millis() - valve1.on_timestamp > valve1.on_time)){

sketch_nov11a:57: error: request for member 'on_time' in '13', which is of non-class type 'int'

     if(valve1.on && (millis() - valve1.on_timestamp > valve1.on_time)){                                                              ^

sketch_nov11a:58: error: request for member 'on' in '13', which is of non-class type 'int'

         valve1.on = false;                ^

sketch_nov11a:69: error: 'ir' was not declared in this scope

      if(ir.value == 0x843509F6 ||          ^

sketch_nov11a:70: error: 'class DS3231' has no member named 'hour'

        (rtc.hour == 16 && rtc.min == 15 && rtc.sec == 00)){             ^

sketch_nov11a:70: error: 'class DS3231' has no member named 'min'

        (rtc.hour == 16 && rtc.min == 15 && rtc.sec == 00)){                              ^
sketch_nov11a:70: error: 'class DS3231' has no member named 'sec'

        (rtc.hour == 16 && rtc.min == 15 && rtc.sec == 00)){                                                ^

sketch_nov11a:71: error: request for member 'on' in '12', which is of non-class type 'int'
         valve2.on = true;                ^

sketch_nov11a:72: error: request for member 'on_timestamp' in '12', which is of non-class type 'int'

         valve2.on_timestamp = millis();

                ^

sketch_nov11a:81: error: request for member 'on_time' in '13', which is of non-class type 'int'

         valve1.on_time = 10*20*1000;                ^

sketch_nov11a:83: error: request for member 'on' in '12', which is of non-class type 'int'

     if(valve2.on && (millis() - valve2.on_timestamp > valve2.on_time)){
               ^

sketch_nov11a:83: error: request for member 'on_timestamp' in '12', which is of non-class type 'int'

     if(valve2.on && (millis() - valve2.on_timestamp > valve2.on_time)){                                        ^

sketch_nov11a:83: error: request for member 'on_time' in '12', which is of non-class type 'int'

     if(valve2.on && (millis() - valve2.on_timestamp > valve2.on_time)){                                                            ^

sketch_nov11a:84: error: request for member 'on' in '13', which is of non-class type 'int'

         valve1.on = false;                ^

sketch_nov11a:97: error: expected '}' at end of input
 }

exit status 1
expected initializer before numeric constant

```

Can you please reconstruct complete program for me?

# Answer
The best way to handle this kind of thing is by state machine. Each valve is its own state machine and is handled one at a time.

The state machine for the valve seems to be trigger valve on based on RTC or remote. Turn off when timeout triggers

So you handle each event based on the current state:

```
struct valve_state{
    bool on;
    unsigned long on_timestamp;
    unsigned long on_time;
}

valve_state valve1;
valve_state valve2;

void loop(){

    //read ir
    //read rtc

    if(ir.value == 0x843509F6 ||
       (rtc.hour == 16 && rtc.min == 15 && rtc.sec == 00)){
        valve1.on = true;
        valve1.on_timestamp = millis();
        digitalWrite(VALVE1,HIGH);
        valve1.on_time = 10*60*1000;
    }
    if(valve1.on && (millis() - valve1.on_timestamp > valve1.on_time)){
        valve1.on = false;
        digitalWrite(VALVE1,LOW);
    }

    //repeat for valve2
}

```
> 2 votes

# Answer
The code you posted doesn't compile. I fixed the missing brace and used the auto-format command of the IDE to fix the mess in indentation. I then inserted the necessary code for the two buttons.

```
#include <DS3231.h>
#include <IRremote.h>
#include <IRremoteInt.h>
#include "IRremote.h"
#define LED1 2
int receiver = 6;
IRrecv irrecv(receiver);     // create instance of 'irrecv'
decode_results results;      // create instance of 'decode_results'
#define VALVE1 7
#define VALVE2 12
DS3231  rtc(SDA, SCL);
Time  t;
//-------------millis timer----------------------------------
unsigned long last1 = 0;
unsigned long last2 = 0;
void setup()
{
  irrecv.enableIRIn(); // Start the receiver
  rtc.begin();
  Serial.begin(9600);
  pinMode(VALVE1, OUTPUT);
  pinMode(VALVE2, OUTPUT);
}

void loop()
{
  t = rtc.getTime();   // Get data from the DS3231
  if (irrecv.decode(&results)) // have we received an IR signal?
  {
    translateIR();
    irrecv.resume(); // receive the next value
  }

  // turn of valves if they are on for enough time
  if (last1 && millis() - last1 > 600000)
  {
    G_valve1Off();
    Serial.println("valve off");
    last1 = 0;
  }
  if (last2 && millis() - last2 > 900000)
  {
    G_valve2Off();
    last2 = 0;
  }

  //------ALARM FOR AUTO WATERING GARDEN----
  //MORNING Routine FOR VALVE========
  if (t.hour == 16 && t.min == 15 && t.sec == 00)  //Open valve1 8AM morning
  {
    void G_valve1On();
  }

  if (t.hour == 16 && t.min == 20 && t.sec == 00)  //close valve1 8:10AM morning
  {
    void G_valve1Off();
  }
}

//---------FUNCTIONS-----------------------------
//IR COMMAND FUNCTIONS
void translateIR()
{
  switch (results.value)
  {
    case 0x843509F6:         //valve 1 turn on for 10minute delay

      G_valve1On();
      Serial.println("valve ON");
      last1 = millis();
      break;

    case 0x84350AF5:                 //2nd button for 15 min delay
      G_valve2On();
      last2 = millis();
      break;
  }
  delay(300);
}

//----VALVES- FUNCTION------

void G_valve1On()
{
  digitalWrite(VALVE1, HIGH);
  Serial.println("...turning valve1 on...");
}
void G_valve1Off()
{
  digitalWrite(VALVE1, LOW);
  Serial.println("...turningvalve1 off...");
}
void G_valve2On()
{
  digitalWrite(VALVE2, HIGH);
  Serial.println("...turning valve1 on...");
}
void G_valve2Off()
{
  digitalWrite(VALVE2, LOW);
  Serial.println("...turningvalve1 off...");
}

```
> 1 votes

---
Tags: millis, code-review, infrared
---


# Question
Title: Atmega2560V, trying to burn bootloaders of MegaCore
I am trying to burn MegaCore bootloaders to it, I have setup my custom PCB with Atmega2560V-8AU and 8Mhz Crystal + Load Caps all assembled on using PCBA process. I am trying to burn MegaCore bootlaoders to it, I am using Arduino UNO as ISP Programmer. My connections are all correct, It shows different Device Signatures (see below) whenever I hit Burn Bootloaders....

> 0x0000ff 0x00003f 0x0000ff 0x00ff00 0x001000 0xff0000 0xfc0000 0x00fe00

This is complete output with different Device Signatures

> Arduino: 1.8.3 (Windows 10), Board: "ATmega2560, Arduino MEGA pinout, 2.7v, Disabled (default), 8 MHz external"
>
> C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avrdude -CC:\Users\mudas\OneDrive\Documents\Arduino\hardware\MegaCore-avr-100-pin\avr/avrdude.conf -v -patmega2560 -cstk500v1 -PCOM4 -b19200 -e -Ulock:w:0x3f:m -Uefuse:w:0xfd:m -Uhfuse:w:0xd6:m -Ulfuse:w:0xf7:m
>
> avrdude: Version 6.3, compiled on Jan 17 2017 at 12:00:53 Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/ Copyright (c) 2007-2014 Joerg Wunsch
>
> ```
>      System wide configuration file is "C:\Users\mudas\OneDrive\Documents\Arduino\hardware\MegaCore-avr-100-pin\avr/avrdude.conf"
>
>      Using Port                    : COM4
>      Using Programmer              : stk500v1
>      Overriding Baud Rate          : 19200
>      AVR Part                      : ATmega2560
>      Chip Erase delay              : 9000 us
>      PAGEL                         : PD7
>      BS2                           : PA0
>      RESET disposition             : dedicated
>      RETRY pulse                   : SCK
>      serial program mode           : yes
>      parallel program mode         : yes
>      Timeout                       : 200
>      StabDelay                     : 100
>      CmdexeDelay                   : 25
>      SyncLoops                     : 32
>      ByteDelay                     : 0
>      PollIndex                     : 3
>      PollValue                     : 0x53
>      Memory Detail                 :
>
>                               Block Poll               Page                       Polled
>        Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
>        ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
>        eeprom        65    10     8    0 no       4096    8      0  9000  9000 0x00 0x00
>        flash         65    10   256    0 yes    262144  256   1024  4500  4500 0x00 0x00
>        lfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
>        hfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
>        efuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
>        lock           0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
>        calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
>        signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00
>
>      Programmer Type : STK500
>      Description     : Atmel STK500 Version 1.x firmware
>      Hardware Version: 2
>      Firmware Version: 1.18
>      Topcard         : Unknown
>      Vtarget         : 0.0 V
>      Varef           : 0.0 V
>      Oscillator      : Off
>      SCK period      : 0.1 us
>
> ```
>
> avrdude: AVR device initialized and ready to accept instructions
>
> Error while burning bootloader. Reading |
>
> ############################################ | 100% 0.02s
>
> avrdude: Device signature = 0x00fe00 avrdude: Expected signature for ATmega2560 is 1E 98 01 Double check chip, or use -F to override this check.
>
> avrdude done. Thank you.

This report would have more information with "Show verbose output during compilation" option enabled in File -\> Preferences. What should be the problem.??? How to solve this.?

# Answer
I removed 8Mhz from board and followed this instructions LINK, and burnt bootloaders using -F override check, then i returned 8Mhz oscillator to Atmega2560V and see device signature and it's automatically appears 0x1e9801 rather than 0x1e9803
> 1 votes

---
Tags: arduino-uno, arduino-mega, arduino-ide, bootloader
---


title: Splitting Integers

text:
# Question
Title: Splitting Integers
I have bluetooth (HC-05) connected on Serial port of Arduino Mega and two TM1637, I am receiving Strings from an Android phone with an app with two Time picker (Fajar and Zohar) I am sending time which is set by time picker in a formatted way.

The format is

**\<** : Start of number delimiter.

**ID** : is the number 1 or 2 (1 for Fajar and 2 for Zohar), it indicates from which time picker the data has come.

**HH** : Hours, set from time picker.

**MM** : Minutes, set from time picker.

**\>** : End of number delimiter.

Here in the example, first data which comes in is **\<10320\>** , which is starting delimiter "\<" first digit "1" is the ID from Fajar time picker,03 Hours and 20 minutes and ending delimiter "\>". Second data is **\<21830\>**, which is from Zohar time picker and vice versa.

I am parsing the incoming string and converting them into integers using the code found on Arduino Forum.

```
const char startOfNumberDelimiter = '<';
const char endOfNumberDelimiter   = '>';

void setup ()
 {
 Serial.begin (9600);
 Serial.println ("Starting ...");
 } // end of setup

void processNumber (const long n)
 {
 Serial.println (n);
 }  // end of processNumber

void processInput ()
 {
 static long receivedNumber = 0;
 static boolean negative = false;

 byte c = Serial.read ();

 switch (c)
   {

   case endOfNumberDelimiter:
     if (negative)
       processNumber (- receivedNumber);
     else
       processNumber (receivedNumber);

   // fall through to start a new number
   case startOfNumberDelimiter:
     receivedNumber = 0;
     negative = false;
     break;

   case '0' ... '9':
     receivedNumber *= 10;
     receivedNumber += c - '0';
     break;

   case '-':
     negative = true;
     break;

   } // end of switch
 }  // end of processInput

void loop ()
 {

 if (Serial.available ())
   processInput ();

 // do other stuff here
 } // end of loop

```

with the code above, i can convert string to integers and remove delimiters.

See output of the code in serial monitor.

**Problem is** : I have to separate ID and Hours and Minutes from that integer and wrap Hours and Minutes that up in

```
int8_t Digits [] = {1, 2 , 3 , 4 };

```

Here {1,2,3,4} is {H,H,M,M} Hours and Minutes which displays digits on one of the TM1637.

and also ID with "1" should change the digits on one of the TM167 and the ID with "2" should change digits on another TM1637.

Here is my full code :

```
#include "TM1637.h"

#define CLK1 2
#define DIO1 3

#define CLK2 4
#define DIO2 5

TM1637 Display1 (CLK1, DIO1);

TM1637 Display2 (CLK2, DIO2);

const char startOfNumberDelimiter = '<';
const char endOfNumberDelimiter   = '>';

void setup ()
{
  Display1.set ();
  Display1.init ();

  Display2.set();
  Display2.init();

  Serial.begin(9600);
  Serial.println ("Starting ...");
}

void loop ()
{
  if (Serial.available ())
    processInput ();
  fajar();
  zohar();
}

void processNumber (const long n)
{
  Serial.println (n);
}  // end of processNumber

void processInput ()
{
  static long receivedNumber = 0;
  static boolean negative = false;

  byte c = Serial.read ();

  switch (c)
  {

    case endOfNumberDelimiter:
      if (negative)
        processNumber (- receivedNumber);
      else
        processNumber (receivedNumber);

    // fall through to start a new number
    case startOfNumberDelimiter:
      receivedNumber = 0;
      negative = false;
      break;

    case '0' ... '9':
      receivedNumber *= 10;
      receivedNumber += c - '0';
      break;

    case '-':
      negative = true;
      break;

  } // end of switch
}  // end of processInput

void fajar ()
{
  int8_t Digits [] = {1, 2 , 3 , 4 };
  Display1.display (Digits);
  Display1.point(POINT_ON);
}

void zohar ()
{
  int8_t Digits [] = {1, 2 , 3 , 4 };
  Display2.display (Digits);
  Display2.point(POINT_ON);
}

```

Please Help

**EDIT** : Here is my edited code with Majenko shown technique.

```
#include "TM1637.h"

#define CLK1 2
#define DIO1 3

#define CLK2 4
#define DIO2 5

uint8_t fajar[4];
uint8_t zohar[4];

uint8_t address = 0;
uint8_t ptr = 0;

TM1637 Display1 (CLK1, DIO1);

TM1637 Display2 (CLK2, DIO2);
void setup ()
{
  Display1.set ();
  Display1.init ();

  Display2.set();
  Display2.init();

  Serial.begin(9600);
}

void loop ()
{
  int c = Serial.read();
  switch (c) {
    case '<': // Start of string - reset everything
      address = 0;
      ptr = 0;
      break;
    case '>': // End of string

       fajartime (); // Edited
       zohartime (); // Edited

      break;
    default:
      if ((c >= '0') && (c <= '9')) {
        if (address == 0) {
          address = c - '0';
        } else if (ptr < 4) {
          switch (address) {
            case 1:
              fajar[ptr] = c - '0';
              break;
            case 2:
              zohar[ptr] = c - '0';
              break;
          }
          ptr++;
        }
      }
  }
}

void fajartime ()
{

  Display1.display (fajar);
  Display1.point(POINT_ON);
}

void zohartime ()
{

  Display2.display (zohar);
  Display2.point(POINT_ON);
}

```

Thank you

# Answer
> 2 votes
You're thinking the wrong way. At the moment you are receiving individual characters, then combining them into a single integer, and then you want to split that integer back into individual characters. But you *start* with individual characters already. You don't need, nor want, to convert the string into an integer to then split it again.

If you take each character as it comes in as a separate number and store it separately you have no need for splitting.

For instance, you could have two 4-byte arrays for the two times. You don't need to store the first byte, since it's just an indicator of destination (we can call it a register address if you like).

A simple Finite State Machine for receiving in the correct way will make things easier:

```
uint8_t fajar[4];
uint8_t zohar[4];
uint8_t address = 0;
uint8_t ptr = 0;

int c = Serial.read();
switch (c) {
    case '<': // Start of string - reset everything
        address = 0;
        ptr = 0;
        break;
    case '>': // End of string
        // Do whatever with the data here
        break;
    default:
        if ((c >= '0') && (c <= '9')) {
            if (address == 0) {
                address = c - '0';
            } else if (ptr < 4) {
                switch (address) {
                    case 1:
                        fajar[ptr] = c - '0';
                        break;
                    case 2:
                        zohar[ptr] = c - '0';
                        break;
                }
                ptr++;
            }
        }
}

```

You could simplify things by combining zohar and fajar into a single 2D array keyed on the address (though take care that `address` never gets an invalid value in that case), or you can reduce memory usage by only having one 4-byte array if you don't care about keeping the data separate at all times (you use it and throw it away as soon as it's arrived).

# Answer
> 1 votes
I'm not sure I know what you need help with. You have code that reads a 5 character string from between .

* If i == 1 you pass the remaining 4 characters to fajar.
* If i == 2 you pass the remaining 4 characters to zohar.

You then need a function to convert the 4 characters into 4 separate integers. You might need to map these integers onto a code that displays the correct lights or you might have a library to do this already. (You already have the code for this function). All you need to do then is push the number to the display. That might be the problem you have, but how you do that depends on you library and connections.

```
TM1637 Displays[2] = {(CLK1, DIO1), (CLK2, DIO2)};
void loop()
{
    char buffer[1 + 5 + 1 + 1];
    buffer = readNumber (buffer);
    if (buffer[0] == '1')          // Treating as a character not a number.
        fajar(&(buffer[1]));
    else
        zohar(&(buffer[1]));
}
void fajar(char const* buffer) { displayValue(1, buffer);}
void zohar(char const* buffer) { displayValue(2, buffer);}
void displayValue (const int& displayID, char const* buffer)
{
    int numericValues[4];
    convertToNumbers (buffer, numericValues);  // The code in the switch statement.
    Display[displayID].display (numericValues);
    Display[displayID]..point(POINT_ON);
}

```

The above code is only a guide, never compiled and it is riddled with issues that could, if bad data was received, cause a major problem. You are going to have to add error and bounds checking before you do anything more than dev test it, but it should work :)

---
Tags: arduino-uno, arduino-mega, bluetooth, uart, code-review
---


# Question
Title: How to reset ATmega328P fuses using USBasp programmer?
I think I bricked two ATmega328Ps when I was trying to burn new bootloaders using Arduino Pro Mini, the USBasp programmer and the Extreme Burner AVR software. I had two ATMega328p with bad booloaders and I intended burn the correct bootloader to the chips.

First I connected the USBasp programmer to my Arduino Pro Mini equipped with an ATmega328P. I verified that communication was good as I could read and write to EEPROM. All was excellent.

I was using the following fuses:

LOW Fuse Byte=0x62 High Fuse Byte=0xD9 Extended=0xFF Lock = 0xFF Calibration = 0xFFFF FF8A Then the following happened:

I killed the 1st chip when I only pressed button ERASE CHIP on the programmer.

I killed the 2nd chip when I wrote the following fuses to it:

LOW Fuse Byte=0xFF High Fuse Byte=0xDA Extended=0xFD Lock Fuse = 0xCF In both cases I had the following error message:

Cannot Communication with chip Power On failed avrdude output similar messages:

RC=-1. No answer... (avrdude -c usbasp -p m328p -U lfuse:w:0x62:m -U hfuse:w:0xd9:m -U efuse:w:0xff:m ) How can I solve this problem?

How can I reset all the fuses to factory default to make the chips respond again?

# Answer
> 2 votes
Its possible you may have disabled the `SPIEN` or the `RSTDISBL` fuses. The only way to check and fix is to use a High Voltage Programmer like the STK500, STK600 or AVR Dragon and see. I have the AVR Dragon and it saved me a few times.

Also, do a search for AVR Fuse Doctor. Its a homemade fuse repair device. Pretty cool. But save yourself some time and invest in a programmer/debugger that has HVPP (high voltage parallel programming) and HVSP (high voltage serial programming). You won't regret it.

# Answer
> 1 votes
As someone mentioned, the first chip you may be able to fix by passing -B10 to avrdude. In order to program an AVR, the programmer has to be running at a slower speed than the chip you're programming is running. The fuses you have set cause the chip to run at 1Mhz using the internal clock, and -B10 will cause it to go slower (the defaults are suitable for programming a chip that is running faster than 4MHz).

The second chip, the fuses are set to 8MHz using an external crystal, so in order to fix it, you'll need to hook up an 8MHz crystal, or use a high voltage programmer.

Good luck!

# Answer
> 0 votes
Hi that happened to my Nano with atmega 328p using a usbasp programmer just checking the fuse settings to make a backup with out programming, the Extreme Burner AVR software caused the problem as it read the wrong device signature, it gave me 0x0f951e after disconnecting and trying my Nano 328p it would not work I do not use that software anymore and never had a problem with making backups with other software.

---
Tags: arduino-uno
---


title: Arduino & RPi communication via GPIO

text:
# Question
Title: Arduino & RPi communication via GPIO
so I'm working on communication between arduino and RPi via GPIO pin. It's basically connecting them by using a cable jumper. So I have a 2 channel relay shield attached to my arduino, and I've been wondered how do I connect them to RPi. I need help for this problem, any advice would be appriciated. I'll post the GPIO pin below. Thankyou

# Answer
I assume you are using Arduino UNO. Pi's digital logic is at 3.3 V and that of Arduino Uno is at 5 V. Anyway to send data from Pi to UNO, you can connect the pins directly. UNO can recognise both the logic levels of Pi's output. But to receive data from UNO to Pi, make sure you build a voltage divider using resistors, that brings 5V output from UNO's pin to 3.3 V. Also the grounds of both Pi and UNO should be connected to each other.
> 0 votes

# Answer
What you are asking really makes no sense at all.

You are starting from the mid-point of your project and wondering how to communicate using bare GPIOs without really knowing *what it is you want to communicate* and *what you want to do with that data* \- or at least you haven't made any of that clear to us.

It is unclear what you want to do with the shield from the Pi. Do you want to control the relays on it by sending instructions from the Pi? Do you want the Pi to send and receive data through the XBee? Either way the Arduino is pretty redundant in the system and in fact gets in the way more than is useful.

If it's just relays you want then it would be far simpler to wire cheap relay modules direct to the GPIOs of the Pi - then you don't have to worry about "how to communicate" - you just turn the relays on and off.

If you want to communicate with the XBee there are far simpler shields available that will plug directly into a Pi. Indeed, there are some good shields around for the Pi ("Hats" I think they call them) which give you an Arduino footprint and an XBee socket together.

The Arduino is completely pointless in this system. And anyway, if you wanted to make the two systems communicate there are far easier ways than with bare GPIO pins. Serial, for a start. The simplest ever method is to just plug the Arduino into the Pi's USB. That way it gets power and data all in one go. Just like using it with a computer.
> 2 votes

---
Tags: arduino-ide, pins, relay, raspberrypi
---


title: Controlling a stepper with MATLAB

text:
# Question
Title: Controlling a stepper with MATLAB
I am trying to control a 28BYJ-48 stepper motor + ULN2003 motor driver module (this is a picture) using MATLAB.

I tried to follow the instructions on this page, but these instructions are specific to Adafruit MotorShield, and I couldn't understand how to modify the code to fit my motor/driver.

Specifically:

1. How do I wire my motor/driver/Arduino?
2. How do I modify this command:

```
shield = addon(a, 'Adafruit\MotorShieldV2')

```
3. Do I need to flash my Arduino with any libraries?

# Answer
Adafruit Motor Shield V2 itself generates signals that are required for motor control.

ULN2003 motor driver module requires signals at the input. This is a significant difference.

Example of use this driver with MATLAB. Not need to flash Arduino any libraries.

```
a=arduino('com3','uno);

pins={'D8', 'D9', 'D10', 'D11'};
steps={'1100', '0110', '0011','1001'};

steps_size=size(steps,2);                        %steps = 4

for i = 1:50

    step = steps{mod(i,steps_size)+1};      % step=1,2,3,4

    for j=1:4
        writeDigitalPin(a, pins{j}, str2double(step(j)));
    end

    %pause(0.01);

end

```

Wiring example (Copied from CheapStepper v0.2)
> 1 votes

---
Tags: arduino-uno, stepper
---


# Question
Title: Does old/low charge battery affects internal clock?
Totally newbie in eletronics here, but could not find the answer for this one.

When a battery is nearly-exhausted, it's voltage and or amperage dims, right?

My question is if this kind of scenario (running low battery) would affect the arduino internal clock using only it.

I'm using arduino to a device that will operate remotely (with a 9V battery), and also logs intervals using the time function.

If battery is near-exhausted, then will this skew the numbers I get?

# Answer
Microprocessor clock crystal frequencies can vary a few parts per million when microprocessor supply voltages vary significantly. For example, a Czechoslovakian blog article (which was mentioned in avrfreaks.net and is shown in automatic-translated form at translate.google.com) shows a nearly-negligible drop of about 14 PPM as supply voltage for an Atmel ATtiny2313 rises from 2.4 V to 3.5 V or drops from 5 V to 3.5 V. In the results, crystal frequency was about 4000000 Hz near 2.4 V and 5 V, and drops to 3999945 Hz near 3.5 V.

I refer to that 14 PPM frequency change as nearly negligible because typical inexpensive crystals have ±50 PPM or worse accuracy and stability specifications, and ±50 PPM or worse allowance over temperature changes of a few degrees, and somewhat larger allowances as the crystal's load capacitance varies by a few pF. Thus, crystal frequency changes due to supply voltage changes are negligible compared to changes due to other causes.
> 1 votes

# Answer
Let's assume by "internal clock" you mean the internal oscillator, as the arduino's processor does not have a built-in real-time clock (something that is meant to keep track of real time like seconds/minutes/hours.)

The arduino is not like a motor where it runs slower if a lower voltage is applied. If the voltage goes too low, the arduino will just reset. Once it resets, the program running in it just starts over again, unless the battery voltage is so low it can't even start up.

If you're feeding it with a 9V battery, you're going through the 5V linear regulator on-board, which is not very energy efficient. Keep that in mind if your goal is to create a project that is meant to run a long time on the 9V battery. See the notes at http://www.gammon.com.au/power for tips on reducing the power used by an arduino and/or ATMega-based project.
> 2 votes

---
Tags: battery, time
---


# Question
Title: Arduino unable to read from XBee Series 2
An XBee Series 2 is set to `Router AT` whose `TX` and `RX` pins are connected to an Arduino Nano's `Rx` and `Tx` pins respectively. The Arduino is connected to a Mac OSX via USB.

A second XBee Series 2 is connected to a Windows system via USB. It is set to `Coordinator API` mode.

Using the sketch below on the Arduino, a packet is sent from the `Router AT` XBee to the `Coordinator API` XBee, which is seen by `XCTU` as a Explicit RX frame. However the Arduino LED should blink once if it received a reply packet (should it?)

On another test, I wrote a script to send a frame for the `Coordinator API` XBee to send to the `Router AT` XBee. Once again the Arduino LED does not blink, and nothing is seen using Arduino's Serial Monitor.

**Testing the `Coordinator API` XBee**

Using the same script to send a packet from `Coordinator API` XBee to itself, the packet was received as well as a delivery confirmation packet. This shows that both the `Coordinator API` XBee and the script are working.

```
// Delivery confirmation
received:  { type: 144,
  remote64: '0013a20040a74613',
  remote16: '0000',
  receiveOptions: 1,
  data: [ 116 ] }

// Received the packet sent to itself
received:  { type: 139,
  id: 1,
  remote16: '0000',
  transmitRetryCount: 0,
  deliveryStatus: 0,
  discoveryStatus: 0 }

```

**Testing the Arduino Sketch Code**

Using the same Arduino sketch which continuously sends API frames to the `Coordinator`, I connected the `Router AT` XBee's `RX` pin to Arduino's `RX` pin, so the frames the Arduino are sending out are going back into its `RX` pin.

This causes the Arduino's LED to light up! So there is nothing wrong with the code.

**Problem:** Does this mean the `Router AT` XBee is not configured properly? I do not think its `TX` pin is damaged because `XCTU` can still read the settings off this XBee. Any ideas on how we can troubleshoot this?

**Arduino Sketch (Connected to Router Xbee)**

```
#include <XBee.h>

XBee xbee = XBee();
uint8_t payload[] = { 0, 0 };

// SH + SL Address of receiving XBee
XBeeAddress64 addr64 = XBeeAddress64(0x0013a200, 0x40a74613);
ZBTxRequest zbTx = ZBTxRequest(addr64, payload, sizeof(payload));
ZBTxStatusResponse txStatus = ZBTxStatusResponse();

void setup() {
    pinMode(13, OUTPUT);

    Serial.begin(9600);
    xbee.setSerial(Serial);
}

void loop() {
    xbee.send(zbTx);
    delay(1000);

    xbee.readPacket();
    if (xbee.getResponse().isAvailable()) {
        // Response received, blink LED once
        Serial.println('resposne!');
        digitalWrite(13, HIGH);
        delay(1000);
        digitalWrite(13, LOW);
        delay(1000);
    }
}

```

# Answer
As I mentioned in my comments to your question, if you are using this library then it doesn't actually support AT mode. In fact, AT mode (otherwise known as Transparent Mode) is simply attached to the `Serial` port and accessed directly through the `Serial` object.

Example: put this into your Arduino attached to the AT Router.

```
#define LED 13

void setup() {
    pinMode(LED, OUTPUT);
    Serial.begin(9600);
    Serial.println("\nXBee AT communications test");
}

void loop() {
  static unsigned long previous = millis()/1000;
  if(previous != millis()/1000){
    previous = millis()/1000;
    char buffer[5];
    sprintf(buffer,"%04i",previous);
    Serial.println(buffer);
   digitalWrite(LED, !digitalRead(LED));
  }
}

```

Then open the console on the XCTU software on the API Coordinator watch the packets.

You will see above the received packets from the router. Because the coordinator is in `API` mode, you see it like this. (In `AT` mode, you will see the raw packets.

Ichose numbers to send because they are easy to read in this form. Packet `0102` appears in the packets data as `30 31 30 32 0D 0A`

In `AT` mode there is no packet confirmation, validations, status or anything. They are all handled "transparently".

As a side note, I've seen many references that both XBees need to be in the same mode. That is, in fact, incorrect. If we modify our source to include `Serial.read` you would see data the other way as well.

**edit:** I thought I would add communications between `AT Router` and `API Coordinator`. I have modified the code in the `Router` to receive a constructed packet from the `Coordinator` via the XCTU software.

```
#define LED 13

boolean serialComplete = false;
char bufferIn[64];
char bufferOut[5];
int count=0;

void setup() {
    pinMode(13, OUTPUT);
    Serial.begin(9600);
    Serial.println("\nXBee AT communications test");
}

void loop() {
  static unsigned long previous = millis()/1000;
  if(serialComplete) {
    Serial.println(bufferIn);
    serialComplete=false;
    count = 0;
    memset(bufferIn,0,sizeof(bufferIn));
    digitalWrite(LED,!digitalRead(LED));
  }
  if(previous != millis()/1000){
    previous = millis()/1000;
    sprintf(bufferOut,"%04u",(uint16_t)previous);
    Serial.println(bufferOut);
  }
}

void serialEvent() {
  while (Serial.available()) {
    char inChar = (char)Serial.read();
    if (inChar == '\n' || inChar == '\0') {
      bufferIn[count++]=0;
      serialComplete = true;
    } else {
      bufferIn[count++] = inChar;
    }
  }
}

```

Then in XCTU construct a packet for the `Coordinator`. I'm using version 6.1.0.

and click "the create frame using form generator tool"

here is the packet being received by the router. I am only sending `9999` `nul` terminated.

Then once the pair are running, you can send the constructed packet from the XCTU software and it will be received by the router.
> 1 votes

# Answer
`#include <XBee.h>
uint8_t text[] = {'H', 'e', 'l', 'l', 'o',' ','T','H','I','S',' ','I','S',' ', 'A','R','D','U','I','N','O'};
XBee xbee = XBee();
XBeeAddress64 remoteAddress = XBeeAddress64(0x00000000, 0x0000FFFF);//64 address of remote xbee:
ZBTxRequest zbTx = ZBTxRequest(remoteAddress, text, sizeof(text));// api 2 Tx request frame
ZBRxResponse zbRx = ZBRxResponse();// reading remote xbee response:
void setup()
 {
 Serial.begin(9600);
 xbee.setSerial(Serial);
 Serial.println("starting up yo!");
 }
void loop ()
 {
xbee.readPacket();// This will read any data that is available:
 if (xbee.getResponse().isAvailable())//Now, to check if a packet was received:
 {
if (xbee.getResponse().getApiId() == ZB_RX_RESPONSE)
 {
 xbee.send(zbTx);//sending data to remote xbee:
 }
 }
 }`
> 1 votes

---
Tags: programming, serial, sketch, arduino-nano, xbee
---


# Question
Title: Non intrusive current sensor with unreliable (strange) readings
I have a project where I will mount 6 non intrusive current sensor model SCT013 (100A/50mA) manufactured by yhdc.com on an Arduino Mega.

Virtual ground and Burden resistors are 1% tolerance.

To start testing I mounted 2 sensors using the principles of connection found at (http://www.homautomation.org/2013/09/17/current-monitoring-with-non-invasive-sensor-and-arduino/). Code below.

```
#include "EmonLib.h"                   // Include Emon Library
EnergyMonitor emon0;                   // Create an instance
EnergyMonitor emon1;                   // Create an instance

int Calib = 60;

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

  emon0.current(A0, Calib);             // Current: input pin, calibration.
  emon1.current(A1, Calib);             // Current: input pin, calibration.

   }

   void loop(){

double Irms0 = emon0.calcIrms(1480);
double Irms1 = emon1.calcIrms(1480);

Serial.print("Sensor0: ");
Serial.print(Irms0);
Serial.print(" Amps ");

Serial.print("Sensor1: ");
Serial.print(Irms1);
Serial.println(" Amps ");

}
//------------end------------

```

The code I found is for UNO and a single sensor and I just added a second, it works fine and sensors do independent readings well.

Both sensors are mounted on the same test live wire so I have to get more or less the same readings most of the times and it is precisely the case with readings floating between sensors on the order of 100s of miliamps.

My problems are:

1. Even with no load I get, on both sensors, a reading that varies from 270 to 320mA
2. When I connect a hair dryer that consumes in one mode 10A and in another mode 5A the readings are a lot closer to the expected (I am also checking with a clamp meter)

The problem seems to be the no load condition and the imprecise readings at low currents. I could exclude readings under a certain value on my code to solve the no load problem but them I would be ignoring real electrical measurement situations.

# Answer
Every time you use a real clamp meter, you should zero it out before measuring.

The hall effect sensors you describe are the same way. There's magnetic pull from the earth and other sources that need to be corrected for. When you draw 5 or 10 amps, that noise is masked out. They are likely still apart roughly the same # of ma as the baseline reading.

Once you subtract the no-load load from each, maybe on startup, you should get a lot better readings in terms of accuracy and precision.
> 0 votes

---
Tags: arduino-mega, sensors, voltage-level, current, analogreference
---


title: Whats wrong with my code?

text:
# Question
Title: Whats wrong with my code?
Basically what i am trying to do is use an ir remote to turn an rgb on/off and have a few preset colors as well as being able to increase/decrease red/green/blue independently. I don't know much about C/C++ so this is really hard to troubleshoot.

```
#include <IRremote.h>

int rbright;
int gbright;
int bbright;
int before;
int RECV_PIN=12; //data out of IR receiver connects to pin 12
int redPin=11;
int greenPin=10;
int bluePin=9;
int steps=5;
IRrecv irrecv(RECV_PIN);
decode_results results;

//uncomment this line if using a Common Anode LED
#define COMMON_ANODE

void setup()
{
    before=0;
    rbright=80;
    gbright=0;
    bbright=80;
    irrecv.enableIRIn(); // start the receiver
    pinMode(redPin, OUTPUT);
    pinMode(greenPin, OUTPUT);
    pinMode(bluePin, OUTPUT);
}

void loop()
{
    if (irrecv.decode(&results)) {
        if (results.value==B54A3AC5){ //Code to turn the LED ON/OFF
            if(before==0){ // if the LED was turned off, then we turn it on
                digitalWrite(redpin,HIGH);
                digitalWrite(greenpin,HIGH);
                digitalWrite(bluepin,HIGH);
                before=1; //LED is now turned on
            }
            else{
                digitalWrite(redpin,LOW);
                digitalWrite(greenpin,LOW);
                digitalWrite(bluepin,LOW); //if the LED was turned on, then we turn it off
                before=0;
            }
        }
        if (results.value==B54A8A75 && before==1){ //Code to decrease the red
            if(rbright-255/steps<0){
                analogWrite(redpin,rbright);
            }
            else{
                rbright=rbright-255/steps;
                analogWrite(redpin,rbright);
            }
        }
        if (results.value==B54A7A85 && before==1){ //Code to increase the red
            if(rbright+255/steps>255){
                analogWrite(redpin,rbright);
            }
            else{
                rbright=rbright+255/steps;
                analogWrite(redpin,rbright);
            }
        }
        if (results.value==B54AB24D && before==1){ //Code to decrease the green
            if(gbright-255/steps<0){
                analogWrite(greenpin,gbright);
            }
            else{
                gbright=gbright-255/steps;
                analogWrite(greenpin,gbright);
            }
        }
        if (results.value==B54A32CD && before==1){ //Code to increase the green
            if(gbright+255/steps>255){
                analogWrite(greenpin,gbright);
            }
            else{
                gbright=gbright+255/steps;
                analogWrite(greenpin,gbright);
            }
        }
        if (results.value==B54A0AF5 && before==1){ //Code to decrease the blue
            if(bbright-255/steps<0){
                analogWrite(bluepin,bbright);
            }
            else{
                bbright=bbright-255/steps;
                analogWrite(bluepin,bbright);
            }
        }
        if (results.value==B54ACA35 && before==1){ //Code to increase the blue
            if(bbright+255/steps>255){
                analogWrite(bluepin,bbright);
            }
            else{
                bbright=bbright+255/steps;
                analogWrite(bluepin,bbright);
            }
        }
        if (results.value==B54AA956 && before==1){ //Code yellow
            setColor(255, 255, 0);
        }
        if (results.value==B54A2AD5 && before==1){ //Code purple
            setColor(80, 0, 80);
        }
        if (results.value==B54AEA15 && before==1){ //Code aqua
            setColor(0, 255, 255);
        }
        irrecv.resume();
    }

void setColor(int red, int green, int blue)
{
#ifdef COMMON_ANODE
    red = 255 - red;
    green = 255 - green;
    blue = 255 - blue;
#endif
    analogWrite(redPin, red);
    analogWrite(greenPin, green);
    analogWrite(bluePin, blue);
}

```

The errors i get are

> rgbcontrolir\_ino.ino: In function ‘void loop()’:
> rgbcontrolir\_ino.ino:35:24: error: ‘B54A3AC5’ was not declared in this scope
> rgbcontrolir\_ino.ino:37:20: error: ‘redpin’ was not declared in this scope
> rgbcontrolir\_ino.ino:38:20: error: ‘greenpin’ was not declared in this scope
> rgbcontrolir\_ino.ino:39:20: error: ‘bluepin’ was not declared in this scope
> rgbcontrolir\_ino.ino:43:20: error: ‘redpin’ was not declared in this scope
> rgbcontrolir\_ino.ino:44:20: error: ‘greenpin’ was not declared in this scope
> rgbcontrolir\_ino.ino:45:20: error: ‘bluepin’ was not declared in this scope
> rgbcontrolir\_ino.ino:48:22: error: ‘B54A8A75’ was not declared in this scope
> rgbcontrolir\_ino.ino:50:19: error: ‘redpin’ was not declared in this scope
> rgbcontrolir\_ino.ino:54:17: error: ‘redpin’ was not declared in this scope
> rgbcontrolir\_ino.ino:56:22: error: ‘B54A7A85’ was not declared in this scope
> rgbcontrolir\_ino.ino:58:19: error: ‘redpin’ was not declared in this scope
> rgbcontrolir\_ino.ino:62:17: error: ‘redpin’ was not declared in this scope
> rgbcontrolir\_ino.ino:64:22: error: ‘B54AB24D’ was not declared in this scope
> rgbcontrolir\_ino.ino:66:19: error: ‘greenpin’ was not declared in this scope
> rgbcontrolir\_ino.ino:70:17: error: ‘greenpin’ was not declared in this scope
> rgbcontrolir\_ino.ino:72:22: error: ‘B54A32CD’ was not declared in this scope
> rgbcontrolir\_ino.ino:74:19: error: ‘greenpin’ was not declared in this scope
> rgbcontrolir\_ino.ino:78:17: error: ‘greenpin’ was not declared in this scope
> rgbcontrolir\_ino.ino:80:22: error: ‘B54A0AF5’ was not declared in this scope
> rgbcontrolir\_ino.ino:82:19: error: ‘bluepin’ was not declared in this scope
> rgbcontrolir\_ino.ino:86:17: error: ‘bluepin’ was not declared in this scope
> rgbcontrolir\_ino.ino:88:22: error: ‘B54ACA35’ was not declared in this scope
> rgbcontrolir\_ino.ino:90:19: error: ‘bluepin’ was not declared in this scope
> rgbcontrolir\_ino.ino:94:17: error: ‘bluepin’ was not declared in this scope
> rgbcontrolir\_ino.ino:96:22: error: ‘B54AA956’ was not declared in this scope
> rgbcontrolir\_ino.ino:100:24: error: ‘B54A2AD5’ was not declared in this scope
> rgbcontrolir\_ino.ino:104:24: error: ‘B54AEA15’ was not declared in this scope
> rgbcontrolir\_ino.ino:112:5: error: a function-definition is not allowed here before ‘{’ token
> rgbcontrolir\_ino.ino:121:5: error: expected ‘}’ at end of input

# Answer
The errors are self-explanatory. You just have to read them carefully.

> ‘B54A3AC5’ was not declared in this scope

The compiler doesn't know what "B54A3AC5" means. Nor do I, but I *gess* you may mean an hexadecimal 32-bit value. If that's the case, write it with the prefix "0x", as in `0xb54a3ac5`.

> ‘redpin’ was not declared in this scope

Same thing, it doesn't know what "redpin" is. Oh, wait, you have declared a variable named `redPin`. Maybe that is what you meant: "redPin", with an uppercase "P".

> a function-definition is not allowed here before ‘{’ token

You tried to define `setColor()` *within* the `loop()` function. You cannot define a function within a function in C++ (well, you can have lambdas, but that's irrelevant to your problem).

Had you tried to indent your code properly (like I did in my edit), the error would have been obvious: there is no closing brace to match the opening one at the start of `loop()`.

> expected ‘}’ at end of input

Another symptom of the problem above.

---

**Edit**: After reading your code, I have a few suggestions for making it clearer are more efficient:

1. Declare all the constants with the `const` keyword, at the beginning of your program. A common convention is to write them in all caps with underscores, to distinguish them from variables.
2. Avoid "magic numbers" within your code (e.g. the IR codes), and use properly named constants instead.
3. `before` is hard to understand, give it a name that makes sense. I suggest `leds_are_on`. And make it a `bool`, because it can only be either `true` or `false`.
4. One way to avoid deeply nested loops is to use `return` statements to get out of `loop()` as soon as you know you have nothing to do.

With these suggestions, I would start the program like this:

```
#include <IRremote.h>

// Pinout.
const int RECV_PIN  = 12;  // data out of IR receiver
const int RED_PIN   = 11;
const int GREEN_PIN = 10;
const int BLUE_PIN  = 9;

// Number of steps between black and full brightness.
const int STEPS     = 5;

// IR codes.
const uint32_t CODE_ON_OFF     = 0xb54a3ac5;
const uint32_t CODE_LESS_RED   = 0xb54a8a75;
const uint32_t CODE_MORE_RED   = 0xb54a7a85;
const uint32_t CODE_LESS_GREEN = 0xb54ab24d;
const uint32_t CODE_MORE_GREEN = 0xb54a32cd;
const uint32_t CODE_LESS_BLUE  = 0xb54a0af5;
const uint32_t CODE_MORE_BLUE  = 0xb54aca35;
const uint32_t CODE_YELLOW     = 0xb54aa956;
const uint32_t CODE_PURPLE     = 0xb54a2ad5;
const uint32_t CODE_AQUA       = 0xb54aea15;

bool leds_are_on;
int r_bright;
int g_bright;
int b_bright;
IRrecv irrecv(RECV_PIN);

```

and the `loop()` would be like this:

```
void loop()
{
    decode_results results;
    if (!irrecv.decode(&results))
        return;

    // If the LEDs are OFF, the only valid action is to turn them
    // ON.
    if (!leds_are_on) {
        if (results.value == CODE_ON_OFF) {
            digitalWrite(RED_PIN,   HIGH);
            digitalWrite(GREEN_PIN, HIGH);
            digitalWrite(BLUE_PIN,  HIGH);
            leds_are_on = true;
        }
        irrecv.resume();
        return;
    }

    // The LEDs are ON: all codes are valid.
    switch (results.value) {
        case CODE_ON_OFF:  // turn OFF
            digitalWrite(RED_PIN,   LOW);
            digitalWrite(GREEN_PIN, LOW);
            digitalWrite(BLUE_PIN,  LOW);
            leds_are_on = false;
            break;
        case CODE_LESS_RED:
            r_bright = constrain(r_bright - 255/steps, 0, 255);
            analogWrite(RED_PIN, r_bright);
            break;
        case CODE_MORE_RED:
            r_bright = constrain(r_bright + 255/steps, 0, 255);
            analogWrite(RED_PIN, r_bright);
            break;
        // etc...
    }
    irrecv.resume();
}

```
> 3 votes

# Answer
1) You are missing the braces for void loop()

2) Oops !! You have to double check - red**p**in and red**P**in etc. Case sensitive !
> 0 votes

---
Tags: arduino-nano, ir, rgb-led, code-review
---


# Question
Title: Arduino due temperature reading shows random temperatures
I am using an Arduino Due board to read three temperatures from three separate smt160-30 digital sensors but the program is behaving very randomly. the code I am using is one I got from arduino official site and changed the structure to get three temp readings and display them on a 16x2 lcd. The problem is when I use one sensor the output is reasonable but when I use all three the temperature showing are all off by 4 degrees. also I tried removing the line `lcd.print(temperature1, 1)` and the output temperatures changed. Is this odd behavior because of SRAM issues ? if so how can I find out about it and fix it ?

```
#include <LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

unsigned long now;
unsigned long lastSample;
unsigned int sampleSize;

unsigned int highCount1;
unsigned int highCount2;
unsigned int highCount3;

unsigned long lastOutput;

float temperature1;
float temperature2;
float temperature3;
float hcf1, hcf2, hcf3;
float ssf;

int sensorPin1 = 23;
int sensorPin2 = 24;
int sensorPin3 = 26;

void setup(){

    pinMode(sensorPin1, INPUT);
    pinMode(sensorPin2, INPUT);
    pinMode(sensorPin3, INPUT);

    digitalWrite(sensorPin1, LOW);
    digitalWrite(sensorPin2, LOW);
    digitalWrite(sensorPin3, LOW);

    lastSample = 0;
    sampleSize = 0;

    highCount1 = 0;
    highCount2 = 0;
    highCount3 = 0;

    temperature1 = 0;
    temperature2 = 0;
    temperature3 = 0;

    lastOutput = 0;

    delay(2000);
    lcd.setCursor(0, 0);

}

void loop() {
    now = micros();
    if (now - lastOutput > 3000000) {
        lcd.clear();

        hcf1 = highCount1;
        hcf2 = highCount2;
        hcf3 = highCount3;

        ssf = sampleSize;

        temperature1 = ((hcf1 / ssf) -0.32)/0.0047;
        temperature2 = ((hcf2 / ssf) -0.32)/0.0047;
        temperature3 = ((hcf3 / ssf) -0.32)/0.0047;

        lastOutput = now;
        sampleSize = 0;

        highCount1 = 0;
        highCount2 = 0;
        highCount3 = 0;

        lcd.print(temperature1, 1);
        lcd.print(" ");

        lcd.print(temperature2, 1);
        lcd.print(" ");

        lcd.print(temperature3, 1);

    }
    if (now - lastSample > 50) {
        sampleSize++;
        highCount1 = highCount1 + digitalRead(sensorPin1);
        highCount2 = highCount2 + digitalRead(sensorPin2);
        highCount3 = highCount3 + digitalRead(sensorPin3);
        lastSample = now;
    } else {
        delayMicroseconds(10);
    }
}

```

Thank you!

# Answer
Did you read about this smt160 sensor ? It relies on the calculation of duty cycle of the square wave output from the sensor, to calculate the temparature.

> **temperature = (dutyCycle) -0.32)/0.0047**

The square wave output has to be sampled at 8KHz or at 125us for no loss of information. This block samples that data.

> if (now - lastSample \> 50) {
>
> sampleSize++;
>
> highCount1 = highCount1 + digitalRead(sensorPin1);
>
> highCount2 = highCount2 + digitalRead(sensorPin2);
>
> highCount3 = highCount3 + digitalRead(sensorPin3);
>
> lastSample = now; }
>
> else { delayMicroseconds(10); }

when you increased the number of code lines , information loss also increased, cz more number of instructions have to be executed now , till reaching the corresponding digital reads.
> 1 votes

---
Tags: sensors, arduino-due, sram
---


title: How to calculate step delay?

text:
# Question
Title: How to calculate step delay?
I'm struggling with get suitable step delay while driving a stepper motor.

How to calculate exact step delay for 1.8deg/step stepper motor? Give some example calculation.

# Answer
* Convert the RPM of the motor to RPS.
* Take reciprocal to get seconds per revolution.
* Divide it by 360 to get seconds per degree.
* Multiply by 1.8 to get seconds per step.
> 4 votes

# Answer
> How to calculate exact step delay for 1.8deg/step stepper motor?

each rpm = 360 degrees * rpm / 60 second.

So the time, between each step, is resolution / (60 * rpm), where resolution = 1.8deg/step in your case.
> 2 votes

---
Tags: arduino-uno, stepper, calculation
---


# Question
Title: Smart way to map digital pins to a for loop over analogue pins
First post here and I have very little Arduino/c programming knowledge so forgive me my ignorance.

I am processing 18650 cells for a little powerwall project. I am using an Arduino pro mini atmega328p(5v) to read battery slot voltages and to turn on/off the tp4506 when the voltage reaches 3.85 volts for long term storage.

I am getting good voltage readings and after some trouble having a common ground with the tp4506 I think I have isolated it with a couple diodes.

I am using a 30N06L n channel mosfet to switch the tp4506's on and off, shutting them off to get the reading then back on till next voltage reading. I am learning a lot and having fun with it.

My problem stems from me not really having firm grasp of terminology or Arduino C. I cannot find my solution from search engine results after a few hours searching on and off.

I am using a for loop over 3(for now) analogue pins to get my voltage readings. What I can't figure out is how to map those pins to the digital pins controlling the mosfets from the loop. I have a few different versions of this project just trying to get a feel for what is the most efficient way to do it(I like the loop). How do I map or correlate AO with D2 and so forth. It's very frustrating not being able to type what I want out in a way that get's me some code I can learn from so I hope another human can understand my issue.

```
const int aRefVoltage = 5.00;
float voltage         = 0;

void setup() {
  // put your setup code here, to run once:
  pinMode(2, OUTPUT);
  Serial.begin(9600);
}

void loop() {
// put your main code here, to run repeatedly:
// read the input on analog pin 0-2

  for (int i = 0; i < 3; i++) {
    int sensorValue = analogRead(i);
    delay(700);

// float voltage = sensorValue * (aRefVoltage / 1024.0);
    voltage = sensorValue*aRefVoltage/1024.0;
// print out the value you read:
    Serial.print( F("  Slot-") );
    Serial.print(i + 1); // +1 to match slot number
    Serial.print( F(" = ") );
    Serial.print(voltage);
    Serial.print( F(" Volts") );

    if (i == 2) Serial.println("     ");
    Serial.println( F("") );
  }

}

```

What is the smartest way to map analogue "i\[0\]" to the digital pin 2 to turn on that slots mosfet while using the for loop? Switch case? I hope I was clear enough in my question.

Thank you

edit: inb4 I get chewed out.

I am not looking for the answer to be handed to me. I would like a link to a tutorial that will show me how to use i\[1\] either in or out of the loop so I can use it....or how to use it. An explanation from my would be hero would be nice too.

My searches all got me very rudimentary for loop examples and endless tutorials on how to turn analogue pins into digital pins. Surprising amount of tutorials on how to do that out there.

---

edit 2

A ce pin? That sounds handy I will have to look into that. I am sure my use of diodes would make an engineer shake his head. I have limited supplies on hand and this is really my first project where I have a use for my tinkering.

On each analogue pin I have two 10k resistors. One to pull down and the other to prevent the batteries from sending juice back through the analogue pin.

I spent several hours trying to use the 1.1 volt internal reference but even after calculating what my 1.1 actually was my results were not as accurate and it just seemed like slapping a dmm across the rail and dialing the knob on the buck converter was practical.

https://provideyourown.com/2012/secret-arduino-voltmeter-measure-battery-voltage/ and internal1.1Ref = 1.1 * Vcc1 (per voltmeter) / Vcc2 (per readVcc() function)

For diodes I have a 1N4001 between the battery negative on tp4506 chip and ground. If I did not have it there power was flowing back through the chip. I was also playing with a 3v zener on the positive side to block .5 volts to my analogue reading when no battery present in slot.

I have no doubt I am doing it incorrectly I wasn't expecting those issues and was just trying to hack a solution together, luckily my aim is not charging to 4.2 or I would be up a creek.

Thank you again for taking the time to show me the code I needed. I should be able to figure it out from here. As long as I am moving forward I am content. I had been at it for ten hours by the time I broke down and made this post. I was pretty burnt out and knew if I could just see an example I would be good to go.

---

edit 3

```
const int aRefVoltage        = 5.00;
const int readVoltagePins[3] = { A0, A1, A2 };
const int chargePin[3]       = { 2, 3, 4 };
const int hysteresis         = 0.10;
float voltage                = 0;

void setup() {
  // put your setup code here, to run once:
  for (int i = 0; i < 3; i++) {
    pinMode(chargePin[i], OUTPUT);
  }
  Serial.begin(9600);
}

void loop() {
  // put your main code here, to run repeatedly:
  // read the input on analog pin 0-2

  for (int i = 0; i < 3; i++) {
    digitalWrite(chargePin[i], LOW);
    delay(1500);
    int sensorValue = analogRead(readVoltagePins[i]);
    float voltage = (float) sensorValue * (5.0 / 1024.0);

    // Write here code to turn on the digital pin on (once) if the voltage
    // is too low and off (once) with hysteresis.
    // The digital pin is: chargePin[i]

    if (voltage <= 1.50) {
      digitalWrite(chargePin[i], LOW);
      Serial.print( F("  Slot-") );
      Serial.print(i + 1); // +1 to match slot number
      Serial.println( F(" = NFG || Empty ") );
      break;
    }

    else if (voltage <= (3.85 - hysteresis)) {
      digitalWrite(chargePin[i], HIGH);
      Serial.print( F("  Slot-") );
      Serial.print(i + 1); // +1 to match slot number
      Serial.print( F(" = ") );
      Serial.print(voltage);
      Serial.println( F(" Volts & Charging") );
    }

    else if (voltage >= (3.85 + hysteresis)) {
      digitalWrite(chargePin[i], LOW);
      Serial.print( F("  Slot-") );
      Serial.print(i + 1); // +1 to match slot number
      Serial.print( F(" = ") );
      Serial.print(voltage);
      Serial.println( F(" Volts & !Charging") );
    }

  }
  delay(5000); // increase later
  for (int i = 0; i < 3; i++) {
      if (i == 2)
      Serial.println("     ");
  }
}

```

This is what I have for code for now. I am just leaving the b- disconnected on the cloned charging boards. Let me know what you think @Jot

# Answer
> 2 votes
Is the programming code for A0 to D2 the same as for the other pins ? Then you could put the pin numbers in an array and run them in a for loop.

The TP4056 has a CE pin, why don't you use that to turn then on and off ?

The accuracy of reading a voltage with an Arduino depends on the accuracy of the voltage reference. You use the VCC 5V as reference. Is your 5V a stable and accurate 5.00V ? Did you measure the 5V pin of the Arduino board ?

Did you protect the analog inputs with a resistor ?

What did you do with the diodes ? Can you show a schematic (it can be a photo of a drawing) ?

An array with analog pins and digital pins:

```
const int readVoltagePins[3] = { A0, A1, A2 };
const int chargePins[3] = { 2, 3, 4 };

```

In the setup, set the digital pins as outputs:

```
for (int i=0; i<3; i++)
{
  pinMode (chargePins[i], OUTPUT);
}

```

In the loop, use a similar for-loop. I declare the locally used variables locally.

```
for (int i=0; i<3; i++)
{
  int sensorValue = analogRead(readVoltagePins[i]);
  float voltage = (float) sensorValue * (5.0 / 1024.0);

  // Write here code to turn on the digital pin on (once) if the voltage
  // is too low and off (once) with hysteresis.
  // The digital pin is: chargePins[i]
}

```

**Reaction to edit 3**

The idea of StackExchange is to have a question with an answer. Both the question and the answer can be polished along the way to create something that is helpful for others.
Developing a Arduino sketch is something else. I don't know either what the best way is to reply.

What about taking the average value of about 30 (5 to 1000) samples ? If the voltages are not steady, then averaging will help a lot.

The internal voltage reference of 1.1V is not bad, but the actual voltage can be between 1.0 and 1.2V. It is different for each Arduino board. You can measure the AREF pin with a multimeter after setting the 1.1V reference and put the measured voltage in the sketch in the calculation.
If the power to the Arduino board is a good 5.0V and the Arduino is always at the same room temperature, then the internal voltage of 1.1V can be used to measure a battery with 20mV accuracy, and perhaps 5mV with a lot averaging.

You use a delay to slow down the sketch. It is okay to do a digitalWrite over and over again during charging or during idle. In the comment I wrote to do that once, because I was anticipating to use millis instead of delays.

Because of the delay, the if\_else\_if\_else\_if is nice and straightforward code.

An integer can not be 5.0 or 0.10. Please check your whole sketch for 'float' versus 'int'. If floating point is needed, then use floating point. The voltage is a 'float', therefor it is best to use 'float' everywhere the voltage is used, for example the hysteresis.

I still don't understand the diodes. Can you make a schematic ?
Using a mosfet is probably okay, but I have to see the schematic.

# Answer
> 0 votes
> What I can't figure out is how to map those pins to the digital pins controlling the mosfets from the loop.

you probably will have to do a better job articulating what "mapping" an analog pin to digital pins means.

If the issue is "associating" an analog pin with a digital pin, a struct would do, like this:

```
typedef struct {
  uint8_t apin; //analog pin
  uint8_t dpin; //digital pin associated with the analog pin
} PIN_TYPE;

PIN_TYPE pins1, pins2; //two sets of pins

 ...
 if (analogRead(pins1.apin) < BAT_THRESLOW) turn_on(pins1.dpin); //if voltage is too low, start charging it
 if (analogRead(pins2.apin) > BAT_THRESHIGH) turn_off(pins2.dpin); //if voltage is too high, stop charging.

```

Obviously, the logic should be more comprehensive to avoid oscillation.

---
Tags: voltage, charging
---


title: L and ON keeps blinking

text:
# Question
Title: L and ON keeps blinking
I am not sure why the `ON` LED and the `L` LED keeps blinking on my Arduino.

I was just trying to implement a simple circuit using breadboard, and everything worked fine until I unplugged one wire with the power turned on. I accidentally made the wire touch something in the Arduino, and the LED in the breadboard became extremely bright. Then the `ON` LED and the `L` LED in the Arduino started to keep blinking, and I cannot download code to Arduino anymore. I am using IAR and IAR says `AT91SAM3 reset: Communication breakdown after resetting target. Abort debug session?`.

I think maybe there is a short cut when the wire touched the Arduino... But how can I determine what the problem is? Thank you very much, I am totally new to Arduino and has very limited knowledge about hardware...

# Answer
> 4 votes
You should split your problem in pieces. Like you cannot get communication with your Arduino again, so check first:

* If you plug in the Arduino / USB, do you get a message on your computer?
* Is it visible in the systems manager?
* Is it visible by the IDE?
* If you connect an adapter (12 or 9V), does it make a difference?
* If you try another Arduino, does it work like it should be?

If you are a beginner, always make sure:

* Never change any wiring with the Arduino on
* Never have dangling wires, if you do not need a wire for the time being, either remove it completely or put it in a breadboard hole that is not used
* Never change components with the Arduino on
* After rewiring/adding/changing components, double check first

Update for comment below because it does not fit as comment: To buy a cheap/fake (but working) Arduino uno, e.g. Arduino Uno from Aliexpress

---
Tags: arduino-due
---


# Question
Title: Error when trying flash bootloader into Arduino Pro Mini 328P 8MHz 3.3V
I tried flash bootloader into Arduino Pro Mini 328P 8MHz/3.3V clone, but got error.

First I did test:

```
~$ avrdude -c usbasp -p m328p

avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.00s

avrdude: Device signature = 0x1e950f (probably m328p)

avrdude: safemode: Fuses OK (E:FD, H:D9, L:E2)

avrdude done.  Thank you.

```

---

```
~$ avrdude -c usbasp -p m328p -v -U flash:w:optiboot_atmega328_pro_8MHz.hex

avrdude: Version 6.2
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "/etc/avrdude.conf"
         User configuration file is "/home/combox/.avrduderc"
         User configuration file does not exist or is not a regular file, skipping

         Using Port                    : usb
         Using Programmer              : usbasp
         AVR Part                      : ATmega328P
         Chip Erase delay              : 9000 us
         PAGEL                         : PD7
         BS2                           : PC2
         RESET disposition             : dedicated
         RETRY pulse                   : SCK
         serial program mode           : yes
         parallel program mode         : yes
         Timeout                       : 200
         StabDelay                     : 100
         CmdexeDelay                   : 25
         SyncLoops                     : 32
         ByteDelay                     : 0
         PollIndex                     : 3
         PollValue                     : 0x53
         Memory Detail                 :

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

         Programmer Type : usbasp
         Description     : USBasp, http://www.fischl.de/usbasp/

avrdude: auto set sck period (because given equals null)
avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.00s

avrdude: Device signature = 0x1e950f (probably m328p)
avrdude: safemode: hfuse reads as D9
avrdude: safemode: efuse reads as FD
avrdude: NOTE: "flash" memory has been specified, an erase cycle will be performed
         To disable this feature, specify the -D option.
avrdude: erasing chip
avrdude: auto set sck period (because given equals null)
avrdude: reading input file "optiboot_atmega328_pro_8MHz.hex"
avrdude: error opening optiboot_atmega328_pro_8MHz.hex: No such file or directory
avrdude: can't determine file format for optiboot_atmega328_pro_8MHz.hex, specify explicitly
avrdude: read from file 'optiboot_atmega328_pro_8MHz.hex' failed

avrdude: safemode: hfuse reads as D9
avrdude: safemode: efuse reads as FD
avrdude: safemode: Fuses OK (E:FD, H:D9, L:E2)

avrdude done.  Thank you.

@combox:~$ cd Downloads
@combox:~/Downloads$ cd Arduino
@combox:~/Downloads/Arduino$ avrdude -c usbasp -p m328p -v -U flash:w:optiboot_atmega328_pro_8MHz.hex

avrdude: Version 6.2
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "/etc/avrdude.conf"
         User configuration file is "/home/combox/.avrduderc"
         User configuration file does not exist or is not a regular file, skipping

         Using Port                    : usb
         Using Programmer              : usbasp
         AVR Part                      : ATmega328P
         Chip Erase delay              : 9000 us
         PAGEL                         : PD7
         BS2                           : PC2
         RESET disposition             : dedicated
         RETRY pulse                   : SCK
         serial program mode           : yes
         parallel program mode         : yes
         Timeout                       : 200
         StabDelay                     : 100
         CmdexeDelay                   : 25
         SyncLoops                     : 32
         ByteDelay                     : 0
         PollIndex                     : 3
         PollValue                     : 0x53
         Memory Detail                 :

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

         Programmer Type : usbasp
         Description     : USBasp, http://www.fischl.de/usbasp/

avrdude: auto set sck period (because given equals null)
avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.00s

avrdude: Device signature = 0x1e950f (probably m328p)
avrdude: safemode: hfuse reads as D9
avrdude: safemode: efuse reads as FD
avrdude: NOTE: "flash" memory has been specified, an erase cycle will be performed
         To disable this feature, specify the -D option.
avrdude: erasing chip
avrdude: auto set sck period (because given equals null)
avrdude: reading input file "optiboot_atmega328_pro_8MHz.hex"
avrdude: input file optiboot_atmega328_pro_8MHz.hex auto detected as Intel Hex
avrdude: writing flash (32768 bytes):

Writing | ################################################## | 100% 0.00s

avrdude: 32768 bytes of flash written
avrdude: verifying flash memory against optiboot_atmega328_pro_8MHz.hex:
avrdude: load data flash data from input file optiboot_atmega328_pro_8MHz.hex:
avrdude: input file optiboot_atmega328_pro_8MHz.hex auto detected as Intel Hex
avrdude: input file optiboot_atmega328_pro_8MHz.hex contains 32768 bytes
avrdude: reading on-chip flash data:

Reading | ################################################## | 100% 0.00s

avrdude: verifying ...
avrdude: verification error, first mismatch at byte 0x7e00
         0x00 != 0x11
avrdude: verification error; content mismatch

avrdude: safemode: hfuse reads as 0
avrdude: safemode: efuse reads as FE
avrdude: safemode: lfuse changed! Was e2, and is now fe
Would you like this fuse to be changed back? [y/n]

```

How to solve this?

# Answer
First, I put the voltage jumper on USBASP programmer to 5V, to increase voltage. Then I set correct **default fuse bits values** for this board:

```
Arduino Pro or Pro Mini (3.3V, 8 MHz) w/ ATmega328

Low Fuse:   0xFF
High Fuse:  0xDA
Extended Fuse:  0x05

avrdude -c usbasp -p m328p -v -u -U lock:w:0x3f:m -U efuse:w:0xFD:m
avrdude -c usbasp -p m328p -v -u -U lock:w:0x3f:m -U hfuse:w:0xDA:m
avrdude -c usbasp -p m328p -v -u -U lock:w:0x3f:m -U lfuse:w:0xFF:m

```

Note, that I used option **-u** when modifying the fuse bits, this switch tell avrdude we really mean modify it. It disables the default behaviour of reading out the fuses three times before programming, then verifying at the end of programming that the fuses have not changed. I put **0xFD** value for Extended Fuse Byte in place of **0x05**, due to a bug in avrdude. (0xFD and 0x05 are the same value)

After that I flashed correct bootloader:

```
avrdude -c usbasp -p m328p -v -U flash:w:optiboot_atmega328_pro_8MHz.hex -U lock:w:0x0f:m

```

Now it fully fixed and works.
> 2 votes

# Answer
It is locked/blown. Looks like you tried to flash it previously as an Arduino Nano or Uno. Now the lock bits are set. Even in highVoltage programming mode you cannot discover it. Buy a new one.
> 0 votes

---
Tags: atmega328, bootloader, avrdude, flash
---


title: How to refine ultrasonic readings

text:
# Question
Title: How to refine ultrasonic readings
I am trying to filter ultrasonic readings using averaging technique. I've also used `millis()` to measure time from start so that I can calculate readings up to 1 second and average them. I've re-initialized the `elapsedTime` variable each time to zero in the loop but again when the program execution hits this code the time starts from the time it was before. Is there any way to solve this problem?

This is the code:

```
NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE); // NewPing setup of pins and maximum distance.

int dist, ctr, filteredDist;
long rawValue = 0;
unsigned long StartTime = millis();

void setup() {
  Serial.begin(115200); // Open serial monitor at 115200 baud to see ping results.
}
//********************************************************************************************************************
void loop() {
  delay(500);
  unsigned long elapsedTime = StartTime;

  while (elapsedTime < 1000) {
    ctr++;
    dist = sonar.ping_cm();
    rawValue += dist;
    elapsedTime = millis();
  }
  filteredDist = rawValue / ctr;
  Serial.println(filteredDist);
}

```

# Answer
`elapsedTime=millis();` sets `elapsedTime` equal to the current value of `millis()`, which in the sketch above is the total time since the Uno powered up. Thus `elapsedTime` will exceed 1000 any time after the first second of execution, in which case the `while` won't do anything.

Instead say `elapsedTime=millis() - StartTime;` within the loop. Whenever you want to start the averaging cycle again, say `StartTime = millis();`.

If your only use of `elapsedTime` is to control the `while` loop, get rid of that variable; instead of `while(elapsedTime < 1000)`, say `while(millis()-StartTime < 1000)`.
> 1 votes

---
Tags: arduino-uno, code-review
---


# Question
Title: NodeMCU power consumption measurement and DeepSleep
I'm working on a project using a nodeMCU using a ICR14500(3.7V and 700mAh) battery and I'm experienced some issues when I try to estimate the total current consumption. Firstly I experienced some problems with the power supply (here is the previous question NodeMCU powered with battery and use WiFi) but this problem is now solved.

At this moment if I measure the current consumption connecting the amperimeter in serie between the battery and the nodeMCU input voltage pin I see a current consumption of 140mA continiously (ignoring the deep sleep mode) and I experienced some strange behaviours in my NodeMCU, even the code doesn't work. If I remove the amperimeter from my set up all works smooth and my source code works perfectly.

In order to validate my amperimeter I modified a usb cable and I added the amperimeter in the middle of the wire and I measured the current consumption powering me nodeMCU from the computer and I saw a current consumption of 80mA when the code is run and 14mA when the device is in deep sleep. This behaviour seems the expected one.

Are there any colateral effect measuring the battery current consumption which I haven't considered?

# Answer
> 5 votes
An ammeter is basically a small resistor in series over which the voltage drop is measured. That resistance will play a part in the effective output impedance of your power source (battery).

This increased impedance will reduce the overall amount of current the battery can provide before the voltage drops to an unacceptable level.

For instance, I just did a crude measurement of the resistor used for the 200mA range of one of my DMMs and came up with a value of 1.2Ω. At 140mA that would give a voltage drop of (V=IR = 0.14 × 1.2) 0.168V. That's 0.168V that your NodeMCU won't be seeing. Add to that the fact that the WiFi will be creating peaks of current usage up to, say, 500mA (probably less, that's just a wild guestimate), the voltage drop will increase to (0.5 × 1.2) 0.6V. From a battery giving 3.7V nominal that would plummet to 3.1V as seen by the NodeMCU.

Depending on what kind of power regulation you are using that will most likely cause brown-outs of the power and the MCU will reset or crash.

When powered by 5V that 0.6V drop would not be as noticeable, since 4.1V is still well above what is needed to power the chip and the voltage regulation can still work properly.

So how can you measure the current with the battery? Well, there's two options:

1. Use a much smaller resistance (0.1Ω, for example) and measure the voltage across it - then use Ohm's Law to calculate the current.
2. Add a large electrolytic capacitor to the input of the NodeMCU *after* your current measurement to act as an energy source for sustaining the peaks of current required by the WiFi. By big I mean something like 3300µF:

simulate this circuit – Schematic created using CircuitLab

# Answer
> 1 votes
The NodeMCU has an on-board voltage regulator, that needs excess voltage to supply the 3.3V. So if the voltage for the regulator is too low, the voltage for the ESP8266 may become too low too or it can’t draw enough current as it needs. (During boot or wifi operation it’s drawing up to 200mA peak current). If that happens, it’ll be stuck in the boot process, in which it’s drawing the 140mA.

So, when you’re running from battery, be sure to power the 3.3V supply of the board, not the 5V input that goes through the regulator first. When your battery is fully charged it’ll give 4.2V, which may just be enough for the regulator still. With the ampmeter in between it’ll definitely be too low.

Note that with the NodeMCU board you’ll never get the advertised 20μA deep sleep current of the ESP due to the onboard voltage regulator (unless you modify the board).

---
Tags: power, battery, nodemcu
---


# Question
Title: NodeMCU and expected ';' before wrong ' " '
I am creating a home weather station but the Arduino IDE shows

```
"expected ';' before 'viewport'".

```

It detects wrong quotation marks. My code:

```
     String message2 = "<!DOCTYPE html>";
  message2 += "<head>";
  message2 +=  "<title>Bootstrap Example</title>";
  message2 += " <meta name="viewport" content="width=device-width, initial-scale=1">";
  message2 += "<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">";
  message2 +=  "<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>";
  message2 +=  "<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>";
  message2 += "</head>";
  message2 += "<body>";
  message2 += "<div class="container">";
  message2 +=  "<h2>Teplotná Stanica</h2>";
  message2 +=  "<p>Teplota:";
  message2 +=  dht.readTemperature();
  message2 +=  "</p>";

  server.send(200, "text/html", message2);}

```

Can someone tell me what´s wrong? I am using Arduino IDE

# Answer
In C you can not use quotation marks inside quotation marks (thus nested).

Replace

```
message2 += " <meta name="viewport" content="width=device-width, initial-scale=1">";

```

to

```
message2 += " <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">";

```

By using the escape character \ it means that \\" is a character (") instead of the beginning or start of a string.
> 7 votes

---
Tags: esp8266, arduino-ide, nodemcu, code-review, compilation-errors
---


# Question
Title: NodeMCU powered with battery and use WiFi
I'm running a project with a nodeMCU DevKit and my project runs smooth if I run it connected through the usb wire to the computer.

I need to run my project using battery and I tried with a ICR14500 battery (3.7V and 700mAh). I connected the battery to the Vin pin but the NodeMCU doesn't send the data to the cloud.

When I run it with the battery I have detected some random behaviour, some times the led on the ESP8622 is blinking continiously and the total board power consumption is around 130mA!

Any idea what can be happening?

# Answer
It seem to be a problem with onboard regulator such as AMS1117. ESP are really sensitive to power instability. For every of my project i need to put capacitor on alimentation to prevent bugs. I think you dont have enougth voltage to work properly with your regulated input. To correct this issue you should put two battery to get 7.5 volt on the regulated input. Another solution is using 3.3v input to pass trought the regulator.
> 1 votes

# Answer
If your battery is fully charged it’ll supply abount 4.2V. The ESP should be able to handle up to 4.7V fine (according to this forum post), except that it’ll draw more current. So there’s no immediate need to go through the regulator.

If you’re battery-powering and want to use deep sleep, also consider using a different regulator with a lower quiescent current (e.g. MCP1702), otherwise the AMS1117 is already drawing at least 4mA.

Blinking and non-operation of the ESP is a sign for errors during boot, e.g. causing boot loops, typically caused by unstable power-supply, e.g. insufficient voltage or that the power supply cannot fulfill the peak current requirements (abount 200mA for the ESP).

My suggestion to be failsafe: just connect two batteries is series (7.4V nominal) and go through a 3.3V regulator.
> 1 votes

# Answer
ESP8266 require 3.3v input. Some boards require 5V (from USB) and have regulators on. How do you know that supplying 3.7v to Vin will work?

As to the high power consumption I would suspect it might be the WIFI transmitting.
> 0 votes

# Answer
I am sure my NodeMCU requires 5V power, not 3.7V, and the high power consumption is related to Wifi - a notoriously high user of power!

This is why many battery driven ESP8266 related projects contain sleep mode stuff, to attempt to significantly reduce power consumption.
> 0 votes

# Answer
For the deep sleep problem maybe you should try with lower time value such as 10 second for example. For me it's a problem with the duration .

I've never seen this kind of problem on my project but try with lower value and tell me what you got !
> 0 votes

# Answer
The vin pin will work with anything above 5v as it goes via ams1117 to drop it to 3.3, to provide 3.3v directly connect to pin which says 3v directly on nodemcu lolin board
> 0 votes

---
Tags: esp8266, wifi, battery, nodemcu
---


# Question
Title: how to break out servo.write(angle) after it reach the angle?
I used a servo as a grabber so I don't know the angle I need specifically.I need it to break the `serve.write(angle)` when the grabber holds something. I used a simple code

```
#include <Servo.h>
Servo myservo;
void setup() {
  myservo.attach(9);
}
void loop() {
  myservo.write(100);
  delay(500);
  myservo.write(50);
  delay(500);
}

```

when it holds anything it deos not return to the small angle until I remove the obstacle from its way.

# Answer
You change the angle in small increments until the sensor triggers:

```
bool closing = false;
bool openeing = false;
int angle;

void loop(){

    //read touchSensor

    if(sensorHit){
        closing  = false;
    }
    if(closing){
        if(angle <= minAngle) closing = false;
        angle -= 1;
        myservo.write(angle);

    }

    if(opening){
        if(angle >= maxAngle) opening = false;
        angle += 1;
        myservo.write(angle);

    }

}

```

The to start moving the grasper you set `opening` or `closing` to true. You can also add some trigger logic in the places where they get set back to false for the next movement if applicable.
> 1 votes

---
Tags: servo, code-review, analogwrite
---


# Question
Title: unable to find string literal operator 'operator"" stylesheet'
I am new to programing in C and I get this error:

```
unable to find string literal operator 'operator"" stylesheet'.

```

I am making a website for NodeMCU 0.9. My code:

```
 String message2 = "<!DOCTYPE html>";
      message2 += "<head>";
      message2 +=  "<title>Bootstrap Example</title>";
      message2 += " <meta name="viewport" content="width=device-width, initial-scale=1">";
      message2 += "<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">";
      message2 +=  "<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>";
      message2 +=  "<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>";

```

# Answer
I think I answered a similar question in a previous answer.

You use "before/after viewport in the fourth line, which should be prefixed with \ to make it an escape code to be treated like a " character instead of the start/end of a string.

Also afaik String is C++, as is the += operator, not C.

See answer
> 0 votes

---
Tags: esp8266, arduino-ide, nodemcu
---


# Question
Title: How to correctly use functions that return pointers to multiple typedef'ed types in Arduino IDE?
I have a program that typedef's two structs. Each one has a corresponding function that returns a pointer to it....

```
typedef struct {
  int x1;
} x;

x *a;

x *f(void) {
  return a;
}

typedef struct {
    int  y1;
} y;

y *b;

y *g(void) {
  return b;
}

void loop(void) {

}

void setup(void) {

}

```

This program produces the following error when compiled under the Arduino IDE...

```
sketch_nov10a:18: error: 'y' does not name a type

 y *g(void)

```

If we copy/paste to switch the order of the two blocks like so...

```
typedef struct {
    int  y1;
} y;

y *b;

y *g(void) {
  return b;
}

typedef struct {
  int x1;
} x;

x *a;

x *f(void) {
  return a;
}

void loop(void) {

}

void setup(void) {

}

```

...then we instead get the following error...

```
sketch_nov10a:18: error: 'x' does not name a type

x *f(void)

```

...so apparently the Arduino IDE only supports functions that return pointers to the first typedef'ed type defined in the file?

Is there a rational to this? How would you implement the above code to get it to compile under the Arduino IDE (it works fine in `gcc`).

# Answer
The Arduino IDE, rather annoyingly, tries to "help" you by generating function prototypes for functions, something it sometimes fails to do.

You can make your code compile by adding one yourself:

```
typedef struct {
  int x1;
} x;

x *a;

x *f(void) {
  return a;
}

typedef struct {
    int  y1;
} y;

y *b;

y *g(void);    // <------------------ ADD THIS
y *g(void) {
  return b;
}

void loop(void) {

}

void setup(void) {

}

```

I have a post about how to avoid the quirks in the IDE which may help you.

If you just move your code into a separate .CPP file and leave the main sketch blank, it will compile, if you add this line to the start of the .CPP file:

```
#include <Arduino.h>

```

The Arduino IDE uses gcc, so it isn't a problem with the compiler exactly, it is a problem with how it "helps" you.
> 5 votes

# Answer
# Cause

Ok, I've pinned down the root of this issue.

The `arduino-builder` program is responsible for mangling the sketch INO file into a cpp file to be fed into `gcc`. Among other things, it scans the file for function definitions and then adds prototypes for all the found functions.

The prototypes are added as a block just before the first function declaration in the file.

Unfortunately this strategy fails any time there is the following sequence....

1. a function definition
2. a type definition
3. a function definition that depends on the type defined in #2

...since the prototype for the function defined in #3 ends up being added before the type definition in #2 on which it depends, creating the compilation error.

The code responsible for this behavior is here...

https://github.com/arduino/arduino-builder/blob/b91cea8c8a42803b0b40dcdde2d1165c4e225457/src/arduino.cc/builder/ctags\_runner.go#L83

A more robust strategy would be to add each function prototype before the first function definition that calls the function being prototyped.

# Workaround

In the meantime, a workaround is to move all type definitions to be before the first function definition in the source code.

Rearranging the above example program like so...

```
typedef struct {
  int x1;
} x;

typedef struct {
    int  y1;
} y;

x *a;

x *f(void) {
  return a;
}

y *b;

y *g(void) {
  return b;
}

void loop(void) {

}

void setup(void) {

}

```

...resolves the error, at the expense of code clarity.
> 1 votes

# Answer
bigjosh, Thank you for a small and working sketch that shows the problem !

It is probably a bug of the Arduino preprocessing before handing it over to the compiler, as @nick-gammon wrote.

When I rewrite the code in my own way (in a normal sketch, a \*.ino file), the error message is gone. I use a more modern style of the struct typedefs, and I declare first the typedefs and after that the variables and after that the functions.
I suppose that when multiple include files are used, then this might not be possible.

```
// declare the typedefs.
struct x {
  int x1;
};

struct y {
  int  y1;
};

// create variables (pointers)
x *a;
y *b;

// Arduino functions
void loop(void) {
}

void setup(void) {
}

// Your own functions
x *f(void) {
  return a;
}

y *g(void) {
  return b;
}

```

I hope the data of the struct is located somewhere, because the sketch has only pointers and no valid memory location that they can point to.
> 0 votes

---
Tags: programming, arduino-ide, c++, code-review, typedef
---


# Question
Title: Arduino classes, can't get property value
I have tried hard to make a stepper motor work with a class, but I can't get a property returning its value in a method. I get 0 (zero) instead of 26 (expected) from \_stepPin.

I have tried this-\>\_stepPin with no success.

Here is the code. See the comments inside.

```
 class MKSStepperMotors {

   public:
    int _dirPin;
    int _stepPin;
    int _enablePin;

    MKSStepperMotors(int dirPin, int stepPin, int enablePin) {

      int _dirPin = dirPin;
      int _stepPin = stepPin;
      int _enablePin = enablePin;

      //Habilitamos el motor
      pinMode(_enablePin, OUTPUT);
      digitalWrite(_enablePin, LOW);

      //Cambiamos la direccion y aumentamos la velocidad
      pinMode(_dirPin, OUTPUT);
      digitalWrite(_dirPin, LOW);

      // Le indicamos el pin de señal
      pinMode(_stepPin, OUTPUT);

    }

    void move(int steps, int stepDelay)
    {

      for (int x = 0; x < steps; x++) {
        Serial.println(_stepPin); //  <-- _stepPin is zero and not 26 as it should
        digitalWrite(_stepPin, HIGH); <-- _stepPin is zero and not 26 as it should
        delayMicroseconds(stepDelay);
        digitalWrite(_stepPin, LOW);  <-- _stepPin is zero and not 26 as it should
        delayMicroseconds(stepDelay);
      }
    }
};

 MKSStepperMotors pedo(28, 26, 24);

 void setup() {
  Serial.begin(250000);
}

 void loop() {

      pedo.move(3200,100);

}

```

# Answer
When you put the type there, you are creating new variables. SO in your constructor:

```
 MKSStepperMotors(int dirPin, int stepPin, int enablePin) {

      int _dirPin = dirPin;
      int _stepPin = stepPin;
      int _enablePin = enablePin;

```

You start by creating three new variables with the same names as the member variables defined in the class. Throughout the rest of the constructor those get used instead of the ones that are member variables.

You gotta lose the "int" there.

You also have another bug in there. The constructor may run before the init function if one of these objects gets declared at global scope. Things like digitalWite and pinMode aren't going to work yet in that case. A constructor should just have code to initialize variables, it should never touch hardware. The stuff that uses hardware should be in another member function (usually called begin or init) that you can call from setup.
> 3 votes

# Answer
You have redeclared the class member fields in your constructor:

```
class MKSStepperMotors {

   public:
    int _dirPin;
    int _stepPin;
    int _enablePin;

    MKSStepperMotors(int dirPin, int stepPin, int enablePin) {

      int _dirPin = dirPin;
      int _stepPin = stepPin;
      int _enablePin = enablePin;
      ...
    }

```

The `int _dirPin = dirPin;` declares a local variable with the same name as your class member `_dirPin` and *shadows* it, hence your 3 class members never get initialized!

You should change your constructor as follows:

```
    MKSStepperMotors(int dirPin, int stepPin, int enablePin) {

      _dirPin = dirPin;
      _stepPin = stepPin;
      _enablePin = enablePin;
      ...
    }

```

Or better, use standard C++ constructor initialization:

```
    MKSStepperMotors(int dirPin, int stepPin, int enablePin)
    :_dirPin(dirPin),_stepPin(stepPin),_enablePin(enablePin) {
      ...
    }

```

In this latter example, you don't need to initialize your class members in the constructor body as they are already initialized before the body gets executed (this is idiomatic C++ usage).
> 2 votes

---
Tags: class, code-review
---