# Question
Title: How to continuously monitor range finder and immediately interrupt code to run a different code in pedestrian traffic lights setup?
I am currently doing part 2: Pedestrian Mode of my project below:

1. Regular Mode: This is the regular mode of operation. In this mode the three lights (Red, Yellow and Green LEDs) should operate in the following order. The Red LED lights for 2 seconds, followed by the Yellow LED for 1 second, the Green LED for 2 seconds and then the Yellow LED again for 1 second. The cycle should repeat until the mode changes.
2. Pedestrian Mode: This mode uses the SRF05 Ultrasonic Range Finder to detect the proximity of any object. The lights should operate as defined in the regular mode UNTIL an object is detected less than 10 cm from the TLC. The buzzer should then beep and the Yellow LED must blink ON/OFF (flashing intervals of 0.1 sec) repeatedly 10 times. The buzzer should then stop beeping and the operation of the lights (not the system) must behave as it would in the regular mode. The operation stays the same until the mode changes

My code works, however it waits for the entire regular cycle to finish before sensing a pulse with the ultrasonic range sensor to determine if an object is near or not. Therefore, when I put my hand near the sensor, it has to finish running the regular mode before it detects my hand and switches to pedestrian mode. What I would like is for the range finder to **continuously** fire the pulse and **immediately** switch to pedestrian mode when it detects an object less than 10 cm away.

Code below:

```
int red_light = 12;
int yellow_light = 10;
int green_light = 8;
int ECHOPIN = 3;
int TRIGPIN = 5;
int buzzer = 7;
float distance;

void setup() {
  Serial.begin(9600);
  pinMode(red_light, OUTPUT);
  pinMode(yellow_light, OUTPUT);
  pinMode(green_light, OUTPUT);
  pinMode(ECHOPIN, INPUT);
  pinMode(TRIGPIN, OUTPUT);
  pinMode(buzzer, OUTPUT);
}

void loop() {
  range_finder();
  if (distance < 10) {
    pedestrian_mode();
  } else {
    regular_mode();
  }
}

void regular_mode() {
  digitalWrite(red_light, HIGH);
  delay(2000);
  digitalWrite(red_light, LOW);
  digitalWrite(yellow_light, HIGH);
  delay(1000);
  digitalWrite(yellow_light, LOW);
  digitalWrite(green_light, HIGH);
  delay(2000);
  digitalWrite(green_light, LOW);
  digitalWrite(yellow_light, HIGH);
  delay(1000);
  digitalWrite(yellow_light, LOW);
}

void range_finder() {
  digitalWrite(TRIGPIN, LOW);
  delayMicroseconds(2);
  digitalWrite(TRIGPIN,HIGH);
  delayMicroseconds(10);
  digitalWrite(TRIGPIN,LOW);
  distance = pulseIn(ECHOPIN, HIGH);
  // return 0 if no high pulse in 1 sec
  distance = distance/58;
  Serial.print(distance);
  Serial.println("cm");
  delay(200);
}

void pedestrian_mode() {
  digitalWrite(buzzer, HIGH);
  digitalWrite(yellow_light, HIGH);
  delay(100);
  digitalWrite(yellow_light, LOW);
  delay(100);
  digitalWrite(yellow_light, HIGH);
  delay(100);
  digitalWrite(yellow_light, LOW);
  delay(100);
  digitalWrite(yellow_light, HIGH);
  delay(100);
  digitalWrite(yellow_light, LOW);
  delay(100);
  digitalWrite(yellow_light, HIGH);
  delay(100);
  digitalWrite(yellow_light, LOW);
  delay(100);
  digitalWrite(yellow_light, HIGH);
  delay(100);
  digitalWrite(yellow_light, LOW);
  delay(100);
  digitalWrite(yellow_light, HIGH);
  delay(100);
  digitalWrite(yellow_light, LOW);
  delay(100);
  digitalWrite(yellow_light, HIGH);
  delay(100);
  digitalWrite(yellow_light, LOW);
  delay(100);
  digitalWrite(yellow_light, HIGH);
  delay(100);
  digitalWrite(yellow_light, LOW);
  delay(100);
  digitalWrite(yellow_light, HIGH);
  delay(100);
  digitalWrite(yellow_light, LOW);
  delay(100);
  digitalWrite(yellow_light, HIGH);
  delay(100);
  digitalWrite(yellow_light, LOW);
  delay(100);
  digitalWrite(yellow_light, HIGH);
  delay(100);
  digitalWrite(yellow_light, LOW);
  delay(100);
  digitalWrite(yellow_light, HIGH);
  delay(100);
  digitalWrite(yellow_light, LOW);
  delay(100);
}

```

Also I have a feeling some parts of my code may be unnecessarily long and could be shortened. If so, I would appreciate any advice and how to do that. Thank you.

# Answer
> 1 votes
```
   digitalWrite(yellow_light, HIGH);
   delay(100);
   digitalWrite(yellow_light, LOW);
   delay(100);

   digitalWrite(yellow_light, HIGH);
   delay(100);
   digitalWrite(yellow_light, LOW);
   delay(100);

...

```

You really need to read up on "for" loops. Make a loop that does it 10 times, don't copy and paste 10 times.

As for your other issue, at the very least you could test the proximity sensor after each delay. Read up on `millis`. Just imagine how you might do it in real life. Would you really delay for two seconds? Or would you check the clock to see if two seconds had elapsed and also check if a pedestrian had arrived?

And better still, replace `delay` with a loop which tests elapsed time, and also tests the distance sensor.

---

I'm not writing more specific code because clearly the exercise is for you to learn how to do this. I already know how to do it, and if I just posted the exact answer you wouldn't have learned how to do it.

# Answer
> 0 votes
You should use an interrupt pin.

Interrupt pins can operate outside the normal void loop().

So you can have a normal loop going on. If an interrupt pin is triggered - it performs a function immediately.

https://www.arduino.cc/reference/en/language/functions/external-interrupts/attachinterrupt/

Or you could consider using a switch case.

---
Tags: arduino-uno, serial, sensors
---


# Question
Title: Splitting the power source between an arduino and a servo
I have an Arduino board which is controlling a servo. I think I read that I could only supply about 100 mA through the Arduino's 5v pin. Because of that the power supply I use is able to deliver about 2A I would like to split the power before the Arduino. How do I do that?

Do I have to take some safety for the Aduino in concern or could I just split the wire?

# Answer
If you have a 7V to 12V - 2A regulated supply, you can directly power your board using the 2.1mm connector. Do not go above 12V or you may destroy the voltage regulator on the board.

If you have a 5V to 6V - 2A regulated supply, you can supply your servo with this supply and rely on USB to supply the rest of the board (make sure you have a common ground for both the USB and the regulated supply).
> 2 votes

# Answer
There is a page with information about the current limits of Arduino pins. There's also a question on the Electrical Engineering SE site that addresses the current limits of the board overall.

From the accepted answer on that question:

> The 5V output pin is good for ~400 mA on USB, ~900 mA when using an external power adapter

So that's more than the 100 mA you mentioned in your question. (But go read the whole answer; there's more good info there.)

The easiest way to split the power is to use a separate, regulated power supply.

Except for simple tests (e.g., a single small unloaded servo), I use the digital i/o pins only for very low current signals: buttons, status LEDs, sensors, serial communication, etc.

For example, to control an IR LED that can handle up to 50 mA, I'll supply power to the LED from the Arduino board's Vcc pin and control it with a transistor attached to a digital output pin. Drawing 50 mA from the board's supply is well under the limit, and the digital output pin draws practically nothing.

For more than one servo, I use a peripheral PWM controller that takes power separately. That peripheral is powered by a separate 5V 2A power adapter, which supplies the current to actually turn the motors. I send commands to the controller using I2C from the Arduino, which is running from its own power supply.
> 0 votes

---
Tags: power
---


# Question
Title: What is wrong with my code? Did you forget '()'?
```
#include <SimbleeBLE.h>

// constants won't change. They're used here to set pin numbers:

const int ButtonPlayPause = 15;
const int ButtonNext = 12;
const int ButtonPrevious = 11;
const int OBled = 29;
       int Playp = 1;

// variables will change:
int buttonState = 0;         // variable for reading the pushbutton status

void setup()
{

  pinMode(ButtonPlayPause, INPUT);
  pinMode(ButtonNext, INPUT);
  pinMode(ButtonPrevious, INPUT);

  pinMode(OBled, INPUT);

  SimbleeBLE.deviceName = "GBAND";

  Serial.begin(115200);

  SimbleeBLE.begin();

  SimbleeBLE.txPowerLevel = +4;
}

void loop()
{
  buttonState = digitalRead(ButtonPlayPause);
  if (buttonState == HIGH)
  {
    SimbleeBLE.begin();
    SimbleeBLE.deviceName = "GBAND";
    //More code here to establish connection with android
     SimbleeBLE.sendInt = (Playp);
    digitalWrite(OBled, HIGH);
    SimbleeBLE.end();
    digitalWrite(OBled, LOW);
  } else  {
            buttonState = digitalRead(ButtonNext);
            if (buttonState == HIGH)
            {
              SimbleeBLE.begin();

              //More code here to establish connection with android

              digitalWrite(OBled, HIGH);
              SimbleeBLE.end();
              digitalWrite(OBled, LOW);
            } else  {
                      buttonState = digitalRead(ButtonPrevious);
                      if (buttonState == HIGH)
                      {
                        SimbleeBLE.begin();
                        //More code here to establish connection with android

                        digitalWrite(OBled, HIGH);
                        SimbleeBLE.end();
                        digitalWrite(OBled, LOW);
                      }
                    }
          }
    }

```

---

This is the error I keep getting:

```
Arduino: 1.8.5 (Windows Store 1.8.10.0) (Windows 10), Board: "Simblee"

C:\Users\Lestat\Desktop\SD PROJECR PAPERWORK\Sketch programs\sketch_mar20a\sketch_mar20a.ino: In function 'void loop()':

sketch_mar20a:42: error: invalid use of member function (did you forget the '()' ?)

     SimbleeBLE.sendInt = (Playp);
                        ^
exit status 1
invalid use of member function (did you forget the '()' ?)

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

```

# Answer
> 1 votes
You're trying to assign a value to a function. That is almost certainly wrong.

```
SimbleeBLE.sendInt(Playp);

```

---
Tags: serial, arduino-ide, rf, compilation-errors
---


# Question
Title: ESP8266/NodeMCU unable to communicate with MFRC522 RFID reader
I am trying to use the 'DumpInfo.ino' example file to dump an rfid tag, the only changes i have made to the example is changing the pin settings.

```
#define RST_PIN         3          // Configurable, see typical pin layout above
#define SS_PIN          4         // Configurable, see typical pin layout above

```

i have wired it based on this guide (tried using the pins shown on here as well) when i run the code i get this error from `mfrc522.PCD_DumpVersionToSerial();`

