# Question
Title: Reading a monochromatic bitmap with Arduino for plotting
Complete newbie here.

I am following this thread: How to read bitmap image on Arduino

Specifically the third reply from : frarugi87 in my attempt to plot a monochromatic bitmap image with a plotter device. Basically: bitmap\>SD card board\>arduino uno\> plotted image

I attempted to modify their code to work with monochromatic bitmaps and removed the print to file function:

```
    // MODIFIED CODE FROM BELOW CONTRIBUTOR

    // (c) Michael Schoeffler 2016, http://www.mschoeffler.de

    #include <SD.h> //Load SD library
    int chipSelect = 4; //chip select pin for the MicroSD Card Adapter
    File file; // file object that is used to read and write data

int32_t readNbytesInt(File *p_file, int position, byte nBytes)  // FUNCTION WHICH READS A DETERMINED AMMOUNT OF BYTES INTO A SINGLE VARIABLE
{
    if (nBytes > 4)
        return 0;

    p_file->seek(position);

    int32_t weight = 1;
    int32_t result = 0;
    for (; nBytes; nBytes--)
    {
        result += weight * p_file->read();
        weight <<= 8;
    }
    return result;
}

    void setup() {
      Serial.begin(9600); // start serial connection to print out debug messages and data

      pinMode(chipSelect, OUTPUT); // chip select pin must be set to OUTPUT mode
      if (!SD.begin(chipSelect)) { // Initialize SD card
        Serial.println("Could not initialize SD card."); // if return value is false, something went wrong.
      }

      if (SD.exists("bitmap.bmp")) { // if "bitmap.bmp" exists, say so
        Serial.println("Found The Bitmap File.");

      }

      file = SD.open("bitmap.bmp", FILE_READ);   // open the file to an object for reading

      // DETERMINE HOW LARGE THE BITMAP FILE IS
      int howmany;
      howmany = file.available();
      Serial.println(howmany);    // print the how large the file is

      // DETERMINE STARTING IMAGE ARRAY LOCATION IN THE BITMAP FILE
      int32_t dataStartingOffset = readNbytesInt(&file, 0x0A, 4);
      Serial.println("The starting location in the fiile is...");
      Serial.println(dataStartingOffset);

      // DETERMINE THE IMAGE HEIGHT AND WIDTH
      int32_t imgwidth = readNbytesInt(&file, 0x12, 4);
      Serial.println("The image width is the following pixels:");
      Serial.println(imgwidth);
      int32_t imgheight = readNbytesInt(&file, 0x16, 4);
      Serial.println(imgheight);

      // MODIFIED CODE. DOES THE COLOR DEPTH LOCATION WORK IN THE BITMAP AND DOES IT GIVE CORRECT INFO ABOUT THE FILE?
      int16_t pixelsize = readNbytesInt(&file, 0X1C, 2);
      if (pixelsize != 24)
      {
        Serial.println("This image is most definitely not 24 bpp");
        Serial.println(" it is actually a depth of :");
        Serial.println(pixelsize);

      }

       file.seek(dataStartingOffset);   //skip bitmap header and go directly to the image data array.

     /*  for(int32_t i = 0; i < imgheight; i ++) {
        for (int32_t j = 0; j < imgwidth; j ++) {
            B = file.read();
            Serial.println("height and width location from bottom");
            Serial.println(i);
            Serial.println(j);
            Serial.println("B");
            Serial.println(B);
        }
        Serial.println("height advance");
    }

*/
      int B;

      B = file.read();
      Serial.println(B, BIN);
      B = file.read();
      Serial.println(B, BIN);

      B = file.read();
      Serial.println(B, BIN);
      B = file.read();
      Serial.println(B, BIN);

      B = file.read();
      Serial.println(B, BIN);
      B = file.read();
      Serial.println(B, BIN);

      B = file.read();
      Serial.println(B, BIN);
      B = file.read();
      Serial.println(B, BIN);

            B = file.read();
      Serial.println(B, BIN);
      B = file.read();
      Serial.println(B, BIN);

      B = file.read();
      Serial.println(B, BIN);
      B = file.read();
      Serial.println(B, BIN);

      B = file.read();
      Serial.println(B, BIN);
      B = file.read();
      Serial.println(B, BIN);

      B = file.read();
      Serial.println(B, BIN);
      B = file.read();
      Serial.println(B, BIN);

        B = file.read();
      Serial.println(B, BIN);
      B = file.read();
      Serial.println(B, BIN);

            B = file.read();
      Serial.println(B, BIN);
      B = file.read();
      Serial.println(B, BIN);

      B = file.read();
      Serial.println(B, BIN);
      B = file.read();
      Serial.println(B, BIN);

      B = file.read();
      Serial.println(B, BIN);
      B = file.read();
      Serial.println(B, BIN);

      B = file.read();
      Serial.println(B, BIN);
      B = file.read();
      Serial.println(B, BIN);

            B = file.read();
      Serial.println(B, BIN);
      B = file.read();
      Serial.println(B, BIN);

      B = file.read();
      Serial.println(B, BIN);
      B = file.read();
      Serial.println(B, BIN);

      B = file.read();
      Serial.println(B, BIN);
      B = file.read();
      Serial.println(B, BIN);

      B = file.read();
      Serial.println(B, BIN);
      B = file.read();
      Serial.println(B, BIN);

        B = file.read();
      Serial.println(B, BIN);
      B = file.read();
      Serial.println(B, BIN);

    file.close();

    Serial.println("done write");

    }

```

But when I read a 16x16 monochromatic bitmap: see below

At what I assume is the color table starting location (given by dataStartingOffset variable). I get strings two bytes of correct color information, followed by two bytes of just...zeros. Is this a bitmap formatting thing?

Serial output for 16x16 bitmap looks like this:(only up to 9 of the 16 lines starting from the bottom)

> Found The Bitmap File. 126 The starting location in the file is... 62 The image width is the following pixels: 16 16 This image is most definitely not 24 bpp it is actually a depth of : 1 1111111 11111110 0 0 11111111 11111111 0 0 11111111 11111111 0 0 11111111 11111111 0 0 11111111 11111111 0 0 11111111 11111111 0 0 11111111 11111111 0 0 11111111 11111111 0 0 1111111 11111110 0 0 done write

And when I try to read a bitmap that is around 200 x 200 pixels, I get very strange height and width numbers that are negative and my above code does not work at all! Does a 16x16 bitmap have different byte structure formatting than a 200x200?

Any help is appreciated. Again, I am a complete newbie here. I am just trying to figure out how to read a bitmap.

# Answer
Bitmap files (.BMP) have to have a row size that is a multiple of 4 bytes. Any extra space in a row has to be padded with 0.

Since your rows are 16 pixels wide that equates to 2 bytes. That's not a multiple of 4, so it is padded with to bytes of 0 to make it a multiple of 4.

Your code needs to take that into account and know that if it hasn't read a multiple of 4 bytes then to read enough "dummy" bytes to get to the start of the next row.

Also, note that BMP files are the only files in the known universe where the image data is stored upside down (starting lower-left corner instead of upper-left corner).
> 0 votes

---
Tags: arduino-uno
---


# Question
Title: Use 2 DHT22 AND PASS THE DATA TO SD Error File data does not exsist
anyone can help me please to fix this error when I try to compilate says File does not exsist. It would be great if anyone can post the entirely code.

Link of code below if anyone can help me please:

https://create.arduino.cc/editor/Jawad2001/5ea57339-7ca1-4f8d-ab00-f4f1aa639209/preview

error: expected')' before 'f'

Sorry I'm new at this sorry for the annoyances.

Thanks For all your Help.

# Answer
> 1 votes
Here are several things I can see from your code that cause most of the error messages.

**1)** You declare

```
File data_txt;
File data2_txt;

```

but you later use `data_file` and `data_file2`. This is why you see the "not declared in this scope" errors.

**2)** You do not properly define the functions `getData()` and `getData2()`. You start with the definition of `getData2()` inside the function `getData()`.
First finish the function `getData()` by closing all brackets you opened and then define the function `getData2()`, like this:

```
void getData() {
//the code of getData() goes here....
}

void getData2() {
//the code of getData2() goes here....
}

```

**3)** I assume you want to write to `data_file` in `getData()` and to `data_file2` in `getData2()`?! Nevertheless, you also use `data_file` in `getData2()`.

**Update after your edit:**

Regarding the compilation error, you do not open a curly bracket