```
WARNING: Communication failure, is the MFRC522 properly connected?

```

Ive also tried printing the version and i get 0xFF which along with 0x00 seems to mean it isnt connected.

The only light that is on during the test is D1 on the RFID reader which you can see in the first wiring pic.

Pictures of wiring here

Edit: I've changed the pins to D3 and D4 but i still get the same error

# Answer
> 2 votes
change the pins to Dx constants, to match your connections

```
#define RST_PIN         D3
#define SS_PIN          D4

```

because pin D3 is not io 3 and pin D4 is not io 4. see pins\_arduino.h

# Answer
> 0 votes
ok i got it working with this pinlayout:

D1 (GPIO 5)-- RC522 - RST

D2 (GPIO 4)-- RC522 - SDA/SS

D3 (GPIO 0)

D5 (GPIO 14)-- RC522 - SCK

D6 (GPIO 12)-- RC522 - MISO

D7 (GPIO 13)-- RC522 - MOSI

D8 (GPIO 15)

also i used this tutorials code and i posted a serial.println after each piece of code to see where it is/or fails: http://www.instructables.com/id/MFRC522-RFID-Reader-Interfaced-With-NodeMCU/

---
Tags: esp8266, nodemcu, rfid
---


# Question
Title: How to externally power HC-05 module with Arduino Pro Mini?
guys, I am new to arduino. I am trying to power my HC-05 (5v with regulator to 3.3v) from Arduino Pro Mini 3.3v but I can't get it to power on.

**There is a problem: The site I bought HC-05 from says that it needs 3.3-6 volts to power on but the back of HC-05 shows only 5v pin. To confirm that it runs only on 5v I need to connect it to external 5v supply.**

But how do I make the connection? What do I connect to negative of the battery if I choose to externally power it?

Second Problem: If my HC-05 turns out to need only 3.3v input voltage, how many coins cells do I connect in series to power both pro mini and HC-05 module.

I am using a coin cell (3.3v) for powering the pro mini.

Thanks...

# Answer
The HC-05 (the PCB that is mounted on the PCB of the module) itself runs on 3.3V. Many microcontrollers run on 5V, so people are selling the HC-05 mounted on a PCB with extra components, for example a voltage regulator from 5V to 3.3V.

Voltage regulators have a minimum input voltage for which they can hold the output voltage at the specified value. Refer to this question for more information about this. So supplying the module with 3.3V instead of 5V will result in a supply voltage for the HC-05, that is significantly lower than 3.3V, so it most likely won't work correctly.

If you want to use the HC-05 module as it is, you have to provide 5V supply voltage from another source. In this case be sure to connect the grounds of both power supplies, so that they have a common ground.

If you don't want to use an extra power supply, than you may bridge the voltage regulator on your modules PCB and provide the 3.3V as supply voltage, that are used by the Arduino. Doing so would not be an easy task for a beginner, since you would have to solder small SMD components. Also the outlay of the modules PCBs are very different (depending on manufacturer). Note that in this case you should never ever put 5V on the Vcc pin of the module again, since it is then directly passed on to the HC-05 chip, which would be destroyed from the 5V supply.
> 0 votes

---
Tags: arduino-pro-mini, battery, hc-05
---


# Question
Title: Attiny85 appears to be drawing 0.2mA current but battery running down more quickly
I am trying to get a temperature sensor (tmp36) working with an Attiny and if possible I would like it to run for several weeks. I have tried to power down the Attiny and it appears to be drawing only 0.2mA current when asleep, and around 4mA when awake (using a multimeter). However the CR2032 battery went from 3.24V to 2.9V in about 1.5 days. If it was really only using 0.2mA I would have thought it would go down much more slowly than this.

I wonder if it's using a lot of current every 8s when it turns on briefly and I'm not seeing this on the multimeter, or drawing a lot of current every hour when it reads the temperature or is there something else that I'm missing.

My circuit is an Attiny85 connected directly to a tmp36 temperature sensor. I have a capacitor connected across the GND and Vcc of the tmp36. Since I am using a surface mount tmp36 I also have the shutdown pin on the tmp36 pulled high (connected directly to Vcc). Otherwise there are no other connections, it's a very simple circuit and since the current normally appears to be 0.2mA I'm not sure why the battery voltage reading is going down so fast.

I am new to turning off the attiny(and still pretty new to arduino programming) and I copied most of the code for putting the arduino to sleep from here: https://folk.uio.no/jeanra/Microelectronics/ArduinoWatchdog.html (and possibly other places).

The code I have is as follows:

```
#include <stdlib.h>
#include <EEPROM.h>
#include <SoftwareSerial.h>

#include <avr/sleep.h>    // Sleep Modes
#include <avr/power.h>    // Power management
#include <avr/wdt.h>      // Watchdog timer
#include <avr/interrupt.h> // Interrupts handling

// Definitions
#define rxPin 3
#define txPin 4

// 0 1 0 Internal 1.1V Voltage Reference, calling INTERNAL should set the            reference voltage to 1.1

SoftwareSerial mySerial(rxPin, txPin);

int currentTime = 0;
int timeLastSaveFullTemp = 0;

int nbr_remaining;
int sensorPin = 7; // This is the 7th pin on the ATtiny85,

                         // it is an analog input when reading as digital  call it 7? analogpintochannel function
                         // (On the HLT tutorial it is labelled as Pin2:  Analog input 1, SCK )

float temperature = -500.00f;     // Create a new float called temperature and give it the value -500 to start with
float prevTemp = -500.00f;
float tempDiff = -500.00f;

int tempAsInt = 0;
int tempDiffAsInt = 0;  // create int to store temperature difference between samples

signed char tempDiffAsChar; // create char to store temp difference between samples, hopefully this saves as a 1 byte no. between -128 and 127 (will store like this on EEPROM where difference is small enough since only 1 byte) (range around -128 to 128 so can't use for temp diff greater than 10 deg)
signed char warningNextDataIsTwoBytes = 111;

int eepromAddress = 0;       // initialize variable for position in eeprom to store data collected

int decideWhatToSaveFlag = 1;    // Decide what to save,  if this = 0 then save the temp difference as a char (1 byte), otherwise save the entire temperature as an integer.

// interrupt raised by the watchdog firing
// when the watchdog fires during sleep, this function will be executed
// remember that interrupts are disabled in ISR functions
ISR(WDT_vect)
{
        // not hanging, just waiting
        // reset the watchdog
        wdt_reset();
}

// function to configure the watchdog: let it sleep 8 seconds before firing
// when firing, configure it for resuming program execution
void configure_wdt(void)
{

  cli();                           // disable interrupts for changing the registers

  MCUSR = 0;                       // reset status register flags

                               // Put timer in interrupt-only mode:
  WDTCR |= 0b00011000;            // Set WDCE (5th from left) and WDE (4th from left) to enter config mode,
                               // using bitwise OR assignment (leaves other bits unchanged).
  WDTCR =  0b01000000 | 0b100001; // set WDIE: interrupt enabled, 8 seconds
                               // clr WDE: reset disabled
                               // and set delay interval (right side of bar) to 8 seconds

  sei();                           // re-enable interrupts

}

// Put arduino to sleep.
void sleep(int ncycles)
{
 nbr_remaining = ncycles; // defines how many cycles should sleep

  // Set sleep to full power down.  Only external interrupts or
  // the watchdog timer can wake the CPU!
  set_sleep_mode(SLEEP_MODE_PWR_DOWN);

  // Turn off the ADC while asleep.
  power_adc_disable();

  while (nbr_remaining > 0){ // while some cycles left, sleep!

  // Enable sleep and enter sleep mode.
  sleep_mode();

  // CPU is now asleep and program execution completely halts!
  // Once awake, execution will resume at this point if the
  // watchdog is configured for resume rather than restart

  // When awake, disable sleep mode
  sleep_disable();

  // we have slept one time more
  nbr_remaining = nbr_remaining - 1;

  }

  // put everything on again
  power_all_enable();

 }

// the setup routine runs once when you press reset:
void setup() {
  analogReference(INTERNAL);    // This sets the internal ref to be 1.1V (or close to this), note that this makes 1.1V the highest voltage. The TMP36 gives 1.1V at around 55 or 60 deg so need to not put the chip in temperatures hotter than 55deg
  pinMode(sensorPin, INPUT);    // make pin 7 on the ATTiny an input pin

  delay(1000);

  configure_wdt();              // configure the watchdog

  mySerial.begin(9600);         // begin software serial at rate of 9600

}

// the loop routine runs over and over forever:
void loop() {

  sleep(450);                                                 // sleep for a given number of cycles (here, 450 * 8 seconds = 60mins) in lowest power mode

  currentTime = currentTime + 60;                             // add 60 min to current time

  if((eepromAddress<=510))                                    //  the eeprom still has space
  {

/***********Get temperature from sensor, then calculate difference since previous reading****************/

//Earlier set the reference voltage for the analog to digital converter to 1.1V.  This means a value of 1.1V will be read as the maximum (not sure if 1023 or 1024, but anyway)
//Note that this means an input greater than 1.1V from the temperature sensor (temperature about 55deg) is bad, not sure if it will damage the circuit or give bad readings but avoid.

temperature = analogRead(sensorPin)*1100.0/1024.0;  // read value on pin 7, between 0 and 1023 where 1023 is max, convert result back to a voltage in millivolts.
temperature = (temperature - 500)/ 10;              //Celcius temperature = [(analog voltage in mV) - 500] / 10
tempDiff = temperature - prevTemp;

/******* Change temperature diffence to integer and a signed char if it's between -2 and 2 deg ***********/
tempAsInt = int(round(temperature*10));  // multiply temp. by 10 then round and change to an integer type, this should give temp. as a three digit integer scaled by x10, e.g. 335 = 33.5deg, 120 = 12.0deg etc.
tempDiffAsInt = int (round(tempDiff*10));

// work out whether want to save complete temperature or just temp difference
if ((currentTime - timeLastSaveFullTemp) >=10)           // If the entire temperature hasn't been saved for more than 10 min, then want to save the entire temperature rather than just difference
{
  decideWhatToSaveFlag = 1;                               // Set flag to 1, since want to save entire temperature
  }
else
  decideWhatToSaveFlag = 0;                               // If the entire temperature has already been saved recently then set flag to zero since only want to save the difference.

if ((tempDiffAsInt>-20 and tempDiffAsInt<20)and (decideWhatToSaveFlag == 0))    // if temp change is less than 2 degrees and if the decideWhatToSaveFlag hasn't been previously set to 1 for another reason.
  tempDiffAsChar = (char)(tempDiffAsInt);

else decideWhatToSaveFlag = 1;                                                  // if the temp diff since prev sample is > 2 degrees or less than -2 degrees then set flag to 1 since want to save the entire temp. not just the difference

if (decideWhatToSaveFlag == 0)
  {
  //mySerial.print(" Temp diff");
  EEPROM.put(eepromAddress, tempDiffAsChar);
  eepromAddress = eepromAddress + sizeof(tempDiffAsChar);
  }

else
  {
  EEPROM.put(eepromAddress, warningNextDataIsTwoBytes);
  eepromAddress = eepromAddress + sizeof(warningNextDataIsTwoBytes);
  EEPROM.put(eepromAddress, tempAsInt);
  eepromAddress = eepromAddress + sizeof(tempAsInt);
  timeLastSaveFullTemp = currentTime;                       // Update time entire temperature was last saved to the current time.
  }

prevTemp = temperature; // copy temp to prev temp for next time.

}

}

```