**{**

after `getData2()`.

However, there are several other issues that will lead to problems, even if it finally does compile without problems.

---
Tags: sensors, sd-card, temperature-sensor, compilation-errors, error
---


# Question
Title: How to initialize digital output pin as low
I need to define a pin as output for relay module but when i do it in setup section, relay is activated (low - 0) automatically then i deactivated immediately with coding `digitalWrite(pin, 1)` but this issue results the relay is activated then deactivated within miliseconds. But I want to know that is it possible to define a pin as output but low in default.

```
void setup(){
  pinMode(pin,OUTPUT);
  digitalWrite(pin,1);
}

void loop(){
  if(start_relay){
    digitalWrite(pin, 0);
  }
}

```

# Answer
> 2 votes
There are two solutions:

1. Use the pin as a open-collector pin as in the answer of VE7JRO.
Switch the pin between input (high) and output with low. I prefer to use the INPUT\_PULLUP.
2. Write the output value before setting the pinMode.

All the microcontrollers of the AVR family (ATtiny and ATmega chips) allow to set the output value before setting the pin as output. This will enable the pullup resistor, but when it is done in the right order, that is fine.

Because this is a common way to use the microcontrollers and processors, the Arduino libraries allow to use that. The Arduino libraries for the SAMD processors (Arduino Zero, M0 and MKR) are written to allow that as well.

```
void setup() {
  digitalWrite(pin,HIGH);     // pre-set output value to HIGH
  pinMode(pin,OUTPUT);        // set to output, it will be HIGH
}

void loop() {
  digitalWrite(pin,LOW);
  delay(1000);
  digitalWrite(pin,HIGH);
  delay(1000);
}

```

When the relay module has floating inputs (as far as I know they do not) then you need extra hardware to pull the signal high with a pullup resistor to keep the relays disabled during reset.

# Answer
> 2 votes
If you have a relay that is activated by a LOW or ground path, and is deactivated by an open circuit or HIGH signal applied, then you could try switching the pinMode to act as the HIGH or open circuit.

```
const byte pin = 2;

void setup(){

  // Define the pin as INPUT_PULLUP until you are ready to use it.
  pinMode(pin, INPUT_PULLUP);

}

void loop(){

  delay(1000);

  // Activate the relay. Supplying a low impedance
  // path to ground turns the relay on.
  pinMode(pin, OUTPUT);
  digitalWrite(pin, LOW);

  delay(1000);

  // Deactivate the relay.
  pinMode(pin, INPUT_PULLUP);

  // Using digitalWrite(pin, HIGH); is an alternative to using
  // pinMode(pin, INPUT_PULLUP); If your relay module is the
  // same as the one shown below, then it doesn't matter which
  // method you choose.

}

```

I'm not sure which relay module you are using, but if it is the same as this type, using INPUT\_PULLUP will work.

As Edgar Bonet mentions in his comment to kot's answer, using `pinMode(pin, INPUT_PULLUP);` is clearer than using `digitalWrite(pin, HIGH);`.

This code does 2 things:

```
digitalWrite(pin,HIGH);
pinMode(pin,OUTPUT);

```

First it sets the pin to INPUT\_PULLUP, then it sets it to VCC (for lack of a better term). If you connect a modern LED with a 1k ohm resistor to pin 2, and use this sketch, you can see the LED "dimly" lit for 5 seconds, then it is "brightly" lit.

```
const byte pin = 2;

void setup() {

  // pre-set output value to HIGH
  // The internal pull up resistor is now connected to the pin.
  digitalWrite(pin,HIGH);

  // Wait for 5 seconds.
  delay(5000);

  // set to output, it will be HIGH
  // The pin is now connected to VCC (for lack of a better term).
  pinMode(pin,OUTPUT);

}

void loop(){}

```

# Answer
> 1 votes
As fas as I know, by default digital pins are set as inputs. Arduino has internally only pull-up resistors, which you can use in that way:

```
digitalWrite(pinOut[i], HIGH);

```

in first setup() line (without `pinMode(pinOut[i], OUTPUT);`).

If you need LOW state on start-up (pull-down resistors), you have to use an external resistor.

---
Tags: arduino-mega, relay, digitalwrite
---


title: Arduino Python to Serial command

text:
# Question
Title: Arduino Python to Serial command
I am trying to send commands via serial from Python to Arduino with the code below.

If I save this code in a dedicated python file "Stepper.py" (Python2.7 on Mac OSX) , the code runs successfully but nothing happens (the code does not trigger a motor connected to Arduino).

If I start terminal and run the same code from the interactive shell it works as expected.

How can I run it via a dedicated file ?

```
import serial
import time

ser = serial.Serial(port="/dev/cu.usbmodem144231", baudrate=9600, timeout = 0)
ser.write("200+")
time.sleep(1)
print ser.read()

```

# Answer
> 2 votes
Majenkos comment (above) solved the problem:

"You need to wait after opening the serial port for the board to finish resetting and the bootloader to run and exit before you can send any commands."

```
import serial
import time

ser = serial.Serial(port="/dev/cu.usbmodem144231", baudrate=9600, timeout = 0)
time.sleep(1)
ser.write("200+")
print ser.read()

```

---
Tags: serial, python
---


# Question
Title: Set Low Power Level or Enable Pin of stepper driver, so stepper does not get hot
I am using the code below with this stepper shield:

https://www.dfrobot.com/wiki/index.php/Stepper\_Motor\_Shield\_For\_Arduino(DRV8825)\_SKU:DRI0023

Everything works, but tends to get hot (62.3 Celsius) while holding in idle position. What I understood so far, to reduce the temperature I can:

1. Set enable pin only when I need to turn the motor, but loose my position.
2. I can use what the driver manual describes as low level. Which I did not entirely understand.

If I set the enable pin to low by doing `digitalWrite(M1en,LOW);` do I put the stepper in low power mode or do I switch off the power to the stepper ?

3. I could only enable the stepper (if by setting it to LOW or HIGH I enable, disable) when I need it. Which would be the best as I understood it.

Where in my code below would I have to add the digitalWrite LOW,HIGH to achieve this ? Or do I need to just set it LOW (for low power mode).

4. Or is there a much better way I don't know about.

Code:

```
const int dirPin = 4;
const int stepPin = 5;
const int M1en = 12;

int speed = 200;    // desired speed in steps per second
int steps = 0;      // the number of steps to make

void setup()
{
  pinMode(dirPin, OUTPUT);
  pinMode(stepPin, OUTPUT);
  digitalWrite(M1en,LOW);// Low Level Enable
  Serial.begin(9600);
}

void loop()
{
  if ( Serial.available()) {
    char ch = Serial.read();

    if(isDigit(ch)){             // is ch a number?
      steps = steps * 10 + ch - '0';        // yes, accumulate the value
    }
    else if(ch == '+'){
      step(steps);
      steps = 0;
    }
    else if(ch == '-'){
      step(-steps);
      steps = 0;
    }
    else if(ch == 's'){
      speed = steps;
      Serial.print("Setting speed to ");
      Serial.println(steps);
      steps = 0;
    }
  }
}

void step(int steps)
{
  int stepDelay = 1000 / speed;  //delay in ms for speed given as steps per sec
  int stepsLeft;

  // determine direction based on whether steps_to_mode is + or -
  if (steps > 0)
  {
    digitalWrite(dirPin, HIGH);
    stepsLeft = steps;
  }
  if (steps < 0)
  {
    digitalWrite(dirPin, LOW);
    stepsLeft = -steps;
  }
  // decrement the number of steps, moving one step each time
  while(stepsLeft > 0)
  {
    digitalWrite(stepPin,HIGH);
    delayMicroseconds(1);
    digitalWrite(stepPin,LOW);
    delay(stepDelay);
    stepsLeft--;      // decrement the steps left
  }
}

```

# Answer
The product page you gave has a link to the DRV8825 datasheet.

Reading this, it is clear that the enable pin(s) comlpetely disable the H-Bridge that drives the motor coils. This **is** low power mode. It'd doesn't mean low, but non-zero holding current. The driver only supports enabled and disabled.

If your steppers are getting hot, perhaps the current being supplied by the driver is too high. The maximum drive current is set by the current-sense resistors attached to the driver chip. These may not be easy to change. To decrease the maximum current, you increase the current-sense resistor.

The product page notes that the shield has the current set at 1.6A per coil.
> 1 votes

---
Tags: stepper-motor
---


# Question
Title: How to use one button with interrupt to enable and disable sleep mode?
I have written a program for a kitchen timer. The timer uses just one single rotary encoder with a push button on its axis. It has modes for counting up and for counting down. After counting down it switches into alarm state. When I then push the button the alarm stops and the device goes into sleep mode. To wake it up I need to either push the button again or twist the encoder.

The problem: When I push the button during alarm the device does go into sleep mode but since that very same button is used to wake it up again, the timer switches into the wrong state and freezes in sleep mode. At least that is my interpretation of the problem:

Pushing the button during alarm triggers sleep mode ( goToSleep() ). During goToSleep I attach to that very button the interrupt that wakes the device.

The solution must be simple, I just can't see it. I just need to ignore any button input beween calling goToSleep() and sleepcpi();. Right?

How can I make this work?

```
#include <avr/sleep.h>
#include <Rotary.h>
#include <Bounce2.h>

unsigned long timerSeconds = 0;   // Remaining countdown time in seconds. An unsigned int would be enough for more than 18 HOURS!
unsigned long alarmTime = 0;      // The absolute point in time of the alarm

// Variables for updates
unsigned long currentMillis = 0;
unsigned long previousMillis = 0;
unsigned long currCountMillis = 0;
unsigned long prevCountMillis = 0;

// Setup Pins & Variables
Rotary rotary = Rotary(3, 4);     // Needs to be pin 2 or 3 in order to use as interrupt
const byte encBtnPin = 2;         // Needs to be pin 2 or 3 in order to use as interrupt
const byte beepPin = 5;

byte encBtnState;
byte prevEncBtnState;
bool encBtnPushed = false;
Bounce debouncer = Bounce();

// Setup state machine
typedef enum { NONE, SETTING, COUNTING_DOWN, COUNTING_UP, WAS_COUNTING, ALARM } states;
states state = NONE;

void setup() {
  Serial.begin(9600); //remove after testing

  pinMode(encBtnPin, INPUT_PULLUP);
  debouncer.attach(encBtnPin);
  debouncer.interval(10);
  pinMode(beepPin, OUTPUT);

  // Turn off ADC
  ADCSRA = 0;
}

void loop() {
            Serial.println("Top of loop"); // Remove after testing
            Serial.print("State: "); // Remove after testing
            Serial.println(state); // Remove after testing
  switch (state) {
    case NONE:
      goToSleep();
      break;
    case SETTING:
      setCountdown();
      break;
    case COUNTING_DOWN:
      startCountdown();
      break;
    case COUNTING_UP:
      startCounter();
      break;
    case ALARM:
      alarm();
      break;
  }
}

void readEncButton() {
  encBtnState = digitalRead(encBtnPin);     // Check if button state has changed
  if (encBtnState != prevEncBtnState) {
    if (encBtnState == LOW) {
      encBtnPushed = true;
      beep();
    }
  }
  prevEncBtnState = encBtnState;

  if (encBtnPushed) {                     // If Button has been pushed ...
    encBtnPushed = false;                 // ... reset button and do one of the following ...
    switch (state) {                      // Core state machine (state changes)
      case NONE:
        break;
      case SETTING:
        if (timerSeconds != 0) {          // Start countdown only if timer is not = 0 ...
          state = COUNTING_DOWN;
              Serial.print("State: "); // Remove after testing
              Serial.println(state); // Remove after testing
        }
        else {                            // If timer = 0, go to sleep
          state = NONE;
              Serial.print("State: "); // Remove after testing
              Serial.println(state); // Remove after testing
        }
        break;
      case COUNTING_DOWN:
        timerSeconds = (timerSeconds / 10) * 10;        // Set last digit to zero ...
        state = SETTING;                                // ... then go back to setting time
        break;
      case COUNTING_UP:
        timerSeconds = 0;
        state = SETTING;
        break;
      case ALARM:
        state = NONE;
        break;
    }
  }
}

void setCountdown() {
  // Read rotary encoder input
  unsigned long timeOut = millis();
  while (state == SETTING) {
    unsigned char result = rotary.process();
    if (result == DIR_CW) {
      timerSeconds += 10L;
      timeOut = millis();
      writeDisplay();
    }
    else if (result == DIR_CCW) {
      timerSeconds -= 10L;
      timeOut = millis();
      writeDisplay();
    }
    if ( millis() >= timeOut + 30000L ) {         // Go to sleep after 30 seconds idle
      state = NONE;
    }
    // Read rotary encoder button
    readEncButton();
  }
}

void startCountdown() {
  alarmTime = millis() + (timerSeconds * 1000L);  // Determine absolute alarm point in time in milliseconds (only once on countdown start)
  while (state == COUNTING_DOWN) {
    updateDisplay();
    timerSeconds = ( alarmTime - millis() ) / 1000L;            // Calculate new remaining number-of-seconds
    readEncButton();
  }
}

void startCounter() {
  while (state == COUNTING_UP) {
    currCountMillis = millis();
    updateDisplay();
    if (currCountMillis - prevCountMillis > 999) {              // Update counter once per second
      prevCountMillis = currCountMillis;
      timerSeconds ++;
    }
    readEncButton();
  }
}

void updateDisplay () {
  currentMillis = millis();

  // Only once every 1000ms ...
  if (currentMillis - previousMillis > 999) {
    previousMillis = currentMillis;                           // Reset the timer for display updates
    writeDisplay();
  }
}

void writeDisplay() {
  int cHours = timerSeconds / 3600L;                        // Update variables to display
  int cMinutes = timerSeconds % 3600L / 60;
  int cSeconds = timerSeconds % 3600L % 60;
  // Format and print display data
  if (cHours == 0 || cHours < 10) {Serial.print("0");}      // Add leading "0" if necessary
  Serial.print(cHours);
  Serial.print(":");
  if (cHours == 0 || cMinutes < 10) {Serial.print("0");}    // Add leading "0" if necessary
  Serial.print(cMinutes);
  Serial.print(":");
  if (cSeconds == 0 || cSeconds < 10) {Serial.print("0");}  // Add leading "0" if necessary
  Serial.println(cSeconds);
  // Alarm trigger follows here since alarm is supposed to sound AFTER the nillth second has been displayed
  if (state == COUNTING_DOWN && timerSeconds == 0) {
    state = ALARM;
  }
}

void beep() {
  tone(beepPin, 1000, 120);
}

void alarm() {
  int alarmRep = 0;
  attachInterrupt(digitalPinToInterrupt(encBtnPin), endAlarm, LOW);
  while (state == ALARM && alarmRep < 30) {
    for (int i = 0; i < 4; i ++) {
      tone(beepPin, 2000, 100);
      delay(120);
    }
    delay(500);
    alarmRep ++;
  }
  goToSleep();          // Go to sleep after alarm (state is changed to NONE in sleepmode-setup)
  //state = NONE;       // Need condition to prevent state = NONE in case previous while-loop was left due to state change
}

void endAlarm() {
  detachInterrupt(digitalPinToInterrupt(encBtnPin));
  state = NONE;
}

/* Sleep mode and stuff *
************************/

void wakeToSet() {
  sleep_disable();
  detachInterrupt(digitalPinToInterrupt(3));          // Hard-coded to pin 3
  detachInterrupt(digitalPinToInterrupt(encBtnPin));  // Encoder button can no longer wake up CPU
  state = SETTING;
}

void wakeToCount() {
  sleep_disable();
  Serial.println("Detaching interrupts ...");         // Remove after testing
  detachInterrupt(digitalPinToInterrupt(3));          // Hard-coded to pin 3
  detachInterrupt(digitalPinToInterrupt(encBtnPin));  // Encoder button can no longer wake up CPU
  beep();
  Serial.println("Waking up to count ...");           // Remove after testing
  state = COUNTING_UP;
}

void goToSleep() {
  Serial.println("Starting goToSleep()");             // Remove after testing
  timerSeconds = 0;                                   // Reset everything
  alarmTime = 0;
  state = NONE;
  sleep_enable();
  attachInterrupt(digitalPinToInterrupt(3), wakeToSet, LOW);             // Hard-coded to pin 3
  attachInterrupt(digitalPinToInterrupt(encBtnPin), wakeToCount, LOW);   // Encoder button can wake up machine
  set_sleep_mode(SLEEP_MODE_PWR_DOWN);
  Serial.print("State: "); // Remove after testing
  Serial.println(state); // Remove after testing
  Serial.println("Going to sleep now..."); // Remove after testing
  delay(250);
  sleep_cpu();
}

```

# Answer
couple of thoughts: a fritzing Diagram of your Connections may help. as far as i can tell you connect the (?data?) lines of the Encoder to the Interrupt lines? do you want to trigger an Interrupt on Input value Change? like from 4 minutes to 5minutes? did you Thing of debouncing your switches? (just saw you do it in Software... consider a simple RC lowpass instead. Maybe the debouncing uses a timer and then collides with the remaining logic...) do you really Need to now the previous Button state? another Thing i see is you just have an awful lot of Code. consider taking out a piece of paper and draft a state Diagram for the statemachine your About to realise. and then share it here (makes life a lot easier!)
> -1 votes

---
Tags: interrupt, sleep
---


title: Arduino button and led

text:
# Question
Title: Arduino button and led
Program below is my program for my button and LED, but it's not functioning the way I want it too. The LED is supposed to light up before I press switch 9, but it is lighting up immediately.

```
const int sw9=9;
const int sw10=10;
const int sw11=11;
const int sw12=12;
const int sw13=13;
int timer=250;
int s=0;
void setup()
{
  for (int opin=1;opin<=8;opin++)
{
  pinMode(opin,OUTPUT);
  pinMode(sw9,INPUT_PULLUP);
  pinMode(sw10,INPUT);
  pinMode(sw11,INPUT);
  pinMode(sw12,INPUT);
  pinMode(sw13,INPUT);
}
}
void loop(){
{
while (s==0)

for (int opin=1;opin<=8;opin++)
{
digitalWrite(opin,HIGH);
delay(timer);
digitalWrite(opin,LOW);
if(digitalRead(sw9)==LOW);
}

{
s=1;
delay(timer);
}
}
while(s==1)
for (int opin=1;opin<=8;opin++)
{
digitalWrite(opin,LOW);
if(digitalRead(sw9)==HIGH);
}
}

```

# Answer
```
if(digitalRead(sw9)==LOW);

if(digitalRead(sw9)==HIGH);

```

Both of these have the effect of "read the switch and then do nothing"

Change them to

```
if(digitalRead(sw9)==HIGH){
// do intended action
}

```
> 2 votes

---
Tags: arduino-uno
---


# Question
Title: How to subtract the current analog value from previous one
I pretty new to the Arduino. I am working on project that find the power by reading your

# Answer
> 0 votes
I think you need something like the following :

```
int lastTime;

void loop(){
  int thisTime = analogRead(A1);
  int diff = thisTime - lastTime;
  lastTime = thisTime;
  Serial.println(diff);
}

```

---
Tags: arduino-mega, power
---


# Question
Title: Does the square-wave nature of PWM dictate how much resistance you need?
I think the answer is yes, but I wanted to ask the question anyway for future common reference. And to check my understanding.

Say I want to power 10 LEDs with PWM with my Mega 2560. I have a bunch of 200 ohm resistors.

I know the Mega and most other Arduinos can safely provide a maximum of 200mA total current. 200mA / 10 is 20mA per LED maximum.

Using my 200 ohm resistors I can calculate how much voltage will supply 20 mA of current:

```
V = 200 ohms * 20mA
V = 4V

```

So I just need to make sure to analogWrite less than or equal to 4V to each of the ten LEDs and I won't cross the 200mA threshold. That's if PWM was true analog.

However, PWM is not true analog, and if I analogWrite 4V to each pin, they're going to spend most of the time at 5V and some of the time at 0V.

When every pin is at 5V the board has to supply

```
(5V / 200 ohms) * 10 = 250mA

```

Which is over the spec, so I am in danger of damaging my board. Right?

So if I want to calculate the maximum current draw of the 10 LEDS being powered simultaneously with PWM, I have to assume that they are all getting 5V regardless of what I analogWrite to them. I do not actually have control over the voltage, I only have control over the resistance.

Thus in order to be safe I need to get some new resistors with resistance:

```
5V / 20mA = 250 ohms

```

Is this all correct?

# Answer
It's... mostly wrong. For three independent reasons.

The LEDs themselves, like all diodes, absorb some of the electrovoltaic potential of the electricity passing through them, resulting in a voltage decrease in their circuit. This means that although 5V is being used to power the resistor and LED in a circuit, only some of that voltage is passing through the resistor. If we use a typical (for blue, white, and other exotic colors) forward voltage (Vf) of 2.8V, this means that the resistor only has 2.2V across it. For a 200ohm resistor, this means that only 11mA is passing through the circuit. If you want 20mA to pass through the LED you need to use a resistance of 110ohm instead.

Second, the voltage from the MCU pins themselves depend on the current passing through them. Section 32.7 of the ATmega2560 datasheet, "Typical Characteristics - Pin Driver Strength" has charts for voltage versus current for both sourcing and sinking current; at 20mA the voltage drops to about 4.5V, which means that the resistance required for a 2.8V LED drops from 110ohm down to 85ohm.

Third, although semiconductors (i.e. the MCU and LED) can be damaged when too much current passes through them, it is not the current itself that causes the damage. The current passing through the voltage drop results in a consumption of power, and this power subsequently turns into heat. This heat then causes the breakdown of the semiconductor material. Even a junky, third-hand LED can take bursts of current up to 35mA or so without being damaged, provided the duration is limited. With a PWM signal this duration is directly linked to both the frequency and the duty cycle of the signal. You will need to see the datasheet for the LED in question to figure out what the maximum safe current and duration are, but the implication is that if you keep the frequency high enough and the duty cycle low enough, you can get away without any resistor at all and both the MCU and LED will survive.
> 7 votes

# Answer
Note that PWM does not actually drop the output voltage. It generates variable length pulses of 5V at different "duty cycles" (percent on vs percent off).

For an LED you might get away with using PWM to vary the power that passes through the LED since it can probably tolerate over-current for brief intervals.

What you should really do is calculate resistor value based on LED voltage drop and maximum current:

Say you have a red LED with a 1.8V voltage drop.

5V supply - 1.8 LED voltage drop = 3.2 V If the LED can handle a max of 15 mA, that would be 3.2/.015 ≈ 213Ω. Round up to the nearest 10% resistor value, 220Ω. That would give you about 14.8mA through the LED, slightly less than it's max.

If you then power the LED through a PWM pin, running the analog output at max will drive the LED at max brightness, and lower analog output levels will make the LED *appear* dimmer. Note that the LED will actually be rapidly flashing between full intensity (limited by your current limiting resistor, assuming you have one) and off. Our eyes average out that flashing light and see it as being a dimmer, constant light.
> 0 votes

---
Tags: voltage-level, pwm, current
---


# Question
Title: Powering an Arduino Mini Pro using a CR2032 battery as a remote control
I'm looking into making my own remote control using an Arduino Mini Pro and some RF transceivers. The receiving end won't be a problem, but the remote will. I want to make it as small as possible and consume as little energy as possible.

Is it possible to turn on the Arduino Mini Pro at the push of a button, while also using that same button to trigger a piece of code? That way I can cut the power when it's not being pressed.

I will make sure to code it, so I have to hold the button down for 1-1.5 seconds, so it has time to "boot up" and send the RF signal, but should power off immediately when I let go of the button.

What kind of power should I expect from a single CR2032 battery? I have a couple of NRF24L01 RF transceivers laying around together with an Arduino Mini Pro.

If we assume this, while looking at this sheet:

```
NRF24L01: 10 mA per second (low-ball)
ATmega328P: 5 mA per second (low-ball)
CR2032: 0.19 mA @ 2V = 2100+ hours

```

Even if we just say 600 hours and it takes 2 seconds to turn something on, I should be able to run it `600H*60M*60S = 2.160.000 seconds = 1.080.000 times`. If my calculation isn't completely wrong, it means I could literally turn it on a million times in the worst case scenario.

I hope that calculation is wrong, because that seems crazy.

EDIT: I could desolder the LED and regular as well, if that won't damage it too much. Just to consume power. I've read I can basically run it for free then.

# Answer
You should take a look at ATmega328P datasheet

> On page 2, it says: Six Sleep Modes: Idle, ADC Noise Reduction, Power-save, Power-down, Standby, and Extended Standby

These are the modes which can be used to put Arduino Pro Mini in stand-by. You can search for them at datasheet and choose the only that better applies to you. To learn more about sleep mode and other methods to save battery, you can take a look at this source: Arduino Low Power - How To Run ATmega328P For a Year On Coin Cell Battery

On the datasheet of battery, you should pay attention at its charge:

> Typical Capacity: 240 mAh (to 2.0 volts)

This means that from 3 to 2 Volts, it relases 240 mAh. This is the charge you can expect to use. Using the consumptions rates you posted above

```
NRF24L01: 10 mA per second (low-ball)
ATmega328P: 5 mA per second (low-ball)
CR2032: 240 mAh
Time: 240mAh/(10mA + 5mA) = 16 hours

```

Which is not so much. To increase this autonomy, the link I posted above is quite useful because it will show you alternatives like removing the voltage regulator that will reduce drastically your consumption. Now, if you feel *really* adventurous, you may take a look at how to underclock your board: Arduino pro mini @ 1MHz - 1.8V. This is a very efficient way to save power where clock frequency is not a must.

---

**EDIT after comments:**

The 16 hours were computed using 5mA for the Arduino (which is a value for power consumption that can be expected on active mode) and 10mA for the NRF24L01. You have to estimate a sleep mode consumption for both and a percentage of time in sleep mode if you want to estimate an autonomy. At the link I sent you about sleep mode there are some tables with power consumption in different configurations.

ATmega328P can run with a minumum of 1.8 Volts, while nRF24L01+ can while with a minimum of 1.9V - see datasheet. So probably you are going to have a little bit more than 240mAh to work with. Your battery won't have 3v all the time. It is going to start with 3V (maybe a litte bit more) and gradually reduces it voltage as the charge is provided to the circuit. Once the voltage goes bellow 1.9V, nRF24L01+ won't be guaranteed to work properly.

Definitely, to sleep the Pro Mini, just waking it up when using, is the right way to design this circuit. According to this reference I posted above, power consumption for Arduino should be 0.90 mA. At the item 5.1 of nRF24L01+ datasheet, it is described that it consumes 0.32mA at standby mode II. If you sleep the Pro Mini for, let's say, 90% of the time, without removing leds or voltage regulators, you can estimate that

```
t = 240mAh * (0.1/(5mA+10mA) + (0.9/(0.9mA+0.32mA)) = 178.65 hours

```

If you use strategies to reduce Arduino power consumption, like the ones I send you above, you can increase this time. You will also save power if you change nRF24L01+ from standby mode 2 to standby mode 1. Check the database to see which one fit your needs.
> 2 votes

# Answer
If you have a single button, it is useless to use the button to trigger the piece of code. The fact that you are powered on means that the button is pressed.

simulate this circuit – Schematic created using CircuitLab

Of course you need a 3.3V Arduino PRO Mini...

If you have multiple buttons, you can have different circuits to detect this.

**Solution 1**

Use a set of diodes to power the board, then another to detect the digital pins.

simulate this circuit

The second set of diodes is needed because you should not show to the atmega pins a voltage greater than Vcc+0.5V. Since a pull-down resistor is needed, if you want you can replace the second set of diodes with 2k2 resistors.

**Solution 2**

Again use a set of diodes to power the board, but then decode the value through an analog reading

simulate this circuit

You will need to experiment a bit to figure out the thresholds. For instance, with the values I wrote, you can expect to read from the ADC a value around 1000 for the button 1, a value around 600 for the button 2, and 300 for the button 3; for this reason, you write

```
int buttonRawValue = analogRead(A1);
if (buttonRawValue > 800) {
    // Button 1 was pressed
}
else if (buttonRawValue > 450) {
    // Button 2 was pressed
}
else {
    // Button 3 was pressed
}

```

This will require some tuning, but I think it can work.

**Solution 3**

You can power the board through a transistor (I usually prefer small MOSFETs)

simulate this circuit

You will need to find a MOS with a very low Vgs-th, sinceit should fully turn on with 1.5V. This solution has the advantage of not wasting the small voltage you have (while the other ones waste around 0.3V for Schottky diodes and 0.6V for PN diodes).

Personally I'd go with solution 3, since it is also easy to let the atmega control the power (simply attach one of the digital outputs to the cathodes of the diodes, and the ATMEGA will be able to force power on until it has finished the operations).

As a side note, I would recommend you not to use a pre-made board, but use a bare ATMEGA328P in this project. You can experiment with another arduino board, but then use the arduino board to flash a bare ATMEGA; you will get rid of all the useless things. You can avoid using a crystal and a voltage regulator, so your circuit will consist only of the components I used in the schematics and a 100nF capacitor between the VCC and GND pins of the microcontroller.

And... Don't flash a bootloader. Use another arduino board to flash the microcontroller, not a serial peripheral. This is because the bootloader is useful, but at boot it wastes some seconds (and you need to be as quick as possible)
> 0 votes

---
Tags: arduino-pro-mini, nrf24l01+, rf, remote-control
---


title: Negative currentmA and Shuntvoltage

text:
# Question
Title: Negative currentmA and Shuntvoltage
Why is my INA219 current sensor gives a negative currentmA and Shunt voltage? My sensor is connected in a glucose test strip connector. The current is from a glucose biosensor? Is it possible that my INA219 is damaged?

# Answer
> 1 votes
The "sign" of the INA219 shows the direction of flow of the current. Current isn't either "positive" or "negative", it has a direction. The sign is just used to represent that direction.

It's like a car. It has a speed. That speed could be in the forward direction, or the reverse direction. It could be going 5 miles per hour forwards, or 5 miles per hour backwards. Either way, it's 5 miles per hour. However the backwards direction could be represented as "minus 5 miles per hour". It doesn't mean that you're doing a negative speed (there is no such thing), but that your speed is in a "negative direction".

This "speed" and "direction" are combined together to create "velocity", which is "speed relative to some arbitrarily chosen 'normal' direction and speed".

At this point the "velocity" can be represented as a 2D vector, with forward velocity in the + direction, and reverse velocity in the - direction.

But that's all a bit of a digression. All it means is that the "-" is meaningless if you don't care about the direction of current flow. If all you care about is the quantity of current you can discard the "-" completely. The simplest way is:

```
current = abs(current);

```

---
Tags: arduino-nano
---


title: Arduino max power supply limit

text:
# Question
Title: Arduino max power supply limit
What is the maximum current that can be supplied to an Arduino Mega board before frying/breaking?

Basically i have several components connected to my board which draw a total current of 1.6A (which i calculated through a table), and thinking of using a 9V 2A power supply. I know that the arduino voltage limit is 7-12V but just wondering about the current as I can't find it on the datasheets?

Thanks in advance!

# Answer
1A coming in thru the barrel jack connecor, then you risk blowing the 1A rated reverse polarity protection diode. The 5V regulator will overheat at high currents above 7.5V. The chip itself can have 800mA put thru if if properly cooled and the IO limits of current per port are respected.

So 1.6A, no way.
> 5 votes

# Answer
From the ATmega328P datasheet.
> 2 votes

# Answer
Your question isn't clear. Are you talking about drawing regulated 5V from the Arduino power supply? I believe the built-in regulator has a hard limit if 1A total output, but how much you can draw from it will depend on various factors (mostly how much waste heat it generates. If you drive it from 9V it will generate quite a bit of heat, since a linear regulator simply dissipates the excess voltage as heat. Better to use a 7V supply)

You won't be able to draw 1.6A of 5V from the Arduino. You should probably get a separate 2A 5V regulated power supply for your external components. Again though, your question isn't very clear so I'm not sure I'm answering what you're asking.
> 1 votes

---
Tags: arduino-mega, power, current
---


# Question
Title: NodeMCU display temperature and control LED from an autorefresh web page
I'm totaly new to Arduino, I'm using ESP2866 NodeMCU and dht22 to display temperature and humidity in a web page, it is autorefresh (using AJAX) and it works perfectly, I wanted to add 2 buttons to it so I can control 2 Leds but when I tried that I couldn't control them and even the values of temperature and humidity stopped refreshing. Can you tell me what is wrong in the code ? here it is :

```
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
#include "DHT.h"
#define DHTTYPE DHT22   // DHT 22  (AM2302), AM2321

 /*Put your SSID & Password*/
 const char* ssid = "xxx";  // Enter SSID here
 const char* password = "xxx";  //Enter Password here

  ESP8266WebServer server(80);

 // DHT Sensor
 uint8_t DHTPin = D6;

  // Initialize DHT sensor.
  DHT dht(DHTPin, DHTTYPE);

  float Temperature;
  float Humidity;
  float reading;
  float percentage;
  // Auxiliar variables to store the current output state
  String output5State = "off";
  String output4State = "off";

 // Assign output variables to GPIO pins
 const int output5 = 5;
 const int output4 = 4;
 void setup() {
 Serial.begin(115200);
 delay(100);

 pinMode(DHTPin, INPUT);
 dht.begin();

// Initialize the output variables as outputs
  pinMode(output5, OUTPUT);
 pinMode(output4, OUTPUT);
 // Set outputs to LOW
 digitalWrite(output5, LOW);
 digitalWrite(output4, LOW);
 Serial.println("Connecting to ");
 Serial.println(ssid);

//connect to your local wi-fi network
WiFi.begin(ssid, password);

//check wi-fi is connected to wi-fi network
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected..!");
Serial.print("Got IP: ");  Serial.println(WiFi.localIP());

server.on("/", handle_OnConnect);
server.onNotFound(handle_NotFound);

server.begin();
Serial.println("HTTP server started");

}
void loop() {

server.handleClient();
}

void handle_OnConnect() {

Temperature = dht.readTemperature(); // Gets the values of the temperature
Humidity = dht.readHumidity(); // Gets the values of the humidity

//Serial.println(reading);
String header=SendHTML( Temperature,Humidity,percentage);

server.send(200, "text/html",header);
// turns the GPIOs on and off
        if (header.indexOf("GET /5/on") >= 0) {
          Serial.println("GPIO 5 on");
          output5State = "on";
          digitalWrite(output5, HIGH);
        } else if (header.indexOf("GET /5/off") >= 0) {
          Serial.println("GPIO 5 off");
          output5State = "off";
          digitalWrite(output5, LOW);
        } else if (header.indexOf("GET /4/on") >= 0) {
          Serial.println("GPIO 4 on");
          output4State = "on";
          digitalWrite(output4, HIGH);
        } else if (header.indexOf("GET /4/off") >= 0) {
          Serial.println("GPIO 4 off");
          output4State = "off";
          digitalWrite(output4, LOW);
        }

      }

   void handle_NotFound(){
   server.send(404, "text/plain", "Not found");
    }

   String SendHTML(float TempCstat,float Humiditystat, float  percentage){
    String ptr = "<!DOCTYPE html> <html>\n";
    ptr +="<head><meta name=\"viewport\" content=\"width=device-width,
    initial-scale=1.0, user-scalable=no\">\n";
    // ptr +="<meta http-equiv=\"refresh\" content=\"2\" >\n";
   ptr +="<link href=\"https://fonts.googleapis.com/css?
    family=Open+Sans:300,400,600\" rel=\"stylesheet\">\n";
    ptr +="<title>ESP8266 Weather Report</title>\n";
    ptr +="<style>html { font-family: 'Open Sans', sans-serif; display:
    block; margin: 0px auto; text-align: center;color: #333333;}\n";
    ptr +="body{margin-top: 50px;}\n";
    ptr +="h1 {margin: 50px auto 30px;}\n";
    ptr +=".side-by-side{display: inline-block;vertical-align:
     middle;position: relative;}\n";
    ptr +=".humidity-icon{background-color: #3498db;width: 30px;height:
    30px;border-radius: 50%;line-height: 36px;}\n";
     ptr +=".humidity-text{font-weight: 600;padding-left: 15px;font-size:
     19px;width: 160px;text-align: left;}\n";
     ptr +=".humidity{font-weight: 300;font-size: 60px;color: #3498db;}\n";
     ptr +=".temperature-icon{background-color: #f39c12;width: 30px;height:
     30px;border-radius: 50%;line-height: 40px;}\n";
     ptr +=".temperature-text{font-weight: 600;padding-left: 15px;font-size:
     19px;width: 160px;text-align: left;}\n";
     ptr +=".temperature{font-weight: 300;font-size: 60px;color:
     #f39c12;}\n";
     ptr +=".superscript{font-size: 17px;font-weight: 600;position:
     absolute;right: -20px;top: 15px;}\n";
     ptr +=".data{padding: 10px;}\n";
     ptr +="</style>\n";
     ptr +="<script>\n";
     ptr +="setInterval(loadDoc,200);\n";
     ptr +="function loadDoc() {\n";
     ptr +="var xhttp = new XMLHttpRequest();\n";
     ptr +="xhttp.onreadystatechange = function() {\n";
     ptr +="if (this.readyState == 4 && this.status == 200) {\n";
     ptr +="document.getElementById(\"webpage\").innerHTML
     =this.responseText}\n";
     ptr +="};\n";
     ptr +="xhttp.open(\"GET\", \"/\", true);\n";
     ptr +="xhttp.send();\n";
     ptr +="}\n";
     ptr +="</script>\n";

     ptr +="</head>\n";
     ptr +="<body>\n";

     ptr +="<div id=\"webpage\">\n";

     ptr +="<h1>ESP8266 Weather Report</h1>\n";
     ptr +="<div class=\"data\">\n";
     ptr +="<div class=\"side-by-side temperature-icon\">\n";
     ptr +="<svg version=\"1.1\" id=\"Layer_1\"
     xmlns=\"http://www.w3.org/2000/svg\"
     xmlns:xlink=\"http://www.w3.org/1999/xlink\" x=\"0px\" y=\"0px\"\n";
     ptr +="width=\"9.915px\" height=\"22px\" viewBox=\"0 0 9.915 22\"
     enable-background=\"new 0 0 9.915 22\" xml:space=\"preserve\">\n";
      ptr +="<path fill=\"#FFFFFF\" d=\"M3.498,0.53c0.377-0.331,0.877-
      0.501,1.374-0.527C5.697-0.04,6.522,0.421,6.924,1.142\n";
      ptr+=
       "c0.237,0.399,0.315,0.871,0.311,1.33C7.229,5.856,7.245,9.24,7.227,
        12.625c1.019,0.539,1.855,1.424,2.301,2.491\n";
      ptr +="c0.491,1.163,0.518,2.514,0.062,3.693c-0.414,1.102-1.24,2.038-
      2.276,2.594c-1.056,0.583-2.331,0.743-3.501,0.463\n";
      ptr +="c-1.417-0.323-2.659-1.314-3.3-2.617C0.014,18.26-
      0.115,17.104,0.1,16.022c0.296-1.443,1.274-2.717,2.58-3.394\n";
      ptr +="c0.013-3.44,0-6.881,0.007-
      10.322C2.674,1.634,2.974,0.955,3.498,0.53z\"/>\n";
      ptr +="</svg>\n";
      ptr +="</div>\n";
      ptr +="<div class=\"side-by-side temperature-
      text\">Temperature</div>\n";
      ptr +="<div class=\"side-by-side temperature\">";
      ptr +=(int)TempCstat;
      ptr +="<span class=\"superscript\">°C</span></div>\n";
      ptr +="</div>\n";
      ptr +="<div class=\"data\">\n";
      ptr +="<div class=\"side-by-side humidity-icon\">\n";
      ptr +="<svg version=\"1.1\" id=\"Layer_2\"
      xmlns=\"http://www.w3.org/2000/svg\"
      xmlns:xlink=\"http://www.w3.org/1999/xlink\" x=\"0px\" y=\"0px\"\n\";
      width=\"12px\" height=\"17.955px\" viewBox=\"0 0 13 17.955\" enable-
      background=\"new 0 0 13 17.955\" xml:space=\"preserve\">\n";
      ptr +="<path fill=\"#FFFFFF\"
     d=\"M1.819,6.217C3.139,4.064,6.5,0,6.5,0s3.363,4.064,4.681,6.217c1.793,
      2.926,2.133,5.05,1.571,7.057\n";
     ptr +="c-0.438,1.574-2.264,4.681-6.252,4.681c-3.988,0-5.813-3.107-
     6.252-4.681C-0.313,11.267,0.026,9.143,1.819,6.217\"></path>\n";
     ptr +="</svg>\n";
     ptr +="</div>\n";
     ptr +="<div class=\"side-by-side humidity-text\">Humidity</div>\n";
     ptr +="<div class=\"side-by-side humidity\">";
     ptr +=(int)Humiditystat;
     ptr +="<span class=\"superscript\">%</span></div>\n";
     ptr +="</div>\n";

    //Buttons

     ptr +="<div class=\"data\">\n";
     ptr +="<div class=\"side-by-side button-text\">Button</div>\n";
     ptr +="<div class=\"side-by-side Button\">";
     ptr +=" <p><a href=\"/5/on\"><button class=\"button\">ON</button></a>
     </p>";
     // If the output5State is off, it displays the ON button
        if (output5State=="off") {
          ptr +="<p><a href=\"/5/on\"><button class=\"button\">ON</button>
       </a></p>";
        } else {
          ptr +="<p><a href=\"/5/off\"><button class=\"button
        button2\">OFF</button></a></p>";
        }
         // If the output4State is off, it displays the ON button
        if (output4State=="off") {
          ptr +="<p><a href=\"/4/on\"><button class=\"button\">ON</button>
         </a></p>";
        } else {
          ptr +="<p><a href=\"/4/off\"><button class=\"button
          button2\">OFF</button></a></p>";
          }
           ptr +="<span class=\"superscript\">%</span></div>\n";
           ptr +="</div>\n";
           ptr +="</div>\n";
           ptr +="</body>\n";
           ptr +="</html>\n";
           return ptr;
          }

```

# Answer
Write handlers for different URLs

```
server.on("/5/on", led5On);
server.on("/5/off", led5off);

```

do you get the concept?

or you could write one handler `server.on("/setLED", setLED);`, if you would send `"/setLED?num=5&state=on"`. and then in `setLED` function get the parameters values as

```
String num = sever.arg("num");
String state = sever.arg("state");

```

see the SimpleAuthentication example
> 1 votes

---
Tags: arduino-ide, led, nodemcu, web
---


# Question
Title: nRF24L01 with antenna transmitter and receiver
I am trying to use nRF24L01 with antenna in my project, but when I do test with getting start from rf24 master is showing a serial monitor like in the picture abov e. What is the problem here?

# Answer
> -1 votes
Search in the code for the line `Serial.begin(###)` where **###** is a number representing the serial speed, also known as *baud rate*. This number must match with the baud rate of your serial monitor, otherwise all you get is garbage.

BTW, this has nothing to do with nRF24, this is plain Arduino serial connection.

---
Tags: nrf24l01+
---


title: 12 V relay using Arduino

text:
# Question
Title: 12 V relay using Arduino
I want to control a 12 V relay using an Arduino 5 V signal, but due to some unknown reason the relay does not work. I am using a BC548 transistor as a switch for relay. Please suggest where I go wrong.

# Answer
> 3 votes
If it's working with 12v on the input but not 5v, it sounds like the base resistor value (which is missing from the diagram) might be too high. A value of around 1k should ensure the transistor is fully switched on.

---
Tags: arduino-nano, relay, transistor
---


title: timer library on Arduino DUE

text:
# Question
Title: timer library on Arduino DUE
I'm trying to call an interrupt routine (let's call it handler() ) every second on my arduino DUE. I thought the simplest way to do this was to use this library but it seems that i don't know how to use it...

# Answer
> 1 votes
You are trying to print 6 characters ("test\r\n"), i.e. 60 bits including the start and stop bits, 1000 times per second. This requires a baud rate of at least 60 kbit/s, yet the serial port has been configured for only 9.6 kbit/s. Something has to give...

As Mikael Patel wrote in a comment, it is generally inadvisable to `Serial.print()` from within an ISR. It is supposed to work, though, as long as you don't fill the `Serial` output buffer. The problem is that your code does fill the buffer, as it is writing to it faster than the UART can empty it. Once the buffer is full, the program will malfunction.

---
Tags: arduino-due, timers
---


# Question
Title: attiny85 reset itself instead of wakeup procedure
I have a digispark attiny85, and I am using SLEEP\_MODE\_PWR\_DOWN to sleep, and wake-up with external interrupt on pin2. I am trying to count number of interrupts received with the code below.

Problem is on every LOW signal on pin2, attiny85 reset (restart) itself instead of processor wake-up and continue where it left. I can identify this by seeing led blink 3 times(*as in setup()*) on every LOW signal.

Is there a limitation on this hardware? **How can I only wake-up from sleep and not reset?** I appreciate if you direct me an example.

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

//modified from http://playground.arduino.cc/Learning/arduinoSleepCode

int ledPin = 0;            // LED connected to digital pin 0
int interruptPin = 1;      // LED to show the action of a interrupt
int wakePin = 2;            // active LOW, ground this pin momentary to wake up
unsigned int counter = 0;