Please excuse my coding I'm still learning. I deleted my comments at the start of the program which explain why I'm changing the temp. to char etc. as they weren't really relevant to this question but if anyone wants them let me know.

Here is the circuit, a 3V battery is connected between Vcc and GND. The capacitor is 0.1uF ceramic. I am using the SOIC (surfacemount) type package of the tmp36, the (not) shutdown pin in the SOIC version needs to be pulled high so I have connected it to Vcc as specified in the datasheet (this pin doesn't exist in the TO92 through-hole version of the tmp36).

All help is greatly appreciated,

I'm also interested in suggestions for reducing the current further. (Or for how to store more temperatures in a 512 byte EEPROM but that's less important than the battery)

Thanks very much!!

p.s. I have tested this code and it did save one temperature per hour as expected. (The section of code that saves temperature differences rather than temperature doesn't run when there is a 60 min gap between temperatures so all temperatures were saved to the eeprom as integers).

# Answer
2.9V doesn't sound too bad. See a datasheet for the CR2032 I found:

It looks like slightly more than 2.9V would be the expected voltage for up to 600 hours.

3.2V looks like it is fully charged, and won't stay at that level for long.

Having said that, 200 µA current sounds like a lot. You should be able to get it down to 6 µA. Perhaps post your schematic?

---

After a bit of experimenting I got the current draw down to the (expected) lower level of 4.25µA running at 3V, and 6.77µA running at 5V.

You had not in fact turned the ADC off. You need to change:

```
 // Turn off the ADC while asleep.
  power_adc_disable();

```

To:

```
  // Turn off the ADC while asleep.
  ADCSRA = 0;            // turn off ADC
  power_all_disable();

```

I can't comment on what extra draw, if any, your TMP36 will cause, however this should help get the overall current down.

---

Of course, you need to put the ADC back on afterwards, so this might be better:

```
  // Turn off the ADC while asleep.
  byte saved_ADCSRA = ADCSRA;
  ADCSRA = 0;            // turn off ADC
  power_all_disable();

  ... sleep here

  power_all_enable();
  ADCSRA = saved_ADCSRA;

```
> 5 votes

# Answer
**THIS IS NOT AN ANSWER**; it's just a very long comment and I was not able to add all the formatting and ideas in the comment I was writing. Please don't consider it as a valid answer.

I leave all the low current topics to Nick, since he's doing a great work as usual. I wanted just to give you some ideas for the temperature acquisition and storing.

First of all, the `float`s. Forget them. `float`s are one of the worst things you can do to your poor microcontroller, unless you have an onboard FPU.

I haven't checked your sensor, so I assume that the calculations you performed were correct. (Note: voltages above 1.1V should not damage the board, but will not be detected - the value will cap at 1023)

So when you read number X (from 0 to 1023) you get the temperature by writing

```
((X * 1100 / 1024) - 500) / 10

```

You are using floats to do this. I don't like them at all, so let's switch to ints. Moreover you decided to store them with a 0.1°C precision, so that /10 is meaningless. So in the end

```
<integral type> finalTempInTenthsOfDegree = ((X * 1100 / 1024) - 500);

```

Now, the types. The value of the final temperature is between +60°C (corresponding to 1.1V) and -50°C (0V - not sure about this, but let's stick with these value). This means an integral value going from +600 to -500; the proper type is therefore `int16_t` (signed 2-bytes value). During your calculations, the X (which is a `uint16_t`) is multiplied by 1100; this value can rise up to 1125300 (when X = 1023), which does not fit a 2-bytes variable. You can reduce 1100/1024 to 275/256, but this does not solve the problem.

**EDIT:** As Edgar Bonet pointed out in the comments, the problem of having a 4 bytes is not solved with this trick, but dividing by 1024 is more "time consuming" than dividing by 256 (because the 10-bit shift involves shifting bits through bytes, while a 8-bit shift is just moving the bytes. His tests (avr-gcc 4.9.2, optimization for size -Os) show that a shift by 10 bits (=division by 10) is converted in a routine to shift one bit through all the four bytes and then this is repeated 10 times. This lead to 72 clock cycles. A 8-bit shift, on the other hand, was converted to a byte movement for three out of four bytes and the zeroing of the uppermost. So 4 clock cycles. So... Yes, this does not solve the problem, but can optimize the code; I'll think of this trick in my future projects. Of course this can be done in a much more optimized way, and the number of cycles required can change according to the way the operation is written and the optimization level, but it is worth remembering that if you shift by a multiple of 8 bits (on an 8-bit machine) it is more optimized than another arbitrary value.

In any case, even with either of the two values, a 4-bytes int is required. In order to reduce unnecessary overhead, let's switch it back to a 2-bytes whenever possible. Something like

```
int16_t finalTemp = ((int16_t)((((uint32_t)X) * 1100U) / 1024) - 500;

```

So the operation order is

1. Take the X value
2. Promote it to a unsigned 32 bit variable
3. Multiplicate by 1100 (values from 1125300 to 0)
4. Divide it by 1024 (values from 1098 to 0)
5. Cast it back to a signed 16 bit value
6. subtract 500 (values from 598 to -500)

Now, the storage. If you store the values as they are, you will get 256 measurements, which at one measurement per hour mean something like 10 days.

One easy way to increase this space is noticing that you are using only 11 bytes out of 16. So you can compact it and get 372 measurements (around 15 days)

The trick you used (ten measurements with just the difference) is ok only if you guarantee that in ten hours the value will not drift by more than +/- 12°C. This is not guaranteed and probably also not optimal. I'd prefer another approach, which is based on the fact that you are using only 11 bytes out of 16. You can have two different data stored in the EEPROM, which are differences (1 byte) or whole temperatures (2 bytes). You will distinguish them with the first bits: a 0 denotes a difference, a 1 a whole temperature (followed by 0 is the low byte, by a 1 is a high byte). This means that for the difference you have seven bits, so it can range from +63 to -64. Whenever you reach a difference from the previous temperature within 6 degrees you don't save anymore the whole temperature. The code to do this is for instance the following one:

```
// int16_t finalTemp calculated before
// int16_t prevTemp initialised, at beginning, for instance to -32000, so the difference is greater and you force a full writing at the first round

int16_t tempDiff = finalTemp - prevTemp;
prevTemp = finalTemp; // update the temperature

if ((tempDiff <= -63) || (tempDiff >= 63)
{
    // In this case we want to save the whole integer
    EEPROM.update(eepromAddress++, (((uint8_t)finalTemp) & 0x3F) | 0x80); // Write the lowest 6 bits, and set the first two to 0b10
    EEPROM.update(eepromAddress++, (((uint8_t)(finalTemp >> 6)) & 0x3F)| 0xC0); // Write the highest 6 bits, and set the first two to 0b11
}
else
{
    // In this case we save only the difference
    EEPROM.update(eepromAddress++, ((uint8_t)tempDiff) & 0x7F); // Just remove the highest bit, and store it
}

```

In this case, provided that the temperature does not vary a lot, you will get 511 measurements, which is like 21 days. For each variation greater than 6°C/h you will lose one hour of measurement, down to 256 measurements. Please note that I wrote `EEPROM.update` instead of `write`, even if this is not necessary (just one of the things I do every time).

The last possibility is to switch to a 0.5°C resolution. If you use this resolution, you can map your values on a range 120/-100, thus being able to use only one byte for each measurement. Since the accuracy is +/- 2°C, you can also choose this without problems.

Apart from the storage, if you record only 256 bytes of information how do you know which are the correct values and which are the previous ones? My suggestion is to reserve one value (for instance if you have used my code you can get an impossible value such as 0x40 - which if I'm not wrong maps to DIFFERENCE -64, which is impossible since the difference is stored only when greater than -63) and fill the memory before starting to insert the values. beware that if you do it then turning on the board will reset the memory...

One last suggestion: you have a sensor which stores the data internally, but.. How do you get them out of it? My personal suggestion is to have a dedicated pin (for instance PB3) tied to a jumper. If it is open then you will proceed with the normal program, otherwise you wait for a download request. (don't do the opposite since the jumper inserted drains the battery). Consequently the code can be something like this:

```
const uint8_t invalidEepromValue = 0x40;
const int16_t maxAddress = 510; // Not equal to 512 to avoid a last reading of 2 bytes

void dumpMemory()
{
    int16_t prevTemp = 0;
    for (int16_t i = 0; i < maxAddress; i++)
    {
        int16_t value = EEPROM.read(i);
        if (value == invalidEepromValue)
            break; // Finished the reading

        if (value & 0x80)
        { // WholeData
            int16_t value2 = EEPROM.read(i+1);
            if (((((uint8_t)value) & 0xC0) != 0x80) || ((((uint8_t)value2) & 0xC0) != 0xC0))
            {
                mySerial.print("Error with memory cell ");
                mySerial.println(i);
                continue;
            }

            prevTemp = (value & 0x3F) | ((value2 & 0x3F) << 6);
            if (value2 & 0x40) prevTemp |= 0xF000; // Extend the sign

            mySerial.println(prevTemp);
            i++; // skip the next value (already analysed)
        }
        else
        { // Difference
            if (value & 0x40) value |= 0xFF80; // Extend the sign

            prevTemp += value;
            mySerial.println(prevTemp);
        }
    }
}

void setup() {
    pinMode(modePin, INPUT_PULLUP);
    mySerial.begin(9600);         // begin software serial at rate of 9600

    delay(1);
    if (digitalRead(modePin) == LOW)
    { // Enter read mode
        while (1) // loop forever
        {
            while (mySerial.available() == 0); // Wait for some chars

            dumpMemory();

            while (mySerial.available() > 0)
                mySerial.read(); // Flush receiving buffer
        }
    }

    // Clear the memory
    for (int16_t i = 0; i <= maxAddress; i++) // Equal to cover the last reading of 2 bytes
        EEPROM.update(i, invalidEepromValue); // Here update is almost mandatory

    // Go on with the initialization you already implemented
    ...
}

```

I hope that the software serial works even without the main structure (so in a `while(1)` in the setup).

Please keep in mind that all the code written here has NOT been tested, so it may require some corrections
> 2 votes

---
Tags: power, attiny, current, sleep, attiny85
---


# Question
Title: How to install several IDE version on my PC
How can i install old version of IDE, without uninstalling the other version?(How can i install several IDE version in same laptop).

# Answer
> 3 votes
Arduino.cc have a guide :

https://www.arduino.cc/en/Guide/PortableIDE

The gist is:

1. Download the desired version in ZIP format
2. Unpack the content in the zip file to a folder
3. Start the arduino.exe in that folder.

Remember that you have to place all libraries, board definitions in that folder.

The folder can be copied to another computer or a USB stick....

---
Tags: arduino-uno, arduino-ide, ide
---


title: Semantics of local PROGMEM

text:
# Question
Title: Semantics of local PROGMEM
I want to create a class to better use strings in flash. At its core is the following

```
template<size_t N>
struct progstr
{
    constexpr progstr(const char (&str)[N])
        : progstr(str, make_index_sequence<N> {}) {}

    template<size_t... Is>
    constexpr progstr(const char (&str)[N], index_sequence<Is...>)
        : _str{str[Is]...} {}

    constexpr operator const char*() const {
        return _str;
    }

    const char _str[N] PROGMEM;
};

```

Where `make_index_sequence` and `index_sequence` are the same as those from `<utility>`.

The problem arises when I try to emulate `PSTR`

```
template<size_t N>
constexpr const char* pstr(const char (&str)[N])
{
    return progstr<N>{str};  // huh?
}

```

It even compiles. However

* The returned pointer is "dangling", but it is pointing into flash memory. Will this work?
* A `constexpr` function may be called with an array with runtime values, and that cannot possibly create the string in flash can it?

# Answer
> 2 votes
I tested with 100 chars string

const char\*

```
Sketch uses 1566 bytes
Global variables use 288 bytes

```

with F macro

```
Sketch uses 1594 bytes
Global variables use 188 bytes

```

progstr \<101\> ps(...

```
Sketch uses 1618 bytes
Global variables use 288 bytes

```

const char\* ps = pstr("...

```
Sketch uses 1502 bytes
Global variables use 188 bytes

```

the pstr version string has errors at the end, when printed.

**sorry, the pstr function works only if previous sketch version put the string into flash memory. it is not in hex file.**

---
Tags: c++
---


# Question
Title: How to set the sampling frequency in Arduino without using a delay
I am reading an ECG signal using a single lead heart rate monitor. What I know is that when I use `delay(15)` it means that I am getting 66.67 readings in a second which corresponds to the sampling frequency. I want to set the sampling frequency to 250. This can be done by introducing `delay(4)`.

What I really need is to set the sampling frequency to 250 Hz without introducing a delay in the code because I am acquiring ECG data in real time. Also, I am sending the data to python for processing and the delay will affect the sampling frequency in the time domain analysis.

any detailed solution or code ??

PS. I am using Arduino UNO

Code:

```
#define SERIAL_BUFFER_SIZE 8192
#include <SoftwareSerial.h>
unsigned long Time;
void setup() {

  // initialize the serial communication:

  pinMode(10, INPUT); // Setup for leads off detection LO +
  pinMode(11, INPUT); // Setup for leads off detection LO -
  Serial.println("CLEARDATA"); //clears up

  Serial.println("RESETTIMER"); //resets timer to 0

  Serial.begin(115200);

}

void loop() {
  if((digitalRead(10) == 1)||(digitalRead(11) == 1)){
   Serial.println('!');
  //  continue;
  }
  else{
   /*
     // send the value of analog input 0:
     int idata = analogRead(A0);
  //  float data = (idata*3.3)/1023;
      Serial.println(idata);
*/
  int sensorValue = analogRead(A0);
  float voltage = sensorValue * (3.3/1023.0);
  Serial.println(voltage);
  }
  //Wait for a bit
    delay(4);
}

```

# Answer
> 5 votes
Use the concept of blink without delay.

Instead of using delay() to set the timeout you use a timestamp and check `micros()` against that to see whether your interval has passed:

```
const unsigned long READ_PERIOD = 4000;  // 4000 us: 250 Hz

void loop() {
    static unsigned long lastRead;
    if (micros() - lastRead >= READ_PERIOD) {
        lastRead += READ_PERIOD;
        if (digitalRead(10) == 1 || digitalRead(11) == 1)
            Serial.println('!');
        else
            Serial.println(analogRead(A0) * (3.3/1024));
    }
}

```

---
Tags: arduino-uno, interrupt, millis
---


# Question
Title: Control/Interacting with Android OS using Arduino board
I am new to arduino, and based on my search, it is possible to connect Android devices and Arduino board thru bluetooth module. But most solutions i found are either for controlling Arduino board using an Android app, or controlling Android app using Arduino board.

My question is, is there a way to control/interact with the Android OS on the phone using Arduino, thru whatever connection?

I am asking this because I am thinking of building a portable keyboard or touchscreen device for Android devices, and want to see if Arduino is a good platform for prototype.

# Answer
> 2 votes
What you've seen is most usually a bluetooth module which has a "virtual COM port" service -- you connect to the bluetooth module and you can then send a data stream up and down through this COM port, just like you are able to do with a normal `Serial` port.

**If you want a bluetooth keyboard**:

What you *want* for seamless integration is a bluetooth module which natively exposes a "HID" (Human Interface Device) profile. Keyboard, mice and gamepads are examples of an HID.

There is a multitude of projects which use Arduino + Bluetooth HID module:

When you are a beginner you should buy the more expensive modules which don't require you to do any firmware hacking. Adafruit's product might work for you. As the description page says, you can connect a microcontroller's UART TX to the modules RX pin to send arbitrary keystrokes. You can then add a keyboard matrix, or lots of buttons, or whatever you desire to that microcontroller to make it trigger the keypresses you want.

This should get you started on your own research.

---
Tags: bluetooth, wifi, communication, android
---


# Question
Title: Arduino UNO SPI Serial Clock (Pin 13 SCK) gives no output, but Blink Example (Pin 13 LED) works
I was attempting to use an SPI library and DAC device (Library AD57X4) for the first time, when I realized that the Arduino UNO Pin 13 was not outputting a clock signal (something I expected it to do).

Using a serial analyzer I can sample at 16MHz, yet nothing comes out of UNO Pin 13 except maybe a very occasional noise blip. After no luck with the AD57X4 library, I wrote this simple program to try to get SPI clock signal on UNO Pin 13. Setting UNO Pin 13 to OUTPUT makes no difference.

```
#include <SPI.h>

void setup() {
  //pinMode(13, OUTPUT);
  SPI.begin();

}

void loop() {
  SPI.transfer(0x00);
}

```

I do get a signal on UNO Pin 11 (MOSI), frequency 381 kHz. This signal is due to `SPI.transfer(0x00);` , as it disappears when the line is removed. Although likely irrelevant to the question, I noticed some periodic 6us gaps every ~1ms on this UNO Pin 11 (MOSI) signal.

The Blink Example Works:

```
    // the setup function runs once when you press reset or power the board
void setup() {
  // initialize digital pin LED_BUILTIN as an output.
  pinMode(LED_BUILTIN, OUTPUT);
}

// the loop function runs over and over again forever
void loop() {
  digitalWrite(LED_BUILTIN, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);                       // wait for a second
  digitalWrite(LED_BUILTIN, LOW);    // turn the LED off by making the voltage LOW
  delay(1000);                       // wait for a second
}

```

I tried monitoring UNO ICSP header pin 3 (SCK), however there is no signal for either the SPI or Blink programs.

**UPDATE:** I switched over to an Arduino NANO that I had around and was able to get this output. I expected the clock to be high frequency and continuous for SPI. The MOSI output is the same 381 kHz that I observed earlier.

```
#include <SPI.h>

void setup() {
  pinMode(13, OUTPUT);
  SPI.begin();

}

void loop() {
  SPI.transfer(0x00);
}

```

**EDIT:** Here is a schematic of my circuit. I am using an EVAL-AD5754R Evaluation Board from Analog Devices. Here is a link to the AD5754 chip data sheet. I'm providing 5V power through the J7 terminal (via the UNO), and supplying the SPI connections through the J8 header. The EVAL-AD5754R board works perfectly via USB and their software, but now I am transitioning to controlling it through Arduino/SPI. As you can see I'm temporarily using a 12V battery for the analog voltage supply - this is until I build a regulated circuit. J8 DGND pins are shown unconnected on the schematic below, but I've tried connecting one of them to the UNO's GND to no effect.

This is the configuration of the linkers which act to configure the eval board:

This is an annotated table describing J8 header connections (UNO \<-\> EVAL-AD5754R):

# Answer
I can't reproduce that. Using your first test code:

```
#include <SPI.h>

void setup() {
  //pinMode(13, OUTPUT);
  SPI.begin();

}

void loop() {
  SPI.transfer(0x00);
}

```

I get this on the logic analyzer:

Also on my scope on pin 13:

As expected, a 4 MHz signal with gaps between the bytes.

---

> I expected the clock to be high frequency and continuous for SPI.

No, you get the clock when data is being transmitted and not at other times.

> Although likely irrelevant to the question, I noticed some periodic 6us gaps every ~1ms on this UNO Pin 10 (MOSI) signal.

That would be the Timer 0 interrupt kicking in (roughly every 1 ms) and thus interrupting your looping code for a few microseconds.

---

## Possible solution

Try enabling slave select (write LOW to pin 10). I think some versions of the logic analyzer ignore incoming data if the slave isn't selected.

In fact, pin 10 should be an output, otherwise the SPI hardware goes into slave mode. Some versions of the library might not set it to output.
> 3 votes

---
Tags: spi
---


# Question
Title: Can someone help me with my arduino and relay and switch?
This is my code. What i want to do is activate the relay when switchInNcPin is activate. I am using a switch (micro switch). It has COM NC and NO pins. Can you tell me what is wrong with my code? PROBLEM: The relay keeps clicking ON and OFF even though it is meant to wait 5000ms, activate, wait 3000ms, deactivate only once. Can you look at my code and help me?

# Answer
Maybe it's not the only problem, but at least:

```
int val = ...

```

and

```
if (val == "FLUSH")

```

do not match.

I assume you mean a digit here (0 or 9 to flush)?

Also, you should put your circuit in your question. A reason because of the 'flipping' is that your switch is not pulled down, and it results in undefined behavior.

Another thing you could add is debouncing, when a switch is clicked, it results in multiple 0/1 and 1/0 transitions (although your delay might help too).
> 1 votes

---
Tags: arduino-uno, programming, relay, electronics, switch
---


# Question
Title: Can you make it so, when your phone connects to the Hc-05 on a Arduino, a variable changes?
So whenever my phone gets close, and it connects to the Hc-05, the Arduino changes a variable? I want to avoid the use of apps, where the user has to do anything after first time connecting. The project is an automatic door opener, wherein the user for whatever reason can't use their hands, like if they have groceries in their hands.

Thank you for your time

# Answer
## Detecting successful connection with HC-05

The HC-05 can be configured to do what you are after.

Search for "POLAR" in the AT set documentation.

```
AT+POLAR=0,1

```

should be what you need as per their examples. Hook up **PI09** to your arduino and wait for it to go HIGH. You may even want to wake up your arduino with an hardware interrupt using that signal.

Depending on your package, this may require soldering to the HC-05 module. The datasheet features a pinout in that case. Be sure to checkout the manual of your breakout board first.
> 1 votes

---
Tags: arduino-uno, hc-05, android
---


# Question
Title: GSM library_ all examples ar working except GPRS?
i am using arduino uno and sim808. i connected the sim808 to pins 2,3 on arduino uno and used GSM library. i tested all examples: make and receive a call or messages. the part of GPRS initialization is not working after many tries in changing APN and pin number. i want to use the arduino as a webserver exactly as the example includded in the library. any one can help? thanks, https://www.arduino.cc/en/Reference/GSM

# Answer
> 1 votes
I had the same problem I solved it by moving the jumper wires on the shield(if you are using one) to SW serial. if that doesn't work try testing it with AT commands

---
Tags: gsm, web-server
---


# Question
Title: Problems encountered when trying to program Arduino UNO via esp8266 with ESP-Link
Basically my project requires to program Arduino Board wirelessly and I have found ESP-link which seems to match my purpose.

I tried to follow the instructions in documentations on the github page https://github.com/jeelabs/esp-link I am using Arduino UNO and ESP8266-01 by the way.

Flashing ESP-link into ESP8266 was successful. I followed the configuration page and successfully connect the ESP8266 to an MQTT Server. I connect my Arduino UNO to computer via USB Serial. Connected UNO to ESP8266 using the default settings (TX - TX, RX - RX, GPIO0 - RST). When I checked the Microcontroller Console page, I could send and received messages to/from UNO as well as resetting the UNO (I programmed blink sketch into my UNO, so I can see every time I reset it, it works)

However, the next step is not that successful. I tried to program UNO via ESP8266 but it does not work out quite well. There are several methods posted on the documentation https://github.com/jeelabs/esp-link/blob/master/UC-FLASHING.md and I have tried them to some extent.

1.Use Avrdude to program. Basically I copied the command when Arduino IDE programmed UNO using avrdude, and change the port to net:{localIP\_of\_ESP8266}:23 By the way I tested the code by set the port to local Serial port and it works I get the error and below is what cmd shows:

```
avrdude.exe: Version 6.3, compiled on Feb 17 2016 at 09:25:53
             Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
             Copyright (c) 2007-2014 Joerg Wunsch

             System wide configuration file is "C:\Users\ktz001\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino9/etc/avrdude.conf"

             Using Port                    : net:192.168.10.97:23
             Using Programmer              : arduino
             Overriding Baud Rate          : 115200
avrdude.exe: ser_drain(): read error: The parameter is incorrect

avrdude.exe: ser_drain(): read error: The parameter is incorrect

avrdude.exe: ser_drain(): read error: The parameter is incorrect

avrdude.exe: stk500_recv(): programmer is not responding
avrdude.exe: stk500_getsync() attempt 1 of 10: not in sync: resp=0xa4
avrdude.exe: stk500_recv(): programmer is not responding
avrdude.exe: stk500_getsync() attempt 2 of 10: not in sync: resp=0xa4
avrdude.exe: stk500_recv(): programmer is not responding
avrdude.exe: stk500_getsync() attempt 3 of 10: not in sync: resp=0xa4
avrdude.exe: stk500_recv(): programmer is not responding
avrdude.exe: stk500_getsync() attempt 4 of 10: not in sync: resp=0xa4
avrdude.exe: stk500_recv(): programmer is not responding
avrdude.exe: stk500_getsync() attempt 5 of 10: not in sync: resp=0xa4
avrdude.exe: stk500_recv(): programmer is not responding
avrdude.exe: stk500_getsync() attempt 6 of 10: not in sync: resp=0xa4
avrdude.exe: stk500_recv(): programmer is not responding
avrdude.exe: stk500_getsync() attempt 7 of 10: not in sync: resp=0xa4
avrdude.exe: stk500_recv(): programmer is not responding
avrdude.exe: stk500_getsync() attempt 8 of 10: not in sync: resp=0xa4
avrdude.exe: stk500_recv(): programmer is not responding
avrdude.exe: stk500_getsync() attempt 9 of 10: not in sync: resp=0xa4
avrdude.exe: stk500_recv(): programmer is not responding
avrdude.exe: stk500_getsync() attempt 10 of 10: not in sync: resp=0xa4
avrdude.exe: ser_drain(): read error: The parameter is incorrect

avrdude.exe done.  Thank you.

```
2. Then I tried the post http method. Basically I sent a post request to http://{IP\_of\_ESP8266}/pgm/sync in my case:

POST http://192.168.10.97/pgm/sync

I get 204 OK as response Then I tried:

GET http://192.168.10.97/pgm/sync

It returns "sync abandoned after 8 attempts" So I am stuck again

3. I tried also a small tool called avr-link https://gitlab.com/bc547-playground/avr-link Someone used it to program a pro mini via esp8266-01 which I think is close enough to my situation. I ran it on the powershell (I am using Windos 10 btw) The result is

> ```
> PS C:\> .\avr-link.exe flash --esp 192.168.10.97 --file C:/Blink.ino.hex
> AVR reset initiated...waiting for SYNC status
> .
> .
> .
> .
> .
> .
> .
> .
> .
> .
> .
> .
> .
> .
> .
> FATAL ERROR: Unexpected response:
> 00000000  73 79 6e 63 20 61 62 61  6e 64 6f 6e 65 64 20 61  |sync abandoned a|
> 00000010  66 74 65 72 20 38 20 61  74 74 65 6d 70 74 73     |fter 8 attempts|
>
> ```

4. using avrflash script. I am not sure how to run it in Windows OS so I did not use the script. If anyone could tell me about this, I appreciate it as well.

So to conclude, the problem seems to happen in getting sync after resetting the UNO (Although I am not 100% sure what does it mean - I am not familiar with the hardware process when flashing a UNO) There is a paragraph actually in documentation suggesting the problem. Here is the quote:

> If you are having trouble with the built-in programmer and see something like this:
>
> ./avrflash 192.168.3.104 blink.hex Error checking sync: FAILED to SYNC: abandoned after timeout, got: :\xF/\x00\xCj\xCz\xCJ\xCZ\xC\xAÜ\xC\xAä\xC\xAÜ\xC\xAä\xC\xBì\xC\xBô\xC\xBì\xC\xBô\xC\xAÜ\xC\xAä\xC
>
> the most likely cause is a baud rate mismatch and/or a bad connection from the esp8266 to the AVRs reset line. The baud rate used by esp-link is set on the uC Console web page and, as mentioned above, it will automatically try 9600, 57600, and 115200 as well. The above garbage characters are most likely due to optiboot timing out and starting the sketch and then the sketch sending data at a different baud rate than configured into esp-link. Note that sketches don't necessarily use the same baud rate as optiboot, so you may have the correct baud rate configured but reset isn't functioning, or reset may be functioning but the baud rate may be incorrect.

I tried to change the baud rate (both in command and microController Console page) but it still does not work. And in Arduino IDE it programs the board in 115200 so I should be okay with this baud rate imo, but anyway it did not work even when I change it. As for the reset connection, I could reset the UNO by pressing reset in the Microcrontroller Console page so It shouldn't be the problem (and I don't know how to change it anyway).

Thank you for your patience reading through all this crap.. So what do you think the problem is? Any suggestion would help :D

# Answer
> 1 votes
I tested it some weeks ago again after a year. The default upload from IDE should work, but mDNS in esp-link has now a bug and propagates the service only in AP mode so in STA mode the IDE doesn't show the network port.

from command line you can upload OTA with arduinoOTA tool used by IDE

example:

> /home/duro/.arduino15/packages/arduino/tools/arduinoOTA/1.1.1/bin/arduinoOTA -address 192.168.1.104 -port 80 -sketch /tmp/arduino\_build\_89762/Blink.ino.hex -upload /pgm/upload -sync /pgm/sync -reset /log/reset -sync\_exp 204:SYNC

If the mdns bug was fixed, for upload from IDE some settings must be added to board.txt

```
uno.upload.network.endpoint_upload=/pgm/upload
uno.upload.network.endpoint_sync=/pgm/sync
uno.upload.network.sync_return=204:SYNC
uno.upload.network.endpoint_reset=/log/reset
uno.upload.network.port=80

```

Uno WiFi uses an old version of esp-link so the settings and tutorial apply

# Answer
> 1 votes
I didn't test the avrdude network upload with esp-link. I used it with esp8266 AVRISP library. I configured the Arduino toolchain for network upload in platform.txt.

> tools.avrdude.upload.network\_pattern="{cmd.path}" "-C{config.path}" -p{build.mcu} -c{upload.protocol} "-Pnet:{serial.port}:328" "-Uflash:w:{build.path}/{build.project\_name}.hex:i"

Warning: the use case in my other answer uses the original setting of tools.avrdude.upload.network\_pattern

---
Tags: arduino-uno, esp8266
---


# Question
Title: Difference between Ciao REST server and Ciao REST connector and when to use each or the other
I'm reading the Ciao library and can't make out the difference between Ciao REST server and Ciao REST connector.

When is the connector suitable and at what point do I need the server?

This is a graphic of what im thinking to do:

# Answer
> 1 votes
I don't know about "Ciao" but generally a rest server answers requests from a client that is connecting via a rest connector. You client will use POST, GET, PUT, etc. to ask the server to provide a service. This could be as simple as "GET .\index.htm" or more likely posting information to be stored in a database.

The server will sit waiting for these requests and will have handling routines for each specific request and might supply a response.

---
Tags: library, ciao-library
---


# Question
Title: Need assistance with serial data between PC and Arduino Mega 2560
With help from a friend I have written a sketch for my Mega2560 that talks to a PC application via serial at 9600 baud. The PC application send an S which instructs the mega to send variable values without any delimiters. The PC application then creates a string from the data which is split to fill text boxes. Some elements of these text boxes can then be changed and clicking a button makes the PC application build a string, prefixed by R# and using \<\> as delimiters. It then tags an S on the end. This string is then sent to the Mega, which as it detects the R and # reads the delimited data into a 43 element array. Once it reads the S it then runs the send function again to confirm the changes.

As a stand alone program this works -

I then added in functions for reading four Ds18B20's, four DHT11's an RTC and displaying this on a TFT. These routines were added as separate contained voids and called in order from the main loop. When testing the serial it nolonger works. I either have to click on the get data button multiple times for it to read and display the info. Sending updated information back gets lost in transit (I've used a com port sniffer and it shows data passing out to the mega). Lastly, it's no longer accepting the updates when it does work - and having sent data back a second time it still reads the same as before the values were changed. When the coms fails the mega seems to have locked up, so it's stuck in the comms section, presumably as one of the IF/Then conditions hasn't been met because it's run out of data. But the routine wasn't changed from the standalone code which worked fine.

Hopefully this is as concise as you need but still has enough information to help diagnose the possible issue. I've tried extending delays in the PC application to see if it was that which was the cause, but even setting them to 5 seconds it still errors as described

Thanks Malcolm

Main loop from working standalone code

```
void loop ()
 {

loopcount = 0;

// Serial.println ("in main loop ");   // to show then program is looping the main code
// delay(3000);

 // your other 5seconds of code etc

 if(Serial.available()){             // test is S or R on comms

 int tbyte = Serial.read();

 if (tbyte == 'S'){
//  Serial.println ("send data");      // S received so Send data
  transmit ();
//   sendarray ();
   }

  if (tbyte == 'R'){                 // R received  so readstream of data
//    Serial.println ("recive data");
   readstream ();
    }
  }
 // sendarray ();
 }

 // end of main loop

```

Subroutines from the standalone code

```
// Subroutines --------------------------------------------------

 void readstream ()  {

  while (loopcount < 2000){
    if(Serial.available() > 0){

if  (serialFlag == 0) {

   inByte = Serial.read();

  if (inByte == 0X23 ){
    serialFlag = 1;
//    Serial.println ("# receieved so delimited data follows  ");
  }
}

  if  (serialFlag == 1) {
   processInput ();
    }
   }
  }
 }

// ProcessNumber-----------------

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

 dataIn[i]  = n;

 //Serial.println (i);
// Serial.print (dataIn[i]);

 i++;

// Serial.println (i);

 if ( i >= 43) {
//  Serial.println (" end of data....... return to main loop");
  serialFlag = 0;     // set flag back to zero
  i = 0;

 loopcount = 2222;   // stops the Serial While Loop, though better replaced by a timer
 }
 sendarray ();
 }

 // End of ProcessNumber-----------

 // ProcessInput--------------------

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

```

And the input to array

```
void sendarray ()
{
daytemp1 = (dataIn[0]);
daytemp1=daytemp1/10;
daytemp2 = (dataIn[1]);
daytemp2=daytemp2/10;
daytemp3 = (dataIn[2]);
daytemp3=daytemp3/10;
daytemp4 = (dataIn[3]);
daytemp4=daytemp4/10;

<snip>

```

# Answer
I'm sorry, I know you are new, but this is not a very easy to understand question, please keep reading though, I am trying to help. Your description of what you want your code to do is like trying to eat a dinner plate. Remember no one reading this has the knowledge of the problem that you do and a diagram or three speak a million words.

If it is failing to compile you need to post the source code and the compilation error. Without that information there is no point posting the question. The information on what is wrong is there, unfortunately you haven't used Google's Klingon to English translator. Seriously paste the compile errors into Google and you will get a stack of results, some of which will tell you what you have done wrong.

Your friend's code is not great. If that really is the code (rather than a space enforced edit), then I suspect it won't compile either, because its not valid C++. Also there are logic errors in it, you can make a number negative, but once you have you can't go positive.

**So, what can you do about it?**

Rule 1: You have to learn how to walk before running around the globe. Part of your requirement is to read Q or S from the serial line. So write a program of YOU OWN that does just that (I mean don't copy one of a web site/friend).

* Write a program that reads the serial line.
* When you press Q it prints "You pressed Q!"
* When you press S it prints "You pressed S!"
* When you press any other key it prints "You pressed something else"
* What happens when you press s or q?

Then build up step by step, keep back ups of everything, because you will break it at some point.

Other rules, which will contradict rule 1, will be available once you have mastered number one :)

Good luck and if you get stuck again, please post here again

```
 (small example code + error messages + output + expectations) = good post

```
> 2 votes

---
Tags: serial, arduino-mega
---


# Question
Title: Does the StringObject.reserve() function prevent memory fragmentation/leaks?
I'm currently writing and testing a professional Arduino application, I'm aware of the dangers of using the String class, so I began to implement C-style strings in some places, but it's just way harder using them to receive data from a Software Serial port that's variable in size and needs some manipulation.

I've upgraded from an Arduino Uno to a Leonardo so my current minimum SRAM usage is 1325 bytes (51%)

Here's the relevant part of my code:

```
String serialContents;
char emailChar[SIZEOF_ARRAY][SIZEOF_CHAR];

void setup(){
  serialContents.reserve(70);
  SerialOne.begin(9600);
}

void loop{

  if (SerialOne.available() > 0) //something is there to be read
  {
    serialContents = SerialOne.readStringUntil('\n'); //make a string of the characters coming on serial
  }

  if (serialContents.length() >= 60)
  {
   serialContents = ""; //ignore serial data
  }
 else{
  serialContents = cutString(serialContents); //some String manipulation, no adding only cutting
  serialContents.replace("@", "%40");
  serialContents.toCharArray(emailChar[count], 31);
  serialContents = ""; //String reset
}

```

So my question is, does something like this make my code unstable? Does the *reserve()* function help at all?

Edit: Here's the cutString() function

```
String cutString(String request) {

  int points = request.indexOf(':');

  if (request.substring(0, points) == "CHECKOUT")
  {
    modoPedido[count] = 'o'; //char array
  }
  else if (request.substring(0, points) == "CHECKIN")
  {
    modoPedido[count] = 'i';
  }

  request = request.substring(points + 1);

  return request;
}

```

# Answer
> 5 votes
Reserving space will *help* reduce memory fragmentation, but much of what else you are doing is swamping that small improvement you have made.

The biggest area of concern is your `cutString` function, which you have omitted from your code above. Passing a `String` as a parameter, modifying it, and then returning it again, ends up in new `String` objects being created and destroyed multiple times, which will make a mess of your heap.

Instead you should pass a String object by reference, and modify that object in-place. No need to return anything.

```
void cutString(String &theString) {
    // Modify theString here.
}

```

Of course, what you do in `cutString` could cause more problems - you should include that function in your code above so we can check it out.

---
Tags: serial, string, sram, memory
---


# Question
Title: How do I turn lights on & off manually along with home automation?
Need some help regarding HomeAutomation

I was doing my room automate via Arduino with the help of relay , but a little problem I am facing,that when I switched on the light via relay then I cannot turn it off via switch board manually ,the switch is now useless & I have tried two way switch but it's not a better solution. So please can anyone tell me how to solve this problem so that I can turn lights on manually & automatic too Thanks

# Answer
> 2 votes
You would need to create something like in the picture, one switch will be the relay.

---
Tags: home-automation
---


# Question
Title: Why do we need a transistor with a dc motor while we don't need one with a servo motor?
I was wondering why do we need to attach a transistor as we don't need one while we connect the Arduino with the servo motors. I am using mini servos.

# Answer
> 3 votes
A servo typically has 3 wires: Power, Ground, and Signal

Inside the servo are a bit of electronics that read the input signal duty cycle, the absolute position of the horn, and power the motor in forward or reverse accordingly. There are transistors inside the servo housing to handle the high current of the motor.

A standalone motor doesn't have any other control electronics that separate power from control inputs.

**EDIT:**

Just to clarify: the signal wire for the Servo doesn't carry any significant power. The IO pins on the Arduino should not be asked to provide more than 40mA of current, and the PWM signal to the servo falls under that current limit.

But to operate a motor, or other device which draws significant operating power, it (the motor) asks for much more than 40mA of current, which can burn out the IO pin and damage it forever. This is why a transistor or other "switch" is necessary: the device which switches the high-current on and off can itself be operated by a very low current.

# Answer
> 0 votes
Because a servo contains a driver circuit that controls the motor portion, whereas a motor doesn't. The transistor is the (simplistic) driver circuit for the motor.

---
Tags: arduino-uno, motor, servo
---


# Question
Title: Wemos mini pro switch power from servo with mosfet bs170
I got a servo connected to a wemos/arduino with a capacitor(470uf). Before I didn\`t use a cap.

Now with the cap the device use to much power while sleeping(capacitor on the servo). I want to switch off the power to the servo with a MOSFET. I tried this with a BS170 N channel MOSFET. There is a youtube movie with the same settings except for the mainboard. They use an Arduino uno instead a wemos.

When I test the circuit with a led everything is working. When I use a servo instead a led, nothing happen. There is a little sound from the servo(I think not enough voltage).

When I check the voltage without anything hooked on the drain of the mosfet the output is perfect(5V). If I connect a led or a servo the voltage will drop to 3v.

Wemos mini pro has 3.3v output on the gpio pins.

Can someone explain me what I doing wrong? I saw and read some articles about Mosfet. I think it\`s not clear enough for me.

# Answer
My supposition:

The MOSFET's R(DSON) is too high and causing a large voltage drop.

A servo uses more current than a little LED. That current passing through the MOSFET, with an R(DSON) of potentially up to 5Ω, reduces the voltage available to the servo, causing it to not work. Further more, ground for the servo is raised up above the real ground level adding an offset into the logic levels that could cause communication issues.

Suggestion: Pick a MOSFET with a lower R(DSON) (ideally measured in the milli-ohms), and a lower V(GS) threshold (something around 1-2V max would be good).
> 0 votes

---
Tags: esp8266, power, servo, mosfet
---


# Question
Title: Using digital pins 0/1 on Arduino Due when writing/reading over serialUSB port
I am aware that you cannot use pins 0 and 1 as digital pinouts when communicating over serial via serial.print(), but what if you are using the native port on the due with serialUSB.write()?

Thanks

# Answer
> 1 votes
Yes, you can use 0/1 while using the native USB. The two are completely separate.

---
Tags: serial, arduino-due
---


title: Does millis() work inside a function?

text:
# Question
Title: Does millis() work inside a function?
So I know that millis() doesn't work how it's suppose to if you use it in an interrupt but lets say we have a code that looks like below, will millis() work properly or how it behaves in an interrupt? Do I need to use the delay() instead of millis() when I'm outside of void loop() ?

To clarify, I understand how millis() behaves in an interrupt and why delay() doesn't work in an interrupt.

```
const int ledPin =  LED_BUILTIN;// the number of the LED pin

// Variables will change:
int ledState = LOW;             // ledState used to set the LED

// Generally, you should use "unsigned long" for variables that hold time
// The value will quickly become too large for an int to store
unsigned long previousMillis = 0;        // will store last time LED was updated

// constants won't change:
const long interval = 1000;

void setup() {
 pinMode(ledPin, OUTPUT);
}
void loop(){
blink();
}
void blink(){
  unsigned long currentMillis = millis();

  if (currentMillis - previousMillis >= interval) {
    // save the last time you blinked the LED
    previousMillis = currentMillis;

    // if the LED is off turn it on and vice-versa:
    if (ledState == LOW) {
      ledState = HIGH;
    } else {
      ledState = LOW;
    }

    // set the LED with the ledState of the variable:
    digitalWrite(ledPin, ledState);
  }
}

```

# Answer
Millis is driven by an interrupt. The reason it doesn't "work" from inside an interrupt is that you can't have two interrupts running at the same time. So when your interrupt is running the interrupt that makes millis count can't run.

Millis does work in an interrupt as long as all you want is to record a single point in time. If you do anything that relies on millis changing within the lifetime of the interrupt it will break. That is why delay is bad in interrupts.

So from that you can see that it's only when in an interrupt that things can go awry. Everywhere else, as long as interrupts are enabled, both millis and delay work fine.

After all, loop is just a function called by main, and main is just a function called by \_startup... Etc...
> 3 votes

---
Tags: millis
---


# Question
Title: Problem converting character array into integer in arduino using atoi function
I'm receiving a character string from a radio signal on my arduino. This character string consists of four character digits, which I want to convert into an integer. The four digit sequence may contain zeros padded in front of the integer, such as '0025' to represent the integer 25.

So, I saved this character string onto a character array of length 5:

```
char left[5];

```

The first four characters in this array have the four character digits received in the radio signal. I have a fifth character which I set to the character '\0' to signify a termination character.

The message received is any number ranging from 0 to 1023, but I need to use values between -255 and +255. To convert the character into an integer, I use the atoi function as follows:

```
int leftpower = (atoi(left)-512)/2;

```

When I print out the variable "leftpower", it seems to give the correct value. I'm even able to use "leftpower" in an if then statement as follows:

```
if (myvalue<0){
  Serial.println("inside the if-then statement");
  digitalWrite(in1,HIGH);
  digitalWrite(in2,LOW);
  //analogWrite(enableA,myvalue);
}

```

So, as far as I can tell, everything is working fine. I want to use "myvalue" as a command to an analogWrite function call as follows:

```
//analogWrite(enablePinA,myvalue);

```

However, something strange happens when I uncomment this line. WHen I uncomment it, the program seems to hang at the if statement, as if it paused at that point and neither crashes nor gives any error. The program no longer prints out "inside the if-then statement" at all, but no other errors seem to be detected. No other compilation or runtime errors.

The strange thing about this is that if I change "leftpower" to a number like 223 as follows:

```
analogWrite(enablePinA,223);

```

the program works as I expected it to, producing a motor command. So, I know the problem is not with my wiring. The problem seems to be associated with the variable "leftpower", which was converted from a character array to an integer using the atoi function.

What exactly is going on? What problem is actually occurring and how can I fix it? Any help would be greatly appreciated!

For reference, my code is posted below:

```
#include <RH_ASK.h> //radiohead library to read RF signals
#include <SPI.h> //just because radiohead library depends on it
RH_ASK driver; //default: transmitter data pin goes to arduino pin 11
int in1=4;
int in2=5;
int in3=6;
int in4=7;

int enableA = 9;
int enableB = 10;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  if (!driver.init()){
    Serial.println("receiver init failed");
  }
  pinMode(enableA,OUTPUT);
  pinMode(enableB,OUTPUT);
  pinMode(in1,OUTPUT);
  pinMode(in2,OUTPUT);
  pinMode(in3,OUTPUT);
  pinMode(in4,OUTPUT);
}
int leftpower,rightpower;
void loop() {
  // put your main code here, to run repeatedly:
  uint8_t buf[8];
  uint8_t buflen = sizeof(buf);
  if (driver.recv(buf, &buflen)){ //non-blocking
    //Convert buf (unsigned integer) to a character array
    char temp[8]="";
    sprintf(temp,"%s",(char*) buf);
    //Four characters for first integer, four for the second integer
    //So, we have to split them into two parts (left and right)
    char left[5]="";
    for (int i=0; i<4; i++){
      left[i]=temp[i];
    }
    //Put a terminating character at the end
    left[4]='\0';
    char right[5]="";
    for (int i=0; i<4; i++){
      right[i]=temp[4+i];
    }
    //Put a terminating character at the end
    right[4]='\0';
    leftpower=(int) (atoi(left)-512)/2;
    rightpower=(int) (atoi(right)-512)/2;
    constrain(leftpower,-255,255);
    constrain(rightpower,-255,255);
    Serial.println(leftpower);
    Serial.println(rightpower);
    if (leftpower<0) {
      //switch H-bridge to forward direction
      Serial.println("inside the if-then statement");
      digitalWrite(in1,HIGH);
      digitalWrite(in2,LOW);
      analogWrite(enableA,255);
      Serial.println("got this far");
    }
    else {
      digitalWrite(in1,LOW);
      digitalWrite(in2,HIGH);
      analogWrite(enableA,255);
    }
//    if (rightpower<0) {
//      //switch H-bridge to forward direction
//      digitalWrite(in3,LOW);
//      digitalWrite(in4,HIGH);
//      analogWrite(enableA,abs(rightpower));
//    }
//    else {
//      digitalWrite(in4,LOW);
//      digitalWrite(in3,HIGH);
//      analogWrite(enableA,abs(rightpower));
//    }

  }
}

```

# Answer
> 3 votes
You have a few issues here.

> `if (driver.recv(buf, &buflen)) { ... }`

You don't check the value of `buflen` after calling the `recv()` method. ~~I didn't read the doc of the RH\_ASK library you are using. Are you sure it does preserve message boundaries? I let you check. If it only transports bytes (rather than full messages), then you will have to repeatedly `recv()` until you have a full message.~~

**Edit**: Looked at the doc. The communication is indeed packetized, so you don't need to collect the message chunk by chunk. It is, however, still a good idea to check whether the received size is what you expect:

```
if (driver.recv(buf, &buflen) && buflen == 8) { ... }

```

> `sprintf(temp,"%s",(char*) buf);`

This is a serious bug, and most probably the reason your program behaves inconsistently. Here `buf` is **not** a NUL-terminated string. The `sprintf()` function will copy bytes from `buf` into `temp` until it finds a NUL. It can potentially overwrite the receiving buffer and start clobbering whatever happens to be past `temp` in your memory. This is called “memory corruption” and can lead to any kind of unpredictable behaviors.

Note that the whole copying you do here serves no useful purpose. You can work from the initial buffer to start with:

```
char left[5];
memcpy(left, buf, 4);
left[4] = '\0';
char right[5];
memcpy(right, buf+4, 4);
right[4] = '\0';

```

> `constrain(leftpower,-255,255);`

You are implicitly discarding the value computed by `constrain()`. You probably mean

```
leftpower = constrain(leftpower, -255, 255);

```

---
Tags: c, data
---


title: Proto Threading 2 functions

text:
# Question
Title: Proto Threading 2 functions
I would like to proto thread two functions to run pseudo-simultaneously. One function takes the input of a force sensor and moves a servo accordingly, and the other takes the input of a gyroscope (MPU650) and moves a different sensor accordingly. Below is my code where I attempt to use timers to handle this.

```
#include <Wire.h>
#include <Servo.h>
#include "I2Cdev.h"
#include "MPU6050.h"
#include "Servo.h"

int FSR_Pin = A0;
bool isClosed = false;
unsigned long lastMillis = 0;
unsigned long lastMillis2 = 0;

MPU6050 mpu;

int16_t ax, ay, az;
int16_t gx, gy, gz;

Servo handServo;

Servo wristServo;

int pos = 0;
int val;
int prevVal;

void setup(){
  Serial.begin(9600);
  handServo.attach(9);

  Wire.begin();
  Serial.begin(38400);

  Serial.println("Initialize MPU");
  mpu.initialize();
  Serial.println(mpu.testConnection() ? "Connected" : "Connection failed");
  wristServo.attach(8);
}

void handleFingers () {
  int FSRReading = analogRead(FSR_Pin);
  Serial.println(FSRReading);

if (FSRReading > 9) {
 if (pos < 90) {
     handServo.write(pos);
      pos ++;
 }
  isClosed = true;

} else if (isClosed == true && FSRReading < 10) {
  pos = 0;
  handServo.write(pos);
  isClosed = false;
}
}

void handleWrist() {
  mpu.getMotion6(&ax, &ay, &az, &gx, &gy, &gz);

    val = map(ay, -17000, 17000, 0, 179);
    if (val != prevVal)
    {
        wristServo.write(val);
        prevVal = val;
    }

}

void loop(){
  if (millis() - lastMillis > 1000) {
    handleFingers ();
  }
   lastMillis = millis();

 if (millis() - lastMillis2 > 1000) {
    handleWrist();
  }
   lastMillis2 = millis();

}

```

When I run the code above, the servos move a few degrees each and then do nothing at all. It appears that none of the servos are responsive to the sensor feedback. Something is wrong with my timing or my method of proto threading. I would really appreciate your help, thanks.

# Answer
> 1 votes
Jot provided the answer in a comment: you are updating `lastMillis` in the wrong place. The correct way is:

```
if (millis() - lastMillis >= 1000) {
    handleFingers();
    lastMillis = millis();
}

```

Optionally, you can use `lastMillis += 1000` instead of `lastMillis = millis()` if you want to precisely control the *average* (rather than *minimum*) update period.

Just to elaborate a bit, the idiom I like for doing this kind of stuff is as follows:

```
const unsigned long FINGER_UPDATE_PERIOD = 1000;
const unsigned long WRIST_UPDATE_PERIOD  = 1000;

void loop() {
    unsigned long now = millis();

    // Handle the fingers.
    static unsigned long last_finger_update;
    if (now - last_finger_update >= FINGER_UPDATE_PERIOD) {
        last_finger_update = now;
        handleFingers();
    }

    // Handle the wrist.
    static unsigned long last_wrist_update;
    if (now - last_wrist_update >= WRIST_UPDATE_PERIOD) {
        last_wrist_update = now;
        handleWrist();
    }
}

```

Note that:

* The update periods are constants defined at the top of the program.
* `millis()` only needs to be called once per loop iteration: if the loop takes many milliseconds to run you would be doing something wrong anyway.
* `last_finger_update` and `last_wrist_update` stand for `lastMillis` and `lastMillis2`, which are very poor naming choices.
* These two variables are local to `loop()`, as they are not needed anywhere else.
* These variables are also declared `static`, which means they are implicitly initialized to 0 and they preserve their values from call to call.
* I update the timing variables before doing the actual work. This helps keeping all the timing code together, which makes the code clearer, especially if the actual work takes many lines of code (e.g. you do the work inline instead of having it in separate functions).

Some people prefer using libraries for this kind of proto-threading. If you use the ArduinoThread library, the same could be written as:

```
const unsigned long FINGER_UPDATE_PERIOD = 1000;
const unsigned long WRIST_UPDATE_PERIOD  = 1000;

Thread updateFingers(handleFingers, FINGER_UPDATE_PERIOD);
Thread updateWrist(handleWrist, WRIST_UPDATE_PERIOD);
StaticThreadController<2> scheduler(&updateFingers, &updateWrist);

void loop() {
    scheduler.run();
}

```

---
Tags: programming
---


# Question
Title: Sleep power down mode with change interrupt
I want to use to use an IR sensor as an interrupt to wake up my Arduino Uno R3 from the deep sleep power mode and then go back to sleep after changing the state of the relay.

Lets say if I press a button on the remote and the relay is on LOW mode, the relay is turned to HIGH mode and vice versa.

```
#include <avr/interrupt.h>
#include <avr/sleep.h>
#include <IRremote.h>

/* Sleep Demo
------------

int relayPin = 8;            // LED connected to digital pin 13
int irPin = 2;            // active LOW, ground this pin momentary to wake up
int sleepStatus = 0;        // variable to store a request for sleep
volatile byte state = LOW;

IRrecv irrecv(irPin);
decode_results results;

void setup()
{
  pinMode(relayPin, OUTPUT);         // sets the digital pin as output
  pinMode(irPin, INPUT);
  irrecv.enableIRIn(); // Start the receiver

  /* Now is time to enable a interrupt. In the function call
     attachInterrupt(A, B, C)
     A   can be either 0 or 1 for interrupts on pin 2 or 3.

     B   Name of a function you want to execute while in interrupt A.

     C   Trigger mode of the interrupt pin. can be:
                 LOW        a low level trigger
                 CHANGE     a change in level trigger
                 RISING     a rising edge of a level trigger
                 FALLING    a falling edge of a level trigger

     In all but the IDLE sleep modes only LOW can be used.
  */

  attachInterrupt(0, wakeUpNow, CHANGE); // use interrupt 0 (pin 2) and run function
  // wakeUpNow when pin 2 gets LOW
}

void sleepNow()         // here we put the arduino to sleep
{
  /* Now is the time to set the sleep mode. In the Atmega8 datasheet
     http://www.atmel.com/dyn/resources/prod_documents/doc2486.pdf on page 35
     there is a list of sleep modes which explains which clocks and
     wake up sources are available in which sleep modus.

     In the avr/sleep.h file, the call names of these sleep modus are to be found:

     The 5 different modes are:
         SLEEP_MODE_IDLE         -the least power savings
         SLEEP_MODE_ADC
         SLEEP_MODE_PWR_SAVE
         SLEEP_MODE_STANDBY
         SLEEP_MODE_PWR_DOWN     -the most power savings

     For now, we want as much power savings as possible,
     so we choose the according sleep modus: SLEEP_MODE_PWR_DOWN

  */
  set_sleep_mode(SLEEP_MODE_IDLE);   // sleep mode is set here

  sleep_enable();              // enables the sleep bit in the mcucr register
  // so sleep is possible. just a safety pin

  /* Now is time to enable a interrupt. we do it here so an
     accidentally pushed interrupt button doesn't interrupt
     our running program. if you want to be able to run
     interrupt code besides the sleep function, place it in
     setup() for example.

     In the function call attachInterrupt(A, B, C)
     A   can be either 0 or 1 for interrupts on pin 2 or 3.

     B   Name of a function you want to execute at interrupt for A.

     C   Trigger mode of the interrupt pin. can be:
                 LOW        a low level triggers
                 CHANGE     a change in level triggers
                 RISING     a rising edge of a level triggers
                 FALLING    a falling edge of a level triggers

     In all but the IDLE sleep modes only LOW can be used.
  */

  attachInterrupt(0, wakeUpNow, CHANGE); // use interrupt 0 (pin 2) and run function
  // wakeUpNow when pin 2 gets LOW

  sleep_mode();                // here the device is actually put to sleep!!
  //

  sleep_disable();             // first thing after waking from sleep:
  // disable sleep...
  detachInterrupt(0);          // disables interrupt 0 on pin 2 so the
  // wakeUpNow code will not be executed
  // during normal running time.
  delay(1000);                 // wat 2 sec. so humans can notice the
  // interrupt.
  // LED to show the interrupt is handled
}

void wakeUpNow()        // here the interrupt is handled after wakeup
{
  //execute code here after wake-up before returning to the loop() function
  // timers and code using timers (serial.print and more...) will not work here.
  if (irrecv.decode(&results)) {
    if (results.value == 0xff629d) {
      state = !state;
      digitalWrite(relayPin, state);
    }
  }
}

void loop()
{

  sleepNow();                      // sleep function called here
}

```

The Arduino never seems to wake up from sleep when I use the CHANGE interrupt. But if I use with the IDLE sleep mode, it is working.

Can somebody please help me how to fix this ? Also will this code work with an Arduino Pro Mini or an ATTiny45?

# Answer
> 3 votes
You actually don't need to to worry about interrupts *at all* for this project. The IRremote library is itself based on a timer interrupt. As soon as you `irrecv.enableIRIn()`, you start receiving a continuous stream of interrupts... in addition to the timer interrupt initially set up by the Arduino core.

If you want to save some power, you can call `sleep_mode()` once in your loop. That's it. No need to `sleep_enable()` or `sleep_disable()`, as these are already taken care of by `sleep_mode()`. No need to `set_sleep_mode()` either, as the default sleep mode (IDLE) is the only one that is appropriate for you. No need to `attachInterrupt()`, as you will be waken up by these timer interrupts anyway.

Removing all the cruft, your posted code would become:

```
#include <avr/sleep.h>
#include <IRremote.h>

const int relayPin = 8;
const int irPin = 2;
IRrecv irrecv(irPin);

void setup()
{
    pinMode(relayPin, OUTPUT);
    pinMode(irPin, INPUT);
    irrecv.enableIRIn();
}

void loop()
{
    decode_results results;
    if (irrecv.decode(&results)) {
        if (results.value == 0xff629d) {
            static byte state = LOW;
            state = !state;
            digitalWrite(relayPin, state);
        }
        irrecv.resume();
    }

    // Sleep until next interrupt.
    sleep_mode();
}

```

# Answer
> 0 votes
> The Arduino never seems to wake up from sleep when I use the CHANGE interrupt.
>
> ```
>   attachInterrupt(0, wakeUpNow, LOW); // use interrupt 0 (pin 2) and run function
>
> ```

That's not a CHANGE interrupt, it's a LOW interrupt. Please post code that supports what you say in the question.

---

> ```
> void wakeUpNow()        // here the interrupt is handled after wakeup
> {
>   //execute code here after wake-up before returning to the loop() function
>   // timers and code using timers (serial.print and more...) will not work here.
>   if (irrecv.decode(&results)) {
>     if (results.value == 0xff629d) {
>       Serial.println("UP");
>       state = !state;
>       digitalWrite(relayPin, state);
>     }
>   }
> }
>
> ```

**Don't** do serial prints inside an ISR. In particular, a LOW interrupt keeps being called continuously while the interrupt pin is low.

> // timers and code using timers (serial.print and more...) will not work here

You *even have a comment* saying that the code won't work, yet you posted it in your question.

---
Tags: arduino-uno, interrupt, sleep
---


# Question
Title: handling array from post data on espwebserver
I think I have a supplement question. If irrelevant , then sorry in advance.

I have nested array in post like: from apache web server page index.php

$\_POST\['colorsarray'\]\[0\] = '#ff0000';
$\_POST\['colorsarray'\]\[1\] = '#2d67ea';
$\_POST\['colorsarray'\]\[3\] = '#7cf325';
$\_POST\['mode'\] = 'none';
$\_POST\['singlecolour'\] = '#ff0000';

Can you suggest me how to assign this array (coloursarray) directly to another array in espwebserver. In other use cases , only the list (length) of array will increase and is not know until the variable arrives from client.

Thanks in advance.

# Answer
> 1 votes
The ability for PHP to do this is special to PHP. The PHP program parses the field names as PHP arrays if they are named thus:

```
<form ....>
<input name="[colorsarray][0]" value="#ff0000" />
<input name="[colorsarray][1]" value="#2d67ea" />
<input name="[colorsarray][2]" value="#000000" />
<input name="[colorsarray][3]" value="#7cf325" />
[...]
</form>

```

But since the ESP8266's core doesn't use PHP or understand PHP arrays, you will have to use the literal field name `[colorsarray][3]`, parse it yourself, and determine at run-time the length of the array and how much memory is needed, etc.

---
Tags: esp8266, nodemcu
---


# Question
Title: Why do people complain when I call my functions voids?
I have posted questions about "my void loop" or "my void setup" and people complain that they aren't really voids. But they are! See this example code:

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

void loop() {
  digitalWrite(13, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);              // wait for a second
  digitalWrite(13, LOW);    // turn the LED off by making the voltage LOW
  delay(1000);              // wait for a second
}

```

Clearly `setup` and `loop` are voids because they have the word `void` right before them!

---

*Note: this is a reference question.*

# Answer
> 7 votes
This is an easy mistake for a beginner to C++ to make. Let's look at other languages, like PHP:

```
function add ($a, $b)
  {
  return $a + $b;
  }

```

Or Lua:

```
function add (a, b)
  return a + b
end

```

Or JavaScript:

```
function add (a, b)
  {
  return a + b;
  }

```

Or VBscript:

```
Function add (a, b)
  add = a + b
End Function

```

All those languages have the word "function" there to indicate that you are declaring a function.

---

So what does C++ look like:

```
int add (int a, int b)
  {
  return a + b;
  }

```

So this must be an "int" right? Or what if it doesn't return a value?

```
void loop ()
  {
  }

```

Now it's a "void"? Kind of a weird name for a function!

Actually `int` and `void` in these examples are not weird names for functions. They are the **return types** of those functions. `int add (int a, int b)` is a **function** that returns an int. And `void loop ()` is a **function** that returns nothing.

The C++ compiler can deduce when it is seeing a function declaration from some clues:

* A return type (eg. int, float, long)
* A name (the function name)
* Some parentheses (for the function arguments)

Think of the word `function` as being there in spirit:

```
int [function] add (int a, int b)
    ^^^^^^^^^^   <-- don't actually type this!
    {
    return a + b;
    }

```

# Answer
> 0 votes
I think if you use a phrase like " my int a or my CustomType a " people would interpret those phrases to mean that you have a variable `a` that is an instance of an `int` or a `CustomType`.

According to http://en.cppreference.com/w/cpp/language/types you can't have an object or reference of type `void`.

If you have a phrase like "my void setup", I think most people would try to read that as implying you have a variable `setup` of type `void`, which I don't think makes sense, to most people.

What you actually have is this:

```
void setup() {
...
}

```

I think most people would phrase this as "my function setup, which takes no arguments are returns nothing".

---
Tags: programming, c++, faq
---