void setup(){
  pinMode(ledPin, OUTPUT);         // sets the digital pin as output
  pinMode(interruptPin, OUTPUT);   // sets the digital pin as output
  pinMode(wakePin, INPUT_PULLUP);        // sets the digital pin as input
  digitalWrite(wakePin, HIGH);
  counter = 0;
  //do some blinks so we can identify boot & loop
     digitalWrite (interruptPin, HIGH);    // sets the digital pin as output
    delay(250);
     digitalWrite (interruptPin, LOW);    // sets the digital pin as output
    delay(250);
     digitalWrite (interruptPin, HIGH);    // sets the digital pin as output
    delay(250);
     digitalWrite (interruptPin, LOW);    // sets the digital pin as output
    delay(250);
     digitalWrite (interruptPin, HIGH);    // sets the digital pin as output
    delay(250);
     digitalWrite (interruptPin, LOW);    // sets the digital pin as output
    delay(250);
}

void sleepNow(){

    set_sleep_mode(SLEEP_MODE_PWR_DOWN);   // sleep mode is set here
    sleep_enable();                          // enables the sleep bit in the mcucr register so sleep is possible
    attachInterrupt(0, wakeUpNow, LOW);     // use interrupt 0 (pin 2) and run function wakeUpNow when pin 2 gets LOW
    digitalWrite(interruptPin, LOW);

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

    sleep_disable();                       // first thing after waking from sleep: disable sleep...
    detachInterrupt(0);                    // disables interrupton pin 3 so the wakeUpNow code will not be executed during normal running time.
    delay(250);                           // wait 2 sec. so humans can notice the interrupt LED to show the interrupt is handled
    digitalWrite (interruptPin, HIGH);       // turn off the interrupt LED

}

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.
 digitalWrite(interruptPin, HIGH);
}

void loop(){
   digitalWrite(interruptPin, HIGH);
  //digitalWrite(ledPin, HIGH);            // sets the LED on
  counter++;
  delay(5000);                           // waits for a second
  sleepNow();                      // sleep function called here
}

```

# Answer
> 0 votes
I found this, I can confirm it is working. on digispark attiny85.

```
void sleepTillChg() {  // 0.02ma drain while sleeping here
    GIMSK |= _BV(PCIE);                     // Enable Pin Change Interrupts
    PCMSK |= _BV(PCINT0);                   // Use PB0 (was PB3) as interrupt pin
    // Turn off unnecessary peripherals
    ADCSRA &= ~_BV(ADEN);                   // ADC off
    ACSR |= _BV(ACD); // Disable analog comparator

    set_sleep_mode(SLEEP_MODE_PWR_DOWN);    // replaces above statement
    sleep_enable();                         // Sets the Sleep Enable bit in the MCUCR Register (SE BIT)
    sei();                                  // Enable interrupts
    sleep_cpu();                            // sleep ... Zzzz

    cli();                                  // Disable interrupts
    PCMSK &= ~_BV(PCINT0);                  // Turn off PB0 (was PB3) as interrupt pin
    sleep_disable();                        // Clear SE bit
    sei();                                  // Enable interrupts
}

ISR(PCINT0_vect) {
    // This is called when the interrupt occurs, but we don't need to do anything in it
}

```

credits should go https://www.instructables.com/id/3-Minute-Game-Timer/

---
Tags: interrupt, sleep, attiny85, digispark
---


# Question
Title: Warning when verifying sketch with VS code
I use Visual Studio Code to develop for arduino which uses Arduino Studio installed files and needs the installation to work. This works very well.

Annoying is that when verifying a sketch it takes longer than in the Arduino IDE. I suspect the following warning to cause it:

> \[Warning\] Output path is not specified. Unable to reuse previously compiled files. Verify could be slow. See README.

I would like to get rid of the warning and I searched through all README files in the arduino installation folder and I also searched google but haven't found out what its supposed to mean and how to fix it. No readme file mentions that or I overlooked it.

Is there a documentation on how to fix this anywhere?

# Answer
Thanks to @Majenko I looked some place new:

documented in the arduino plugin of VS Code Arduino Extension there is an option to set an output directory.
Note though that according to this it should not be in the workspace or subfolders.

So in arduino.json settings file add:

```
"output": "../ArduinoOutput"

```
> 47 votes

# Answer
To clarify the answer, for those new in arduino world +StudioCode (source: https://marketplace.visualstudio.com/items?itemName=vsciot-vscode.vscode-arduino )

The following settings are as per sketch settings of the Arduino extension. You can find them in .vscode/arduino.json under the workspace.

```
{
    "sketch": "example.ino",
    "port": "COM5",
    "board": "adafruit:samd:adafruit_feather_m0",
    "output": "../build",
    "debugger": "jlink",
    "prebuild": "bash prebuild.sh"
}

```

**sketch** \- The main sketch file name of Arduino.

**port** \- Name of the serial port connected to the device. Can be set by the Arduino: Select Serial Port command.

**board** \- Currently selected Arduino board alias. Can be set by the Arduino: Change Board Type command. Also, you can find the board list there.

**output** \- Arduino build output path. If not set, Arduino will create a new temporary output folder each time, which means it cannot reuse the intermediate result of the previous build leading to long verify/upload time, so it is recommended to set the field. Arduino requires that the output path should not be the workspace itself or in a subfolder of the workspace, otherwise, it may not work correctly. By default, this option is not set.

**debugger** \- The short name of the debugger that will be used when the board itself does not have a debugger and there is more than one debugger available. You can find the list of debuggers here. By default, this option is not set.

**prebuild** \- External command before building the sketch file. You should only set one prebuild command. command1 && command2 does not work. If you need to run multiple commands before the build, then create a script.

When You add folder with sketch, you are creating "so called" project. VS code puts there some hidden folders with the project configuration files. To see them from windows file explorer you may enable show hidden files. than in your project folder You may find .vscode , and there is the arduino.json file.

More simple way is just click on the project navigation bar on the left, and open there the .vscode folder and using vscode as editor just add

"output": "../ArduinoOutput" or "output": "../build" or whatever you want to name that folder.

".." tells that it is one level above the "project folder" so it is "outside" as VScode wants.

And as far as i know this is not global setting, so You need to set it for every project if you want it.

Check the proper formatting in order to save file, use code hints to add options in file.

Hope that this is as clear as possible and help others to find that magic arduino.json file and understand where what and why.

Cheers.
> 32 votes

---
Tags: compile, ide
---


# Question
Title: Where does the Arduino core include the name of the sketch?
I'm trying to look through the Arduino core to find where "mySketch.ino" is included or implemented. In 'Arduino.h', the prototypes `void setup(void)` and `void loop(void)` are defined, in 'main.cpp', `setup(void)` and `loop(void)` are called, but I'm not sure where 'main.cpp' or any other related files makes a reference to the sketch.

Where does this occur?

# Answer
Compilation doesn't start with the Arduino.h or the core files; rather, it starts with your own sketch, "whatever.ino". Your .ino file includes Arduino.h into the compilation which makes references to core modules. That compilation leaves many references to to be satisfied, and itself satisfies several - setup() and loop(), for two. At link time, the linker is told to read not only your compiled module(s), but also the compiled core files, from which it can extracts the modules required to satisfy references made by your compiled code. Then it combines your module, and those modules required by it, into the load file that avrdude uploads to the Arduino.
> 2 votes

---
Tags: core-libraries
---


title: Being able to run two functions at once

text:
# Question
Title: Being able to run two functions at once
So I am doing a project where a bunch of servos are moving from 90 - 120 degrees and slowly speed up over time until they reach their max speed and so stay at that speed. This is being done by editing the delay under the servo sweep for loop. However though this works it doesn't work with the next component.

WHat I want to happen next is an MFRC522 RFID reader to always be scanning and at any time it detects a card and verifies it the servos from whatever speed they are now at start to slow down. The problem is I can't get the two functions to run simultaneously. IF the servo is running its sweep function it must finish before the RFID tag can scan. This makes the whole device look very lagy. Is there a way I can get the RFID scanner to be reading all the time even when the servo sweep for loop is working?

Here is the code: Please note that I have put printins everywhere to see how often the RFID is scanning etc just while I test the code out. I essentially have two functions one called nocardservo and yescardservo each one activating if there is a card there or not. Any help would be fantastic!!

```
#include <SPI.h>
#include <MFRC522.h>
#include <Servo.h>

#define RST_PIN     9       //
#define SS_PIN      10      //

MFRC522 mfrc522(SS_PIN, RST_PIN);   // Create MFRC522 instance

Servo myservo;
int pos = 0;
int y = 15;
int z = y;
void setup() {
  myservo.attach(6);
  myservo.writeMicroseconds(1518);
  Serial.begin(9600);       // Initialize serial communications with the PC
  while (!Serial);      // Do nothing if no serial port is opened (added for Arduinos based on ATMEGA32U4)
  SPI.begin();          // Init SPI bus
  mfrc522.PCD_Init();       // Init MFRC522
  //ShowReaderDetails();    // Show details of PCD - MFRC522 Card Reader details
  //Serial.println(F("Scan PICC to see UID, type, and data blocks..."));
}

void loop() {
  // Look for new cards
  if ( ! mfrc522.PICC_IsNewCardPresent()) {
nocardservo();
    return;
  }
  delay(20);
  Serial.println("carddetected");
  // Select one of the cards
  if ( ! mfrc522.PICC_ReadCardSerial()) {

  }
  Serial.println("correctcard");
  yescardservo();
delay(20);
return;
}

//***If card not detected this function runs**//

void nocardservo() {

  for (pos = 90; pos < 180; pos += 1) // goes from 0 degrees to 180 degrees
  { // in steps of 1 degree
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(15);                       // waits 15ms for the servo to reach the position
  }
  for (pos = 180; pos >= 90; pos -= 1) // goes from 180 degrees to 0 degrees
  {
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(15);

  }
}
}

//***If card is detected this function runs**//

void yescardservo() {

  for (pos = 90; pos < 180; pos += 1) // goes from 0 degrees to 180 degrees
  { // in steps of 1 degree
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(50);                       // waits 15ms for the servo to reach the position
  }
  for (pos = 180; pos >= 90; pos -= 1) // goes from 180 degrees to 0 degrees
  {
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(50);

  }

}

```

# Answer
> 4 votes
What you want to implement is described in Blink Without Delay. Basically, instead of using the delay function to just wait until your time has elapsed, you use variables to measure how much time has elapsed and only execute your operation when it has. In the mean time, you can check on other things and do those in the mean time.

# Answer
> 0 votes
have a look my example program below for you reference.

```
/*
 * Author BALASAIDULU.N
 * function -1 : Fading led with pwm pin 9
 * fucntion -2 : Blinking LED on pin 13
 * connect an LED on pin 9 with a 330 ohms resistor
 */
     int leda=9;
     int ledd=13;
int i,g,s1,s2;
int switchPin=8;

void setup() {
pinMode(ledd,OUTPUT);
pinMode(switchPin,INPUT);
}

void fading()
{
  st:
  if(s1==0){
if(s1==1){goto hy;}
analogWrite(leda,i);
delay(30);
i+=5;
if(i>255){s1=1;}
goto st1;
  }
hy:

if(i<0){s1=0;goto st;}
i-=5;
analogWrite(leda,i);
delay(30);
 st1:
delay(10);
}

void blinking()
{
digitalWrite(ledd,HIGH);
delay(30);
digitalWrite(ledd,LOW);
delay(30);

}
void loop() {

int g;
g=digitalRead(switchPin);
if(g==1) {delay(50);}
if(g==0){
blinking();
fading();}
}

```

---
Tags: arduino-uno
---


# Question
Title: Can an Arduino (Leonardo) be recognized via Bluetooth as a mouse/keyboard?
I'm new to wireless communication on Arduinos and doing research for a project. I'm looking at the Arduino Leonardo (which is like the Uno) which via its micro USB port can be automatically recognized as a mouse/keyboard. But also looking at a regular Uno wiFi Rev2.

I want to achieve the same result, but wirelessly via Bluetooth. Because I need to connect it to a device that only recognizes Bluetooth mice/keyboards and nothing else. If I buy something like the HC-05 how would the chip report itself?

How is the Bluetooth stack handled with regards to identification and authentication? Does it somehow copy the USB mouse/keyboard setup?

PS: Can anyone tell me if the Wifi Arduinos (Uno WiFi rev2) also have Bluetooth embedded?

# Answer
> 1 votes
> If I buy something like the HC-05 how would the chip report itself?

As an SPP. I.e., a serial port.

> How is the bluetooth stack handled with regards to identification and authentication?

By the firmware on the HC-05

> Does it somehow copy the usb mouse/keyboard setup?

No.

You need a USB device that can emulate a keyboard. That's not the HC-05. The host microcontroller has absolutely nothing to do with what capabilities the bluetooth interface has.

---
Tags: bluetooth, atmega32u4, arduino-uno-wifi
---


# Question
Title: Is it possible to upload an arduino sketch through the serial port (RX) instead of USB
In another words, is it possible to develop a custom bootloader so sketches can be uploaded via serial connection made using the RX/TX pins and not via the USB connector (I am using Pro Micro boards)? Thanks!

# Answer
No need to have a specific bootloader. The basic bootloader can do that (in Arduino that's the case so I hope this answer will apply in your case. But if not, the principle is certainly the same).

Once you perform a reset on the board, the bootloader look at the serial port during a short time. If something come, it checks if it's an hex file and if yes it send it to flash. The USB just use the RX input.

So you can send data using a direct connection or using for example a Bluetooh like HC-05. I do that for some project in order to update via Android: the Android app send an order to the Arduino, through Bluetooth. Receiving this, the Arduino RESET itself, and then the Android App send immediatly data.

On Arduino side: connect for example A0 to RESET PIN and perform a digitalWrite(PIN\_RESET,HIGH); Have also a look at Reset an Arduino Uno in code

After the RESET, the board will reply with 0x14 0x10 (so it send this to TX and so if you have a bluetooh module, you'll received than on your Android App (eg))

You must then send 0x50 0x20 to the board to tell it you enter programming mode. Then send 0x75 0x20 to get the id of the board in order to be sure you will send the HEX file for the right hardware. You will receive 0x14 XXX 0x10 where XXX = id of the board

Then you can send the HEX file.

For that, you will send it by blocks of 128 bytes

So start by dividing the HEX to know the number of blocks then loop against this number: Start at ADR=0 (adresse dest in flash) and send:

For each block:

1) Send 0x55, low byte of ADR, high byte of ADR, 0x20

2) check reply (must be 0x14 0x10)

3) Send the 128 bytes: 0x64, 0x00, 0x80, 0x46 then the 128 bytes and finish by 0x20 (0x80 is the size)

4) check reply (must be 0x14 0x10)

5) update ADR. Take care: ADR is a word pointer (2 bytes). So ADR = ADR+0X40

Loop on num of blocks

Finish the job by sending 0x51 0x20 (exit programing mode)

Some details:

* 0x46 before the 128 bytes tells you want to write in flash. Other codes are available eg for checking, getting data etc..

+ It seems mandatory to send each time 128 bytes. So if your last block is smaller, you need to add some '\0' to get a total of 128. I've been unable to get good results trying to change the 0x80 value and send less bytes. :(

It's not very easy and need tests to get a good code but that really fine to be able to have an Arduino the user can update.

Hope this will help.
> 5 votes

# Answer
Yes. You can develop a bootloader for the ATmega32u4 that will receive firmware over any interface (UART, SPI, I2C etc.).

Loading via UART is a solved problem. Look for the AVR109 bootloader.
> 1 votes

# Answer
Yes, there is an Optiboot fork supporting ATmega32U4 supporting hardware UART to upload Arduino sketches.

Also, a detailed instructable post explaining how to use it with Arduino Pro Micro.
> 1 votes

---
Tags: usb, serial, bootloader, atmega32u4
---


# Question
Title: Risks when commanding multiple chips with same address via I2C
I know that I2C devices are supposed to have unique addresses when used. What if I still use multiple devices with the same address, what can go wrong? Let me describe the situation:

I have multiple digital capacitors (NCD2400M by IXYS) and I would be using them so, that I always send the same command to every chip. I have no need of reading anything from those, which is the reason I was thinking why should I bother multiplexing my I2C line. I have no reason to identify them, only commanding. For the commanding I use Arduino (Nano currently, might change to some other Arduino model).

I have already tried commanding them simultaneously and it works like a charm. I tried so that I connected SDA and SCL of four chips and used RC circuit and square wave to check the rise time to verify that every chip indeed changes their capacitance.

However, I'm new to I2C protocol and I'm not yet aware of every detail. I guess there could be issues when one of the chips fail? Can I assume in this case that nothing goes wrong with the ACK/NACK bit since the chips are "identical"?

-RautSa

EDIT: After using correct keywords for searching I found this previously asked question. Based on that I now understand at least there would be a problem when only one of the chips tries to send NACK bit.

# Answer
> 1 votes
There is no risk for damaging something, but the risk is the reliability.

The NCD2400M operates at 3.3V and 5V, so that will work with every Arduino board.

Your question is very similar to the question that you already found: electronics.stackexchange.com/questions/417263/multiple-instances-of-same-device-on-i2c-bus.
There are a few specific Arduino things to mention.

During Arduino `setup()` a sensor is often checked if it is connected and if it is possible to communicate with a sensor. That would be impossible when the sensors share the I2C address.

The Arduino Wire library detects a bus error, for example when there are other I2C Masters on the bus, and returns with an error.
Since your NCD2400M are only Slaves, I think that they will not trigger a bus error.

You need some luck, and I can not guarantee that it will always work:

1. When the NCD2400M behaves like a normal I2C Slave and it is not too smart, then it does not detect that another one pulls the SDA low for an acknowledge.
2. Some sensors send a NACK when they are busy, I can not find such a note in the datasheet. You could write to the NCD2400M twice to be sure that they have received it.
3. When they have an internal clock and respond with different timings on the I2C bus, then you can set the SCL clock lower. For example `Wire.setClock(50000);` after `Wire.begin()` for a 50kHz SCL clock.

When one of NCD2400M is blown, then you are not able to identify the bad one. However, when one of the NCD2400M is blown, perhaps the whole circuit is no longer reliable.

For a good design, you should know if you are actually communicating with a sensor or just talking into thin air. When you have made more Arduino projects, then you know that it is essential to know if a sensor is connected or not.

Trying this solution to make it "easy" for now, might cause a lot of troubles later.

**Conclusion:** It will work. You can use it for a test. When you use it in the final version, you take the risk that it can cause a lot of troubles.

More about the basics of the I2C bus: http://www.gammon.com.au/i2c

# Answer
> 0 votes
Could always add a switch like DG406, DG409, or equivalent to select which cap is connected to SDA so that only one is commanded at a time. Pullup SDA on the output side so it is not floating at the chip.

---
Tags: arduino-nano, i2c
---


# Question
Title: Why digital pin not reading ON from push button switches connected to 5V and pull-down 10K resistor?
Here's my circuit:

And the code:

```
//pins
const int control1 = 2;
const int control2 = 3;
const int enable = 9;
const int pinDirection = 4;
const int pinOnOff = 5;
const int pot = A0;
//states
int stateOnOff = 0;
int stateOnOffPrev = 0;
int stateDirection = 0;
int stateDirectionPrev = 0;

int motorEnabled = 0;
int motorSpeed = 0;
int motorDirection = 1;

void setup(){
  pinMode(pinDirection, INPUT);
  pinMode(pinOnOff, INPUT);
  pinMode(control1, OUTPUT);
  pinMode(control2, OUTPUT);
  pinMode(enable, OUTPUT);

  digitalWrite(enable, LOW);
  Serial.begin(9600);
}

void loop(){
  stateOnOff = digitalRead(pinOnOff);
  delay(10);
  stateDirection = digitalRead(pinDirection);
  motorSpeed = analogRead(pot)/4;

  if(stateOnOff != stateOnOffPrev){
    if(stateOnOff == HIGH){
      motorEnabled = !motorEnabled;
    }
  }

  if(stateDirection != stateDirectionPrev){
    if(stateDirection == HIGH){
      motorDirection = !motorDirection;
    }
  }
Serial.println(stateDirection);
  if(motorDirection == 1){
    digitalWrite(control1, HIGH);
    digitalWrite(control2, LOW);
  }else{
    digitalWrite(control1, LOW);
    digitalWrite(control2, HIGH);
  }

  if(motorEnabled == 1){
    analogWrite(enable, motorSpeed);
  }else{
    analogWrite(enable, 0);
  }

  stateDirectionPrev = stateDirection;
  stateOnOffPrev = stateOnOff;

}

```

As you can see, the switch on pin 5 controls whether the motor is on and the potentiometer controls motor speed. Both work.

However, when the switch on pin 4 is closed the `stateDirection` variable still reads 0, or open circuit. It should when pressed change the direction of the motor via the H-bridge. I've tried everything I could, new switches, higher resistance. The only time it read HIGH is when I literally plugged switch out to GND.

Serial shows `stateDirection` as an unending chain of zeroes.

And finally the schematics from the original project.

Thank you.

\**PS: Forgive for lack of comments! But I think a good Arduino programmer should not need comments. \**

# Answer
> when the switch on pin 4 is closed the stateDirection variable still reads 0, or open circuit.

you could have pull-up enabled on that pin: with a nominal value of 50k, 10k pull-down is just on the cusp of making it a logic low.

solution?

1) disable pull-up; 2) use a stronger pull-down; 3) get rid of the pull-down and rely on the pull-up alone. ...
> 1 votes

# Answer
If it shows low when bypassing switch and jumping to ground.. Then either bad switch or maybe simply wrong orientation of switch.

Edit: if GND is making pin 5 HIGH in logic, then your button needs to jump to GND and have the resistor on 5v. Currently it is opposite according to your schematic.
> 1 votes

---
Tags: arduino-uno, digital, switch
---


title: ESP needs a reboot after wifi OTA flash

text:
# Question
Title: ESP needs a reboot after wifi OTA flash
I would like to use OTA in some of my less accessible esp's. I am using the examples/BasicOTA and BasicOTA\_test. My esp is a -01 model with 1Mb of flash.

I upload the BasicOTA to my esp through the COM port, then upload the BasicOTA\_test over WiFi. Everything appears to go OK, but the test sketch doesn't run until I press reset on the esp.

If I upload BasicOTA over the com port then upload a simple blink sketch over WiFi without the OTA code, it uploads fine then runs without a reset. But then, I can't upload over WiFi anymore.

If I have to hit reset every time I upload a new sketch that contains the OTA code, then why bother?

Tips would be appreciated.

# Answer
> 2 votes
You can add `ESP.restart()` in the following line to make it restart.

```
ArduinoOTA.onEnd([]() {
Serial.println("\nEnd");
ESP.restart();
});

```

Now you can upload code each time without hitting reset.

# Answer
> 1 votes
I've done some research and this appears to be a common problem while using OTA to update the ESP8266. In fact, this bug has been reported on their GitHub and it's due to the watchdog timer resetting after the ESP8266 is flashed via OTA.

It appears the problem can be solved by manually resetting (once) after you upload it via serial BEFORE you can upload it via OTA. After that, you shouldn't have any problems.

---
Tags: esp8266
---


title: Sending char arry via nRF24L01

text:
# Question
Title: Sending char arry via nRF24L01
I am trying to send a char array using Arduino Uno board and nRF24L01 modules

Here is the code for both transmitter and receiver:

```
 #include <SPI.h> //~ #include <TMRh20nRF24L01.h> //~ #include <TMRh20RF24.h>
 #include <nRF24L01.h>
 #include <RF24.h>

 #define CE_PIN   9
 #define CSN_PIN 10

 // NOTE: the "LL" at the end of the constant is "LongLong" type //
 These are the IDs of each of the slaves const uint64_t slaveID[2] =
 {0xE8E8F0F0E1LL, 0xE8E8F0F0E2LL} ;

 RF24 radio(CE_PIN, CSN_PIN); // Create a Radio

 char
> dataToSend[64]="e7665072be018b6b58ea9e40cf38553d6dc293cda4c9d94cda6e91ca61b3a073";

 unsigned long currentMillis; unsigned long prevMillis; unsigned long
> txIntervalMillis = 1000; int txVal = 0; float ackMessg[2]={1,2}; byte
 ackMessgLen = 4; // NB this 4 is the number of bytes in the 2 ints
 that will be recieved

 void setup() {

    Serial.begin(9600);
     Serial.println("Track Control Starting");
     radio.begin();
     radio.setDataRate( RF24_250KBPS );
     radio.enableAckPayload();
     radio.setRetries(3,5); // delay, count }

 //====================

 void loop() {

     currentMillis = millis();
     if (currentMillis - prevMillis >= txIntervalMillis) {

     radio.openWritingPipe(slaveID[0]); // calls the first slave
                                         // there could be a FOR loop to call several slaves in turn

     bool rslt;
     rslt = radio.write( dataToSend, sizeof(dataToSend) );
     Serial.print("\nRSLT (1 = success) ");
     Serial.println(rslt);
     Serial.print("Data Sent ");
     Serial.print(dataToSend[0]);
     Serial.print("  ");
     Serial.println(dataToSend[1]);
     if ( radio.isAckPayloadAvailable() ) {
         radio.read(ackMessg,ackMessgLen);
        Serial.print("Acknowledge received: ");
        Serial.print(ackMessg[0]);

```

> ```
>  #include <SPI.h>
>  #include <nRF24L01.h>
>  #include <RF24.h>
>
>
>  #define CE_PIN   9
>  #define CSN_PIN 10
>
>  // NOTE: the "LL" at the end of the constant is "LongLong" type
>
>  const uint64_t   deviceID = 0xE8E8F0F0E1LL; // Define the ID for this slave
>
> int valChange = 1;
>
>  RF24 radio(CE_PIN, CSN_PIN);
>
>  char  dataReceived[64];
>  int ackData[2] = {12,23};
>
>  void setup() {
>
>      Serial.begin(9600);
>      delay(1000);
>      Serial.println("Hand Controller Starting");
>      radio.begin();
>      radio.setDataRate( RF24_250KBPS );
>      radio.openReadingPipe(1,deviceID);
>      radio.enableAckPayload();
>      radio.writeAckPayload(1, ackData, sizeof(ackData));
>      radio.startListening();
>  }
>
>  void loop() {
>
>      if ( radio.available() ) {
>          radio.read( dataReceived, sizeof(dataReceived) );
>           for (int x = 0; x <64; x++) {
>        //if (dataReceived[x] < 16) {
>        //  Serial.write('0');
>      // }
>        Serial.print(dataReceived[x]);}
>        Serial.println();
>          radio.writeAckPayload(1, ackData, sizeof(ackData));
>
>          ackData[0] += valChange; // this just increments so you can see that new data is being sent
>      }
> }
>
> ```

And here is the output that I get

> Hand Controller Starting
>
> e7665072be018b6b58ea9e40cf38553d

# Answer
TX code

```
#include "sha256.h"
#include <Arduino.h>
#include "./printf.h"

#include <SPI.h>
//~ #include <TMRh20nRF24L01.h>
//~ #include <TMRh20RF24.h>
#include <nRF24L01.h>
#include <RF24.h>

#define CE_PIN   9
#define CSN_PIN 10

// NOTE: the "LL" at the end of the constant is "LongLong" type
// These are the IDs of each of the slaves
const uint64_t slaveID = 0xE8E8F0F0E1L  ;

RF24 radio(CE_PIN, CSN_PIN); // Create a Radio

unsigned long currentMillis;
unsigned long prevMillis;
unsigned long txIntervalMillis = 1000;
int txVal = 0;
int ackMessg[6];
byte ackMessgLen = 4;

uint8_t* hash;
uint8_t copy[32];
void printHash(uint8_t* hash) {
  int i;
  for (i=0; i<32; i++) {
    Serial.print("0123456789abcdef"[hash[i]>>4]);
    Serial.print("0123456789abcdef"[hash[i]&0xf]);
      copy[i]=hash[i];
  }
  Serial.println();
}

void setup() {
  printf_begin();

  uint32_t a;
  unsigned long ms;

  Serial.begin(9600);

  radio.begin();
    radio.setDataRate( RF24_2MBPS );
    radio.enableAckPayload();
    radio.setRetries(3,5); // delay, count

  // SHA tests
  Serial.println("Test: FIPS 180-2 B.1");
  Serial.println("Expect:ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad");
  Serial.print("Result:");
  ms = micros();
  Sha256.init();
  Sha256.print("abc");
  printHash(Sha256.result());
  Serial.println();
  for(int x=0;x<32;x++)
        {   Serial.print(copy[x]);
            Serial.print(" ");
                                  }
            Serial.println();

  Serial.print(" Hash took : ");
  Serial.print((micros() - ms));
  Serial.println(" micros");
  Serial.println();

  }

void loop() {

  currentMillis = millis();
    if (currentMillis - prevMillis >= txIntervalMillis) {

    radio.openWritingPipe(slaveID);
    bool rslt,rsltt;
    rslt = radio.write( copy, 32 );

    if ( radio.isAckPayloadAvailable() ) {
        radio.read(ackMessg,ackMessgLen);
        Serial.print("Acknowledge received: ");
        Serial.print(ackMessg[0]);
        Serial.print("  ");
        Serial.println(ackMessg[1]);
    }
    prevMillis = millis();
 }

}

```

Rx code

```
// HandController - the slave or the receiver

    // http://tmrh20.github.io/RF24/

    //~ - CONNECTIONS: nRF24L01 Modules See:
    //~ http://arduino-info.wikispaces.com/Nrf24L01-2.4GHz-HowTo
    //~ 1 - GND
    //~ 2 - VCC 3.3V !!! NOT 5V
    //~ 3 - CE to Arduino pin 9
    //~ 4 - CSN to Arduino pin 10
    //~ 5 - SCK to Arduino pin 13
    //~ 6 - MOSI to Arduino pin 11
    //~ 7 - MISO to Arduino pin 12
    //~ 8 - UNUSED

#include <SPI.h>
//~ #include <TMRh20nRF24L01.h>
//~ #include <TMRh20RF24.h>
#include <nRF24L01.h>
#include <RF24.h>

#define CE_PIN   9
#define CSN_PIN 10

// NOTE: the "LL" at the end of the constant is "LongLong" type

const uint64_t   deviceID[2] ={ 0xE8E8F0F0E1LL,0xE8E8F0F0E1LL}; // Define the ID for slaves

int valChange = 1;

RF24 radio(CE_PIN, CSN_PIN);
RF24 radioo(CE_PIN, CSN_PIN);
uint8_t  dataReceived[32];

int ackData[2] = {12,23};

void setup() {

    Serial.begin(9600);
    Serial.println("Hand Controller Starting");
    radio.begin();
    radio.setDataRate( RF24_2MBPS );
    radio.openReadingPipe(1,deviceID[1]);
    radio.enableAckPayload();
    radio.writeAckPayload(1, ackData, sizeof(ackData));
    radio.startListening();

}

void loop() {

 unsigned long startTimer = millis();

    if ( radio.available() ) {
        radio.read( dataReceived, sizeof(dataReceived) );
        radio.writeAckPayload(1, ackData, sizeof(ackData));
        Serial.println();
        //Serial.println(startTimer);
        Serial.println();
        for(int x=0;x<32;x++)
        {Serial.print(dataReceived[x]);
        Serial.print(" ");}}
        ackData[0] += valChange; // this just increments so you can see that new data is being sent

    }

```

it is fully working now with both outputs on the same size
> 1 votes

---
Tags: arduino-uno
---


# Question
Title: Save Leading Zero HEX into String RFID RC522 Arduino
I'm using RC522 to read RFID card. All is until if the HEX leading by 0 then i can't save it into String. But if i print it to Serial all is well. Here is my code:

```
#include <SPI.h>
#include <MFRC522.h>
#include <stdlib.h>

#define RST_PIN         9
#define SS_PIN          10

String inStringHex = "";

MFRC522 mfrc522(SS_PIN, RST_PIN);

void setup() {
  Serial.begin(9600);
  SPI.begin();
  mfrc522.PCD_Init();
}

void loop() {
  // Look for new cards
  if (mfrc522.PICC_IsNewCardPresent() && mfrc522.PICC_ReadCardSerial())
  {
    //Serial.print("Card UID:");
    for (byte i = 0; i < 4; i++) {
      Serial.print(mfrc522.uid.uidByte[i] < 0x10 ? "0" : "");
      Serial.print(mfrc522.uid.uidByte[i], HEX);
      inStringHex += String(mfrc522.uid.uidByte[i], HEX);
    }

    Serial.println();
    Serial.println(F("Hex normal"));
    Serial.print(inStringHex);
    Serial.println();
    Serial.println();

    inStringHex = "";
    delay(5000);
  }
}

```

Here is what displayed in serial monitor:

What i want is the String under "Hex normal" would be "04292e5a" not "4292e5a"

Please anyone help me. Thank You.

# Answer
`String(mfrc522.uid.uidByte[i], HEX)` means you want to convert number into hexadecimal string repesentation, if you pass 4 as input parameter, it will convert it into "4", not "04". You need to apply similar approach as you have used when printing the value through UART. For example:

```
if (String(mfrc522.uid.uidByte[i] < 0x10)
  inStringHex += " ";
inStringHex += String(mfrc522.uid.uidByte[i], HEX);

```

Personally, I would recommend switching from Strings into static buffers (because arduino has too small memory to use dynamic allocation and there could be issue with running out of memory due to memory fragmentation):

```
char id[16];
sprintf(id, "%02x%02x%02x%02x", mfrc522.uid.uidByte[0], mfrc522.uid.uidByte[1], mfrc522.uid.uidByte[2], mfrc522.uid.uidByte[3]);

```
> 1 votes

# Answer
you can try ;

```
for (byte i=0; i < uidLength; i++)
{
  Serial.print(uid[i] < 0x10 ? " 0" : "");
  Serial.print(uid[i], HEX);
  if (uid[i] < 0x10) inStringHex += "0";
      inStringHex += String(uid[i], HEX);
} Serial.println(); Serial.println(inStringHex);

```
> 1 votes

---
Tags: arduino-uno, string, rfid
---


# Question
Title: Converting code for ATTINY85 to ATMEGA2560. Pin change interupts
I have code that compiles correctly for an ATTINY85 board using the ARDUINO IDE but I don't have an ATTINY85 board. I have an Arduino Mega ATMEGA2560 and when I select this board in the Arduino IDE the code does not compile and throws this error message

```
sketch_feb21a:216:3: error: 'GIMSK' was not declared in this scope

   GIMSK |= _BV(PCIE);                     // Enable Pin Change Interrupts

   ^

sketch_feb21a:216:16: error: 'PCIE' was not declared in this scope

   GIMSK |= _BV(PCIE);                     // Enable Pin Change Interrupts

                ^

sketch_feb21a:217:3: error: 'PCMSK' was not declared in this scope

   PCMSK |= _BV(PCINT2);                   // Use PB3 as interrupt pin

   ^

exit status 1
'GIMSK' was not declared in this scope

```

Here is the code snippet that throws the error

```
void sleep()
{
  GIMSK |= _BV(PCIE);                     // Enable Pin Change Interrupts
  PCMSK |= _BV(PCINT2);                   // Use PB3 as interrupt pin
  ADCSRA &= ~_BV(ADEN);                   // ADC off
  set_sleep_mode(SLEEP_MODE_PWR_DOWN);    // replaces above statement

  MCUCR &= ~_BV(ISC01);
  MCUCR &= ~_BV(ISC00);       // Interrupt on rising edge
  sleep_enable();                         // Sets the Sleep Enable bit in the MCUCR Register (SE BIT)
  sei();                                  // Enable interrupts
  sleep_cpu();                            // sleep

  cli();                                  // Disable interrupts
  PCMSK &= ~_BV(PCINT2);                  // Turn off PB3 as interrupt pin
  sleep_disable();                        // Clear SE bit
  ADCSRA |= _BV(ADEN);                    // ADC on

  sei();                                  // Enable interrupts
}

ISR(PCINT0_vect) {
   /*noInterrupts();
   while (digitalRead(BUTTON_PIN) == LOW);

   delay(50);
   while (digitalRead(BUTTON_PIN) == LOW);
   playTrack(1 + (curTrack++ % 2));
   delay(400);

   interrupts();*/

}

```

# Answer
Each processor has different registers, things that control stuff like interrupts, input and output. I would not expect code written for one processor, especially if it directly accesses the registers, to work on another processor.

You would need to look at the datasheet for the Atmega2560 and see how to control its pin change interrupts.
> 2 votes

---
Tags: interrupt, atmega2560, port-mapping
---


# Question
Title: Unusual use of << operator... not a bit shift?
Poking through the example code of SDFS, I saw the following:

```
static ArduinoOutStream cout(Serial);
// F stores strings in flash to save RAM
cout << F("\ntype any character to start\n");

```

What exactly is \<\< doing in this case? Moreover, F seems to never be defined prior to this. This seems like a useful trick, but I don't understand how it works.

full code available here: https://github.com/greiman/SdFs/blob/master/examples/SdInfo/SdInfo.ino

# Answer
> What exactly is \<\< doing in this case?

It's directing the data into an output device (stream).

Yes, it's confusing using the same symbols for more than one thing...

> Moreover, F seems to never be defined prior to this.

`F()` is a macro. It's defined by the Arduino core in WString.h:

```
#define F(string_literal) (reinterpret_cast<const __FlashStringHelper *>(PSTR(string_literal)))

```
> 2 votes

# Answer
To address your confusion with the bitshift operator;

It indeed is commonly used as a the arithmetic operator for bitshift, but appears to be 'overloaded', so that when used with streams, it is an 'insertion operator'.

> In particular, stream insertion and stream extraction overloads of operator\<\< and operator\>\> return T&.

https://en.cppreference.com/w/cpp/language/operator\_arithmetic

Basically there would be two definitions of the "\<\<" operator function:

```
function <<(integer){//Shift bits}
function <<(stream){//Join streams}

```
> 1 votes

---
Tags: serial, flash, stream
---


title: HC-05 bluetooth module

text:
# Question
Title: HC-05 bluetooth module
I was able to connect my HC-05, pair it with my phone, and I can see data in the Serial Bluetooth Terminal Android App. But when I try to connect it to a certain application it says it cannot find it. Can the application force a certain version of Bluetooth? Am I missing something? Thanks.

# Answer
> 2 votes
The HC-05 modules use bluetooth 2.0. Certain apps would only be compatible with bluetooth 4.0 devices (BLE - Bluetooth Low Energy), such as an HM10 or AT09.

It could be that your app requires the device to use v4.0+. Are you able to find, and pair with the device using your android's default bluetooth device scanning/pairing features?

Assuming that your app does not require v4.0+, have you removed the connection from 'en'/'ch\_pd' to 3.3v? If that was still connected (which is a required connection to enter AT command mode), then your bt module would not be able to accept incoming pair requests etc.

hope this has helped. :)

---
Tags: arduino-mega, bluetooth, hc-05
---


# Question
Title: Define preset colors using FastLed library
I'm using an addressable 150 led strip and an Arduino Nano to control it, using `FastLed` library.

I'm tring do create a function `turn_on_leds`, which gets 4 parameters:

1) delay time for lighting a led in the loop, 2) direction ( not relevant for now), 3) color index for `colors` array , 4) brightness percentage.

**Problem #1**: a color array is defined to select from a preset definitions of colors (Fastled reference, but when selecting `col_indx` =2, meaning `colors[2]`, leds are not lit in `Red` as they should, AND when setting `leds[i]=0xFF0000`, the right result is set.

**Problem #2**: at `loop` there is a for intended for raise bightness from 0 to 100, BUT the results are 0 for first iteration and 9 for all others.

Appreciate any HELP!!

Guy

Code:

```
#include <FastLED.h>

#define NUM_LEDS 10
#define BRIGHTNESS  55
#define DATA_PIN 7

char *colors[] = {0x000000,0xFFFFFF,0xFF0000,0x008000,0x0000FF}; // black, white,r,g,b
CRGB leds[NUM_LEDS];
int t = 0;

void setup() {
  Serial.begin(9600);
  FastLED.addLeds<NEOPIXEL, DATA_PIN>(leds, NUM_LEDS);
  //  FastLED.setBrightness(BRIGHTNESS);
}

void turn_leds_on(int del_1, bool dir_1, int col_indx, int bright_1) {
  if (dir_1 == true ) { // start to end
    for (int i = 0; i <= NUM_LEDS; i++) {
      leds[i] = 0xFF0000;//colors[col_indx];
      FastLED.setBrightness(bright_1*255/100);
      FastLED.show();
      delay(del_1);
    }
  }
}

void loop() {
  Serial.println(t);
  turn_leds_on(50, true, 2, 100);
  delay(1000);
  //  turn_leds_on(50, true, 0, t);
  //  delay(1000);

  if (t < 100 ) {
    t += 10;
  }
  else {
    t = 0;
  }
}

```

# Answer
Your `colors` array should be `CRGB` type, not `char *`.

```
CRGB colors[] = {0x000000,0xFFFFFF,0xFF0000,0x008000,0x0000FF}; // black, white,r,g,b

```

For your second problem - you are overflowing the bounds of your LEDs array:

```
for (int i = 0; i <= NUM_LEDS; i++) {
  leds[i] = 0xFF0000;//colors[col_indx];

```

You are going from 0 to 10 inclusive. That's 11 iterations. There is no such array slice as `leds[10]`, so the value you write to it ends up overwriting the next two bytes in memory - and those happen to be occupied by the variable `t`.
> 1 votes

---
Tags: led
---