# Question
Title: Is extra hardware and components needed to connect the bare MCU directly to a PCB, without a shield?
As a hobbyist I code in a variety of arduino's and in Digispark's (Attiny 85 and 167).

But I'm doing a project with space contraints, so I'd need to use just the MCU directly over my pcb.

Apart from a voltage regulator (to get the VIn to 5V or 3.3V) do I need extra components to mount the MCU to my PCB?

DO I need crystals, capacitors, etc? Or the MCUs (mostly AtMega 32u4 and Attiny85 and Attiny167) have it all what's needed inside them?

I'll program the MCU before soldering on to the PCB, so there's no need for USB or programming stuff or leds.

Thanks!

# Answer
> 1 votes
> DO I need crystals, capacitors, etc? Or the MCUs (mostly AtMega 32u4 and Attiny85 and Attiny167) have it all what's needed inside them?

You don't need a crystal if you use the internal clock of the MCU (which means setting the fuses right and compiling your code to expect the right clock frequency). However if you are using a direct USB interface (such as for the ATMega32U4) then you will need a crystal as the precise timing is required for USB to operate.

You will need capacitors. Decoupling capacitors on all the power pins are not optional and must be included.

You will need a pullup resistor on the RESET pin unless you have set the fuse to disable the RESET pin (not advisable since it will prevent ICSP programming in the future - but can be useful for low pin-count chips).

---
Tags: arduino-leonardo, attiny85
---


# Question
Title: DS2413 One Wire IC read and store the addresses of individual IC's
Hy, Here I using 10 DS2413 to control gpios, it works very well with arduino ,I read the 10 ic address and store it in a 2D array, I want to control the individual IC using their address .Here all works well. My problem is the Ic address are not store in arrange wise manner. For ex, I have 10 IC's, Each IC's have unique address, The address of first IC1 is store in arr1, address of ic2 is arr2 and address of ic3 is store in arr3..... what i need is If i Swap the IC1 and IC2 the address of IC2 is store in arr1 and IC1 address is store in arr2.

# Answer
The OneWire system has no concept of the arrangement of the bus. All it knows is the addresses, and it always searches for those addresses in a pre-defined order.

No matter what arrangement you have on the bus the devices will always be found in the same order.

You can think of it akin to a teacher taking the register in class. They call out the names in alphabetical order and the pupils answer (if they are there). All it tells the teacher is who is there and who isn't. It doesn't give them any information about where in the class the pupil is sat.

You can read more about how the address searching is done here.
> 1 votes

---
Tags: c++
---


# Question
Title: Uno - ESP32 SoftwareSerial communication won't work
I have two boards, Uno and ESP32 and my goal is to send data from the Uno to the ESP. I made a voltage divider so my ESP doesn't get fried and I use the communication only in **ONE** way, strictly UNO -\> ESP32. I use PIN 9 from my UNO to send data and RX2 (16) from my ESP to receive the data. How ever, I get errors and can't make it work.

This is my Uno code:

```
#include <SoftwareSerial.h>

SoftwareSerial softPort(-1, 9);

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

void loop() {
softPort.print("100");
delay(2000);

}

```

and my ESP code:

```
#include <SoftwareSerial.h>

#define RXD2 16
#define TXD2 -1

SoftwareSerial Serial2(RXD2, TXD2); // RX, TX

void setup() {
Serial.begin(115200);
Serial2.begin(9600, SERIAL_8N1, RXD2, TXD2);

}

void loop() {
Serial.println("Data received:");
Serial.println(Serial2.read());
delay(200);

}

```

I'm getting an error that says

> no matching function for call to 'SoftwareSerial::begin(int, int, int, int)'

# Answer
On the ESP32 you would *never* use SoftwareSerial except under *exceptional* circumstances.

The ESP32 has three hardware UARTs that can be mapped to *any* pin combination on the board.

The general usage is:

```
HardwareSerial Serial2(1); // Use UART channel 1

void setup() {
    Serial2.begin(9600, SERIAL_8N1, RXD2, TXD2);
}

```

UARTs are numbered 0-2 where 0 is pre-assigned to the TX/RX (USB connection) pins and is used for debugging and programming. UARTs 1 and 2 are not normally assigned to anywhere and you can use them as you see fit.
> 0 votes

---
Tags: arduino-uno, softwareserial, esp32
---


# Question
Title: Using a pushbutton to power Arduino on and off
I need help adding a pushbutton to provide power to an Arduino to save power, as I am using a battery and the same button to power it off. This is the circuit I wish to implement.

Thanks.

# Answer
> 1 votes
You can use the button as a switcher for the Arduino power. Just wire up the button between the battery + out and the Arduino's Vin port.

# Answer
> 0 votes
You can attach an interrupt and just turn the arduino in sleep mode. If one of your mudules drain power while beeng inactive and drains less than 20mah while working than connect the VCC to one of the digital pins and when the arduino wakes up just turn the pin to HIGH.

# Answer
> 0 votes
This is a hardware/software "bootstrapping" problem: you need a power switch to be controlled by an Arduino, but the power switch also feeds power to, or turns ON the Arduino, which means the Arduino can't control the power switch until the Arduino is ON, and the Arduino can't be ON until the power switch is ON. Each relies on the other, so you must "bootstrap" it to turn it on and get the cycle started.

The process will look like this: you mechanically press a button with your finger, which controls either the Gate of a MOSFET transistor or the Base of a BJT transistor (or it could even power ON a normally-off relay), momentarily turning it ON. This split-second of ON time is just enough to turn on the Arduino, which now commands a signal to the Gate or Base to keep the transistor ON. Now, the Arduino maintains its own power, continually sending the necessary signal to the transistor to keep the transistor ON, which in turn powers the Arduino to keep the Arduino ON. Now, you can press another button to turn the Arduino OFF. This other button press will be read simply as a button press and the Arduino will then command the digital output pin to stop sending the signal which keeps the transistor ON, thereby turning the transistor OFF, which then turns the Arduino OFF. Now, the whole system is 100% OFF. The Arduino isn't even in sleep mode, it's just 100% not powered anymore. You use your finger press on the ON button again to bootstrap the whole system and start the process over again.

As for all of the details, this is an interesting problem I've been wanting to implement for years. I suspect it could be done with a single button, but haven't gone through the design to prove it yet. Meanwhile, for simplicity's sake, just use two separate buttons: one for ON and one for OFF, as I describe above.

---
Tags: power, button
---


# Question
Title: How to properly put a u8g2 handle in a class
I'm trying to create a small battery powered alarm clock using an Arduino MKRZero and a generic SH1106-controlled, 128x64 pixel oled.

I started out just dumping all code into a single file named `Clock.ino`. As the code got bigger, I started to split out functionality into separate classes. This went fine for timekeeping and alarms, but when I tried to do the same for the display functionality, I ran into an issue.

Now I wanted to split out my display code into a separate class. The working code before the refactor looks a bit like this:

## `Clock.ino`

```
//Display stuff
#include <U8x8lib.h>
#ifdef U8X8_HAVE_HW_SPI
#include <SPI.h>
#endif
U8X8_SH1106_128X64_NONAME_HW_I2C u8x8(/* reset=*/ U8X8_PIN_NONE);

void setup(void) {
  u8x8.begin();
}

void print_clock([...]) {
  [...]
  u8x8.setCursor(0,3);
  u8x8.print("23:59:59");
  [...]
}

void loop(void) {
  [...]

  // Main clock
  print_clock(clk.datetime);

  [...]
}

```

I tried to split it out like this:

## `Clock.ino`

```
#include "Display.h"

Display disp;

void setup(void) {}

void loop(void) {
  [...]

  // Main clock
  disp.print_clock([...]);

  [...]
}

```

## `Display.cpp`

```
#include "Display.h"

Display::Display() {
  this->u8x8.begin();
}

void Display::print_clock([...]) {
  [...]
  this->u8x8.setCursor(0,3);
  this->u8x8.print("23:59:59");
  [...]
}

```

## `Display.h`

```
//Display stuff
#include <U8x8lib.h>
#ifdef U8X8_HAVE_HW_SPI
#include <SPI.h>
#endif

class Display {
  public:
    Display();
    void print_clock([...]);
  private:
    U8X8_SH1106_128X64_NONAME_HW_I2C u8x8(/* reset=*/ U8X8_PIN_NONE);
}

```

That didn't work, gave me a whole list of errors, all similar to these:

```
  5 In file included from /home/simon/Arduino/libraries/U8g2/src/U8x8lib.h:45:0,
  6                  from sketch/Display.h:9,
  7                  from sketch/Display.cpp:1:
  8 /home/simon/Arduino/libraries/U8g2/src/clib/u8x8.h:323:23: error: expected identifier before numeric c    \>onstant
  9  #define U8X8_PIN_NONE 255
 10                        ^
 11 sketch/Display.h:26:55: note: in expansion of macro 'U8X8_PIN_NONE'
 12      U8X8_SH1106_128X64_NONAME_HW_I2C u8x8(/* reset=*/ U8X8_PIN_NONE);
 13                                                        ^~~~~~~~~~~~~
 14 /home/simon/Arduino/libraries/U8g2/src/clib/u8x8.h:323:23: error: expected ',' or '...' before numeric    \> constant
 15  #define U8X8_PIN_NONE 255
 16                        ^
 17 sketch/Display.h:26:55: note: in expansion of macro 'U8X8_PIN_NONE'
 18      U8X8_SH1106_128X64_NONAME_HW_I2C u8x8(/* reset=*/ U8X8_PIN_NONE);
 19                                                        ^~~~~~~~~~~~~
 20 sketch/Display.cpp: In constructor 'Display::Display()':
 21 Display.cpp:8:9: error: invalid use of member function 'U8X8_SH1106_128X64_NONAME_HW_I2C Display::u8x8    \>(int)' (did you forget the '()' ?)
 22    this->u8x8.begin();
 23    ~~~~~~^~~~

```

So I tried rewriting it in such a way that the `u8xu` var is global like it was before, defining it in `Display.cpp` and getting rid of the `this->` before the `u8x8.` method calls in the `Display::` methods. That didn't work either. It compiles, but my display stays blank and the arduino gets stuck (does not interface with serial anymore until I hard-reset it).

At some point I rewrote the code such that I passes on the variable to the Constructur for `Display`, but I think I completely botched that as I couldn't get it to compile.

so, main question: **how do I instantiate an object inside my class, so it becomes available as a private variable?**

If anyone wants to look at the full code, it's right here: https://github.com/ffective/wake-up/tree/master/Clock

The latest commit is the way of splitting up I described last: using a global variable. The previous commit is the working code with all Display methods just globally in `Clock.ino`. Unfortunately I didn't save my attempts for putting it as a private variable.

# Answer
> 0 votes
You need to create a "blank" object in your class and then instantiate it in your constructor initializer list:

```
class Display {
    private:
        U8X8_SH1106_128X64_NONAME_HW_I2C u8x8;

    public:
        Display() : u8x8(U8X8_PIN_NONE) {}
        void print_clock([...]);
};

```

The object in `private` is not instantiated until the constructor is called by the calling of the `Display()` constructor.

From then on you can use `u8x8.whatever()` as you would normally.

# Answer
> 0 votes
First errors aren't much helpful, but the last one about member function explains it all. You are not creating member variable of that type, you are trying to create member function (with invalid parameter list) that returns `U8X8_SH1106_128X64_NONAME_HW_I2C` value.

This code is perfectly valid:

```
class Display {
  public:
    Display() { u8x8.begin(); }

    // you can also use different initializer for u8x8 object (default one is never executed in this case):
    Display(uint8_t resetPin) : u8x8{resetPin} { u8x8.begin(); }

  private:
    U8X8_SH1106_128X64_NONAME_HW_I2C u8x8 { U8X8_PIN_NONE };
};

```

and in the sketch:

```
// creating instance:
Display disp{ 5 };

// or with default constructor and reset pin value
Display disp2;

```

---
Tags: programming, class, u8glib, oled, object-oriented
---


# Question
Title: Arduino Due analog output has 500mV offset
I use a simple serial connection to tell the Due what to output into an analog output pin. However, the outputs are offset about 550mV (as seen on an oscilloscope) and the maximum value of 255 gives ~2.7V. What am I missing? Why can't the DAC output 0V - 3.3V mapped onto 0 - 255 values?

```
int output = DAC1; // analog output pin
String inData;

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

void loop() {
  while (Serial.available() > 0) {
    char value = Serial.read();
    inData += value;
    if(value == '\n'){
      val = inData.toInt(); // 0..255
      analogWrite(output, val);
      Serial.println(val);
      inData = "";
    }
  }
}

```

# Answer
I don't know how old this thread is, anyway I thought it doesn't hurt to give some insight because I experienced the same problem. Look at: http://www.atmel.com/Images/Atmel-42187-ATSAM3X-and-ATSAM3A-Series-Checklist\_AP-Note\_AT03462.pdf page 13: DAC0 and 1 voltage lays between 1/6 ADVREF and 5/6 ADVREF which corresponds to approximately ADVREF=3.2v; Span is (4/6)\*3.2 = 2.1v for periodic signals, Offset can be removed by using a small decoupling capacitor which will act as a high pass filter. Hope this helps
> 2 votes

# Answer
```
int output = DAC1; // analog output pin
String inData;
int val;

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

}

void loop() {
  while (Serial.available() > 0) {
    char value = Serial.read();
    inData += value;
    if(value == '\n'){
      val = inData.toInt(); // 0..255
      val=constrain(val, 543, 2720);
      analogWrite(output, map(val,543,2720, 0, 255));
      Serial.println(val);
      inData = "";
    }
  }
}

```
> 0 votes

---
Tags: arduino-due, analogwrite
---


# Question
Title: declaration of 'varDay' as array of references error
I am trying to write a function to store the date and time data from an RTC module. I have used char arrays to implement the function. I get "*declaration of 'varDay' as array of references*" error upon compilation.

I am still learning about char arrays and manipulating them so may be I am making a very obvious mistake. Could you please explain what I am doing wrong?

```
#include <RTClib.h>

RTC_DS3231 rtc;

void setup() {
  Serial.begin(115200);
#ifndef ESP8266
  while (!Serial); // wait for serial port to connect. Needed for native USB
#endif

  if (! rtc.begin()) {
    Serial.println("Couldn't find RTC");
    Serial.flush();
    abort();
  }

  if (rtc.lostPower()) {
    Serial.println("RTC lost power, let's set the time!");
    // When time needs to be set on a new device, or after a power loss, the
    // following line sets the RTC to the date & time this sketch was compiled
    rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
  }

}

void loop() {
  unsigned long newTime = millis();
  static unsigned long oldTime = 0;

  char varYear [] = "1234";
  char varMonth [] = "00";
  char varDay [] = "00";
  char varHour [] = "00";
  char varMinute [] = "00";
  char varSecond [] = "00";
  unsigned int varEpoch;
  char varDate [] = "123456789";
  char varTime [] = "12345678";
  char dash [] = "-";
  char colon [] = ":";

  if (newTime - oldTime >= 60000) {
    oldTime = newTime;

    getDate(varDay, varMonth, varYear, varDate, dash, colon);
  }

}
void getDate (char &varDay[3], char &varMonth[3], char &varYear[5], char &varDate[11], char &dash[2], char &colon[2]) {

  DateTime now = rtc.now();
  strcpy (varDay, now.day());
  strcpy (varMonth, now.month());
  strcpy (varYear, now.year());

  strcat (varDate, varDay) ;
  strcat (varDate, dash);
  strcat (varDate, varMonth);
  strcat (varDate, dash);
  strcat (varDate, varYear)

  Serial.println(varDate);
}

```

# Answer
`char &varDay[3]` is an array of 3 references to type char, not a reference to type char of size 3.

Instead just pass a pointer:

```
void getDate (char *varDay, char *varMonth, char *varYear, char *varDate, char *dash[2], char *colon[2]) {

```

Also:

```
strcpy (varDay, now.day());
strcpy (varMonth, now.month());
strcpy (varYear, now.year());

```

That won't work. You can't copy a number into a string. now.day() etc need converting to a string first.

It would be better to format your string with snprintf:

```
snprintf(varDate, 11, "%02d-%02d-%04d", now.day(), now.month(), now.year());

```
> 1 votes

---
Tags: c-string
---


# Question
Title: Mega 2560 does not play audio file when I want. It plays when the first condition is met, but not the other
Okay, so I am making a jewelry box for my niece that will spin a necklace holder with a stepper motor, play an audio file and turn on LED lights. I am using an Arduino MEGA 2560.

The flow is this:

1. **ringDoor open and necklaceDoor closed:** LED on, stepper spin, audio plays.
2. **ringDoor closed and necklaceDoor open:** LED on and audio plays, no stepper motor.
3. **Both doors closed:** Everything off or off after delay.
4. **Both doors open:** LED on and music plays, no stepper motor.

My issue is that with the doorLatch open, the audio plays as it should. No issues, but if I only open doorLatch2, no audio plays. If I open doorLatch and then doorLatch2, audio will play. If I open in reverse, no audio will play. I have tried adding an `if` statement by itself with an "or" in the loop section to check for either door open and I cannot put it in the setup section because that just continuously plays with latches open or closed. I currently have it to where music plays with doorLatch open. The extremely strange portion to me is that if I put the tmrpcm.play in the first else statement, the audio will play after opening and closing doorLatch2.

So what I would like is for audio to play and loop as long as either door is open. PLEASE HELP! WHAT AM I DOING WRONG?!?!?!?!?!

Code:

```
#include <SD.h>
#include <TMRpcm.h>
TMRpcm tmrpcm;

#include <Stepper.h>
const int stepsPerRevolution = 2048;
const int doorLatch=2;   //Ring door
const int doorLatch2=6;  //Necklace door
const int relayPower=13; //Turn relay on

Stepper myStepper = Stepper(stepsPerRevolution, 8, 10, 9, 11);

void setup() {
  Serial.begin(9600);
  Serial.print("\nInitializing SD card...");

  // set this to your card type and cs pin
  if (!SD.begin(53)) {
    Serial.println("failed!");
    return;
  }
  Serial.println("done.");

  tmrpcm.speakerPin = 46;

  myStepper.setSpeed(5);
  pinMode(doorLatch,INPUT);
  pinMode(doorLatch2,INPUT);
  pinMode(relayPower,OUTPUT);
  digitalWrite(doorLatch,HIGH);
  digitalWrite(doorLatch2,HIGH);

}

void loop() {

  if ((digitalRead(doorLatch)==HIGH)&&(digitalRead(doorLatch2)==HIGH)) {
    //ring door and necklace door is closed
    digitalWrite(relayPower,LOW);

  }
  else {
    //ring door is open, lights on, stepper motor spinning, music playing
    digitalWrite(relayPower,HIGH);

  }

  if ((digitalRead(doorLatch2)==HIGH)&&(digitalRead(doorLatch)==LOW)) {
    //ring door open and necklace door closed

    digitalWrite(relayPower,HIGH);

    myStepper.step(stepsPerRevolution);
    delay(500);
    myStepper.step(-stepsPerRevolution);
    delay(500);

  }
  else {
    tmrpcm.play("music.wav");
  }
}

```

****NEW CODE, NEW PROBLEM, but closer******Updated names and notes for easier following**\*** New problem is if I open the necklaceDoor first, nothing happens. I have to open the ringDoor first. That turns everything on. Then with the necklaceDoor open, the stepper motor will turn off and the lights and music will continue to play. But I want to be able to open the necklaceDoor first and play the music with the lights. I do not want it to matter which one is opened first. I also realized that if I can get an or statement to work within an and statement I could do away with the fourth if statement completely. Both ringDoor open and necklaceDoor open, as well as ringDoor closed and necklaceDoor open have the same outcome. Now if I switch the door states in the third if statement, I get necklaceDoor only plays audio after closed(original problem) but if both doors are open and then ringDoor is closed, the music will shut off after the stepper timer is done and then start again after necklaceDoor is closed?!?!?!?

```
#include <SD.h>
#include <TMRpcm.h>
#include <Stepper.h>
TMRpcm tmrpcm;

const int stepsPerRevolution = 2048;   //Number of pulses per revolution
const int ringDoor=2;                  //Ring door
const int necklaceDoor=7;              //Necklace door
const int relayPower=22;               //Turn relay on

Stepper myStepper = Stepper(stepsPerRevolution, 8, 10, 9, 11);

void setup() {
  Serial.begin(9600);                         //Start connection with computer

  if (!SD.begin(53))                         //Chip pin on card
  {
    Serial.println("failed!");                //SD card did not read
    return;
  }

  tmrpcm.speakerPin = 46;                      //Speaker output pin
  myStepper.setSpeed(5);                       //Stepper speed
  pinMode(ringDoor,INPUT);                     //Check state of ring door magnetic switch, NO
  pinMode(necklaceDoor,INPUT);                 //Check state of necklace door magnetic switch, NO
  pinMode(relayPower,OUTPUT);                  //Relay enable for 12V LED
  digitalWrite(ringDoor,HIGH);                 //Make door closed read high on start up
  digitalWrite(necklaceDoor,HIGH);             //Make door closed read high on start up
  digitalWrite(relayPower,LOW);                //Make relay off on start up
}

void loop() {

  if ((digitalRead(ringDoor)==HIGH)&&(digitalRead(necklaceDoor)==HIGH))
  {                                                                                //ring door and necklace door is closed, everything is off
    digitalWrite(relayPower,LOW);
  }

  if ((digitalRead(ringDoor)==LOW)&&(digitalRead(necklaceDoor)==HIGH))
  {                                                                                //ring door is open and necklace door is closed, lights on, stepper motor spinning, music playing
    digitalWrite(relayPower,HIGH);
    tmrpcm.play("music.wav");
    myStepper.step(stepsPerRevolution);
    delay(500);
    myStepper.step(-stepsPerRevolution);
    delay(500);
  }

  if ((digitalRead(ringDoor)==HIGH)&&(digitalRead(necklaceDoor)==LOW))
  {                                                                                //ring door closed and necklace door open, lights on, stepper motor off, music playing
    digitalWrite(relayPower,HIGH);
    tmrpcm.play("music.wav");
  }

  if ((digitalRead(ringDoor)==LOW)&&(digitalRead(necklaceDoor)==LOW))
  {                                                                                //ring door and necklace door open, lights on, stepper motor off, music playing
    digitalWrite(relayPower,HIGH);
    tmrpcm.play("music.wav");
  }
}

```

*****Please and thank you to any and all who help. It is greatly appreciated*****

# Answer
> 1 votes
Your code doesn't match your desired output. You say you want to:

```
doorLatch open and doorLatch2 closed: LED on, stepper spin, audio plays.
doorLatch closed and doorLatch2: LED on and audio plays, no stepper motor.
Both latches closed: Everything off or off after delay.
Both latches open: LED on and music plays, no stepper motor.

```

Note that both latches open and and doorLatch closed DoorLatch2 open result in the same state: LED on and audio plays, no stepper motor.

Your code says

```
if doorLatch & doorLatch2 are both closed (high)

    relayPower = low (off)

else

    relayPower = HIGH (on). This in ALL cases other than both latches HIGH

```

Next, a second if statement:

```
if doorLatch2 == HIGH && doorLatch == LOW
     relayPower = HIGH (on)
     step motor back and forth
else
     play sound

```

So you play the sound if doorlatch2 is low or doorLatch is high

You turn off the relay if doorLatch & doorLatch2 are both closed (high)

You turn on the relay if doorLatch is low or doorlatch2 is low.

```
void loop() {
   int latchState digitalRead(doorLatch);
   int latch2state = digitalRead(doorLatch2);
   if (latchState = LOW && latch2Sate == HIGH) {        //0 - 1
      //turn on led
      //spin stepper
      //play audio
   } else if (latchState = HIGH && latch2Sate == LOW) { //1 - 0
      //Turn LED on
      //play audio
      //turn off stepper
   } else if (latchState = HIGH && latch2Sate == HIGH) {//1 - 1
     //turn everything off (after delay?)
   } else if (latchState = LOW && latch2Sate == LOW {   //0 - 0
     //LED on
     //play music
     //turn off stepper
   }
}

```

---
Tags: arduino-mega, audio, loop, tmrpcm
---


# Question
Title: Arduino AT not working (Arduino UNO and HC-06)
Recently had issues with HC-06 AND Arduino UNO. Turned out that the last module was not working, this module keeps flashing and it appeared in the Bluetooth list. I'm trying to work with some AT commands but for some reason this doesn't work. This module is brand new (ZS-040).

```
#include <SoftwareSerial.h>

SoftwareSerial btSerial(2, 3); // RX, TX
/*
 * Connect pin 2 Arduino to pin TX HC-06
 * Connect pin 3 Arduino to pin RX HC-06
 */
void setup() {

Serial.begin(9600);

Serial.println("Enter AT commands:");

btSerial.begin(9600);

}

void loop()

{

if (btSerial.available())

Serial.write(btSerial.read());

if (Serial.available())

btSerial.write(Serial.read());

}

```

I uploaded the code, went into Serial Monitor. When I type a command, I get no reply. I opened "Arduino Bluetooth" app,connected to my phone and when I type something in the terminal on my phone I see the text on my PC's Serial Monitor screen. Any ideas what I should do next? Could it be something to do with the RX pin? Should I use voltage divider? I have 1k and 2k Ohm resistors, how should I connect them if that's the solution?

# Answer
> 1 votes
1. Use a macro like this to send AT commands:

```
 #include <SoftwareSerial.h>

 SoftwareSerial btSerial(2, 3); // RX, TX
 /*
  * Connect pin 2 Arduino to pin TX HC-06
  * Connect pin 3 Arduino to pin RX HC-06
  */
 void setup() {

 Serial.begin(9600);

 Serial.println("Enter AT commands:");

 btSerial.begin(9600);

 }

 void loop()

 {

 if (btSerial.available())

 Serial.write(btSerial.read());

 if (Serial.available())

 btSerial.write(Serial.read());
 delay(1000);
 //btSerial.print("AT+PIN4321");
 //btSerial.print("AT+NAMEAlibaba");
 //btSerial.print("AT+BAUD4");

 }

```
2. You may have another port set on the HC 06 instead of 9600, like I had. If so, try this code with all the possible port numbers and changing something like the password, and everytime you run the code - go check if it worked, this way you will find in wich port number you have your module.

good luck

---
Tags: arduino-uno, hc-06
---


# Question
Title: Connecting BMP280 sensor to microcontroller
I am building my own board with integrated pressure sensor. (microcontroller is 3V3 logic)

I want to know which parts do i need. In datasheet there are only 2 capacitors but on breakout board there are also 4 resistors.

Also in datasheet are 2 100 nF capacitors and on breakout board are 1uF and 0,1uF.

schematics from datasheet:

breakout board schematics:

# Answer
The capacitors are just decoupling capacitors. The value is not that critical. 100nF are good values to use. On the breakout they have used just one pair of decoupling capacitors but use that pair for both power pins. The datasheet has one decoupling capacitor for each pin. You can do it either way. Personally I'd do it the datasheet way, but for a small board it really doesn't make much difference.

The resistors are a different matter. The BMP280 can work in a number of communication modes, and which mode you have it in dictates what resistors are needed.

R1 is used to place it into I2C mode. R4 is used to set the I2C address. R2 and R3 are the pullup resistors on the I2C bus. They aren't really part of the BMP280 circuit, but part of any I2C circuit in general.

R1 and R4 could be replaced by direct connections to VCC and GND respectively, but by having resistors gives you the ability to override them and use SPI instead of I2C should you wish it.
> 3 votes

---
Tags: sensors, i2c
---


# Question
Title: Reading out two sensors via Com-Port at the same time
I have two Arduino Nano Every and a sensor connected to each of them. Here is what's happening:

* I upload the sketch to the first Arduino on Com4 and see its output is correct via the Serial Monitor
* I open a new instance of the Arduino-software, upload the same sketch to the second Arduino on Com6 and see its output is correct. However, in the meantime the Arduino on Com4 has stopped sending or receiving data
* If I close the second IDE-instance and re-upload the sketch to the first Arduino on Com4, it starts working again.

So, essentially I have two Arduinos which I can't read out at the same time.

The sensors are not connected, so I don't know where the problem is. Shouldn't the Com-Ports be independent?

# Answer
> 0 votes
UPDATE, self answer:

It was a broken USB cable.

# Answer
> 1 votes
> Shouldn't the Com-Ports be independent?

Not in the Arduino IDE, no. Basically the IDE is \[expletive deleted\] when it comes to using more than one board at a time.

You're better off using a proper serial terminal program, not the "serial monitor" in the IDE. Something like Teraterm or Putty, where you can have multiple instances on different ports at once.

---
Tags: serial, arduino-ide, arduino-nano
---


# Question
Title: How do powering arduino both barrel jack and lipo battery together?
I have arduino mega and Lipo batterry such this and Lipo battery charger 5V USB Boost. I am powering arduino normally from barrel Jack with an 9 Volt adaptor. But if there is power cut occur, I dont want to stop, I want powering arduino with Lipo battery. After power come back, arduino contunie to powering from barrel jack again at the same time battery start to charge. How can I succes this. Do you have any sample circuit?

After Majenko♦ comment, I've tried circuit but there is heating problem occur. More then 70 celsius. Is that normal?

Circuit

Termal Circuit

# Answer
> 2 votes
As is described in this post from the arduino forum, There is a MOSFET switch in series with the USB connector +5V input line. If the battery booster 5V output is connected to the USB input jack, then it will automatically power the UNO whenever power is disconnected from the barrel jack, and will be automatically disconnected whenever at least 7.0V is available at the barrel jack.

If you are experiencing over-heating problems, then you are probably overheating the linear regulator that steps down the barrel jack voltage to 5V. You need about 7-7.5V at the barrel jack to overcome the 2-2.5V loss through the linear regulator, but anything higher than about 7.5V will just cause the linear regulator to get hotter.

---
Tags: arduino-mega, power, battery, lipo, charging
---


title: Why my code isn't working?

text:
# Question
Title: Why my code isn't working?
I wrote this code, but it doesn't work (what I want is that the program choose a random color and turn on or off an RGB led) I use transistors to turn the led strip on or off and analogWrite(pin, random(0, 255) doesn't work

```
int red = 11;
int green = 10;
int blue = 9;

int color = 1;
int stat = 1;

void setup() {
pinMode(red, OUTPUT);
pinMode(green, OUTPUT);
pinMode(blue, OUTPUT);
}

void loop() {
  color = random(1, 3);
  stat = random(0, 1);

  if (color == 1 and stat == 0) {
    digitalWrite(red, LOW);
  }

  if (color == 1 and stat == 1) {
    digitalWrite(red, HIGH);
  }

  if (color == 2 and stat == 0) {
    digitalWrite(green, LOW);
  }

  if (color == 2 and stat == 1) {
    digitalWrite(green, HIGH);
  }

  if (color == 3 and stat == 0) {
    digitalWrite(blue, LOW);
  }

  if (color == 3 and stat == 1) {
    digitalWrite(blue, HIGH);
  }

  delay(1000);

}

```

# Answer
> 2 votes
From Arduino reference: random

In short:

> **Syntax**
>
> random(max)
>
> random(min, max)
>
> **Parameters**
>
> min: lower bound of the random value, inclusive (optional).
>
> max: upper bound of the random value, exclusive.
>
> **Returns**
>
> A random number between min and max-1. Data type: long.

Basically your first random returns values {1,2} and second one is even better {0}

---
Tags: arduino-uno, rgb-led
---


# Question
Title: Wifi strength Automation . Help. Noobie here
```
#include <ESP8266WiFi.h>
const char *SSID = "mr_lazy_boei";
const char *pass  = "usalusal";

WiFiClient client;

// Relay pin number
int ignition=2;
int self=0;

//   Return RSSI(Received Signal Strength Indicator) or 0 if target SSID not found
int32_t getRSSI(const char* target_ssid) {
 byte available_networks = WiFi.scanNetworks();

 for (int network = 0; network < available_networks; network++) {
   if (WiFi.SSID(network).compareTo(target_ssid) == 0) {     //stringOne.compareTo(stringTwo) < 0
     return WiFi.RSSI(network);
   }

 }
 return 0;
}

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

 Serial.println("Connecting to ");
 Serial.println(SSID);

 WiFi.begin(SSID,pass);
 while(WiFi.status() !=WL_CONNECTED)
 {
   delay(500);
   Serial.print(".");
 }
 Serial.println("");
 Serial.println("WiFi connected");

pinMode(ignition,OUTPUT);
pinMode(self,OUTPUT);
}

void loop(){

int32_t rssi = getRSSI(SSID);

 // For debugging purpose only
 Serial.print("Signal strength: ");
 Serial.print(rssi);
 Serial.println("dBm");

 if (rssi > (-55) && rssi != 0) // if rssi is greater then -55 dbm or it's 0 dbm, then the light will turn
 {
   digitalWrite(ignition, LOW);
   Serial.println("ON");
}
else

{
 digitalWrite(ignition,HIGH);
 Serial.println("OFF");
}
if (rssi > (-55) &&rssi !=0)
{
 digitalWrite(self,LOW);
 delay(750);
 digitalWrite(self,HIGH);
 Serial.println("SELF OFF");

}

}

```

Above is my code written. As you can see, I have two variables: `ignition` and `self`. `ignition` works the way I want, but the `self` variable turns on and and then off. That is correct. But it again turns on because of `void loop()`.

Let me explain further:

If wifi signal is strong the `ignition` should turn on and the `self` should turn on for less than a second and then turn off. It should not turn on again. When the signal goes weak the `ignition` turns off. Again, when signal gets strong the `ignition` turns on and I need `self` to turn on for not even a second and turn off.

I tried my best getting that. I tried moving it to `void setup()`, but that just works when I power up the device. After that it doesn't turn on or off. Please kindly help me. I know here I am having very talented brothers who would help me out on this issue.

# Answer
You need to design your program using a Finite State Machine.

First start off by defining each *state* that your program can be in, and what is allowed to happen in each of those states.

For example:

1. **IDLE**

The only thing that is allowed to happen here is detecting the RSSI and deciding whether or not to start the engine.

2. **IGNITION**

The RSSI has got strong enough and you want to start the car. The only thing you want to do is turn on the ignition and wait a moment. Nothing more.

3. **CRANK**

Once you've waited a moment you can crank the engine. That means turning on the starter motor and waiting a moment.

4. **RUNNING**

Now the engine has started you can release the starter motor and leave the engine to idle. It's now that you want to start watching the RSSI gain.

5. **STOP**

The RSSI has dropped below your threshold, so now you can stop the engine.

6. **IDLE**

Now the engine's stopped you can go back to the start and idle looking for the RSSI to get high enough again.

These are all the *states* of a *Finite State Machine*. You move from state to state depending on different *inputs* or *triggers*. One input is your RSSI value - or more strictly your RSSI value being above or below a threshold. Another input is (less obviously) time. Waiting for some time to pass.

So you start in state 1. In that state all your program is doing is watching the RSSI. When that rises you move to state 2. At that point it performs whatever actions are needed (turn on the ignition) and record the time. When enough time has elapsed you move on to state 3, and do the same.

It could actually be simplified by compressing states 2 and 3 together:

* Turn on ignition
* Delay
* Turn on starter motor
* Delay
* Turn off starter motor
* Delay
* Move to next state

You could then increase the complexity again a little (while increasing the safety) by adding extra steps when you're watching the RSSI. You can then check to see if the RSSI has been above (or below) the threshold for a certain amount of time before moving on to the next step:

1. IDLE - watching RSSI
    * If RSSI rises above threshold go to state 2.
    * Else stay in state 1
2. Record the time and keep watching the RSSI
    * If RSSI drops below threshold: Go back to 1.
    * If Enough time has passed: Go to state 3.
    * Else stay in state 2
3. Start the engine.
    * Go to state 4
4. RUNNING - watching RSSI
    * If RSSI falls below threshold go to state 5.
5. Record the time and keep watching the RSSI
    * If the RSSI rises above threshold: Go back to 4
    * If enough time has passed: go to state 6.
    * Else stay in state 5.
6. Stop the engine.
    * Go to state 1.

... etc ...
> 1 votes

---
Tags: loop
---


# Question
Title: ESP8266 - ESP01S with relay. Toggling the relay with http (GPIO0) and GPIO2 at the same time
I have an ESP8266 module with a relay like this: https://aliexpress.com/item/4000348370586.html. I have been able to control the module, I can deactivate and activate the relay by means of an http request, with the following code.

```
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>

#ifndef STASSID
#define STASSID "wifi_name"
#define STAPSK  "wifi_password"
#endif

const char* ssid = STASSID;
const char* password = STAPSK;

ESP8266WebServer server(80);

IPAddress ip(192, 168, 0, 101); //ESP static ip
IPAddress gateway(192, 168, 0, 1);   //IP Address of your WiFi Router (Gateway)
IPAddress subnet(255, 255, 255, 0);  //Subnet mask
IPAddress dns(8, 8, 8, 8);  //DNS
const char* deviceName = "ligth101";

const int relayPin = 0;

void handleOn() {
    digitalWrite(relayPin, LOW);
    setCrossOrigin();
    server.send(200, "text/plain", "Ligth on");
}

void handleOff() {
    digitalWrite(relayPin, HIGH);
    setCrossOrigin();
    server.send(200, "text/plain", "Ligth off");
}

void handlePing() {
    setCrossOrigin();
    server.send(200, "text/plain", "ligth");
}

void configPin(){
    pinMode(relayPin, OUTPUT);
    digitalWrite(relayPin, HIGH);
}

void configWifi(){
    WiFi.setAutoConnect(false);
    WiFi.disconnect();
    WiFi.hostname(deviceName);
    WiFi.config(ip, subnet, gateway, dns);
    WiFi.begin(ssid, password);
    while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    }
}

void setCrossOrigin(){
    server.sendHeader(F("Access-Control-Allow-Origin"), F("*"));
    server.sendHeader(F("Access-Control-Max-Age"), F("600"));
    server.sendHeader(F("Access-Control-Allow-Methods"), F("PUT,POST,GET,OPTIONS"));
    server.sendHeader(F("Access-Control-Allow-Headers"), F("*"));
}

void sendCrossOriginHeader(){
    setCrossOrigin();
    server.send(204);
}

void configServerPaths(){
    server.on(F("/ping"), HTTP_OPTIONS, sendCrossOriginHeader);
    server.on(F("/ping"), HTTP_GET, handlePing);

    server.on(F("/on"), HTTP_OPTIONS, sendCrossOriginHeader);
    server.on(F("/on"), HTTP_GET, handleOn);

    server.on(F("/off"), HTTP_OPTIONS, sendCrossOriginHeader);
    server.on(F("/off"), HTTP_GET, handleOff);

    server.begin();
}

void setup() {
    configPin();
    configWifi();
    configServerPaths();
}

void loop() {
    server.handleClient();
}

```

Now, I want to use the GPIO2 pin to also turn the relay on and off. The desired behavior is to change the state of the relay regardless of whether it comes from the button or from an http request.

I have tried the following modifications to the code:

```
const int buttonPin = 2;
int buttonState = 0;

void configPin(){
    ...
    digitalWrite(buttonPin, LOW);
}

void handleButton(){
    buttonState=digitalRead(buttonPin);
    if(buttonState == HIGH) {
        digitalWrite( relayPin, !digitalRead(relayPin) );
        delay(1000);
    }
}

void loop() {
    server.handleClient();
    handleButton();
}

```

With these modifications to the code, I have tested the following two modifications to the hardware:

1. Placing a switch between ground and GPIO2. As a result of this, each time I activate the push-button, the relay remains intermittent, going from one state to the other infinitely.
2. Placing a switch between ground and GPIO2, but adding a resistor between the switch and the GPIO2 pin, but this also does not work.

Is there a way to deactivate / activate the relay using GPIO2 with a push button and via http as well?

Thanks!

# Answer
Contrary to esp-01, on the esp-01S io 0 and io 2 pins have a pull-up resistor.

Wire a button between io 2 and ground and you will read LOW if the button is pushed.

Use a state variable for the state of the relay, don't read back the pin (does it even work to read the state of an output pin with digitalRead on esp8266?).
> 2 votes

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


# Question
Title: Detecting an incoming 7.875 kHz pulse to use as trigger
I have written a code that detects an incoming pulse (square) of 7.875 kHz to trigger the output High for the entire duration of pulse, and trigger the output low if the pulse is off or not detected.

**CODE**

```
// Define pins
volatile int pulse1 = 2;    //incoming pulse 1 on pin 2

const int ledPin = 13;   //output to trigger LED

void setup() {

  pinMode(pulse1, INPUT);

  pinMode(ledPin, OUTPUT);

  // Timer Setup

  TCCR1A = 0;               // set entire TCCR1A register to 0
  TCCR1B = 0;               // same for TCCR1B
  TCNT1  = 65282;           // initialize counter value
  TCCR1B |= (1<<CS10);      // set prescaler to 8 bit
  TIMSK1 |= (1 << TOIE1);   // enable timer overflow interrupt

}
ISR(TIMER1_OVF_Vect){
  TCNT1 = 65282;
  attachInterrupt(digitalPinToInterrupt(pulse1), ISR_UV2, FALLING);
  }

void loop() {
  attachInterrupt(digitalPinToInterrupt(pulse1), ISR_UV1, RISING);

}

// Interrupt routines

void ISR_UV1(){
  digitalWrite(ledPin, HIGH);      // Send high signal
}

void ISR_UV2(){
  digitalWrite(ledPin, LOW);      // Send low signal
}

```

Is it the correct approach, or am I doing it wrong. One last thing that is bothering me is, every time I connect a wire (not connected to anything) to the input pin 2, it sends a high signal, and keeps the signal high until the Arduino is reset. The pulse is a square wave 50% duty cycle generated by a device. I dont need to measure it or count it. I am just using it as a trigger to send a HIGH signal when it occurs. So it stays on (occurs) for 25ms & turns off during which its freq. is 7.875MHz & then it is repeated by the device according to the device parameters. I am aware it is a very short pulse but for the purpose of project nothing else can be used as the trigger

Any help will be appreciated.

# Answer
So i figured out what the problem was, I had to detach interrupts in the interrupt routines not in my main code. So basically these changes:

```
void loop() {
  digitalWrite(ledPin, LOW);
  attachInterrupt(digitalPinToInterrupt(pulse1), ISR_UV1, CHANGING);

}

```

& in the Interrupt routines:

```
digitalWrite(ledPin, HIGH);      // Send high or Low dpending on the routine
detachInterrupt(digitalPinToInterrupt(pulse1));

```

& basically this works like a charm, & there are still issues with the timer, but that will be solved in my main code with another sensor.
> 2 votes

# Answer
I don't think, that your current approach will work. The logic seems flawed to me (though I cannot know, how exactly this code is embedded in your actual code) and the frequency is that high, that it will be difficult for the microcontroller to do much between the different interrupt triggers.

I would suggest 2 different approaches, based on the actual needs:

1. You can build a demodulator, which just gives you a high value, when your signal is there, and a low one, if it is not. Here you would need extra components.
2. You could feed the signal into one of the timers as clock source. Then the timer counts the pulses (actually twice the pulses, since the timer increments on every edge, rising or falling). You can use the overflow interrupt to get the value out of it. Lets say you use Timer 1 for the signal and still have Timer 0 for doing the Arduino time stuff (`delay()`, `millis()`, `micros()`). Then you can write an ISR for the Timer1 overflow interrupt. In there you take the current time and subtract the time of the last interrupt. Then you get the time, that it took the timer to overflow. Since you know, how many pulses are needed to overflow the timer, you now know the average frequency. If it is in the needed range, you set a simple single byte flag variable (be sure to declare it as `volatile`). You can tune the time for the average for example with the prescaler.

In your main code you can then check for the flag being set and do stuff accordingly. Reset the flag, if you have done stuff, and save a timestamp. Check in your main code, if a specific time has passed since your last timestamp. If yes, that means, that the signal is lost. There you can act accordingly
> 0 votes

---
Tags: arduino-uno, programming, interrupt, timers, digital
---


# Question
Title: How to push two values to the same key from Arduino to Firebase
I would like to push two values at the same time (to the same node) from arduino to firebase. I tried to create an array and push the array to firebase, however, that is not working.

Here are the two values that I'm pushing, but I would like to push them to the same unique key:

```
temp1 = sensors.getTempCByIndex(0);
 StaticJsonBuffer<50> jsonBuffer;
JsonObject& timeStampObject = jsonBuffer.createObject();
timeStampObject[".sv"] = "timestamp";

Firebase.push("Sensors/20/temperatures/001", temp1);
Firebase.push("Sensors/20/temperatures/001", timeStampObject);

```

How it should look like in Firebase

Thanks in advance!

# Answer
@hcheung thanks for your help! It solved the problem. This is my code now:

```
StaticJsonBuffer<256> jsonBuffer;
JsonArray& array = jsonBuffer.createArray();
array.add(timeStampObject);
array.add(temp1);
Firebase.push("Sensors", array);

```
> 0 votes

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


# Question
Title: printing the analogRead() functions result crashes Arduino
I have created a curcuit which reads the analog pin 3 auf the arduino nano and does other things dependant on the returned value. However I have problems regarding the analogRead() function. Whenever I use a piece of wire to short the "Analog\_UpDownHorn\_Signal" and do it fast paced so that the arduino reads 0V and 5V repeatedly the serial communication stops. Sometimes it resumes. Sometimes it doesn't and when it does the value is always 1023.

I have managed to reduce the problem to the following 2 lines of code, which leads me to believe its my curcuit or a bug in the functions used. Before the arduino gets stuck it sometimes puts out random '?' or other wierd characters on the serial monitor.

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

void loop()
{
  Serial.println(analogRead(A3));
}

```

# Answer
The capacitor you have is rather large on the Analogue input, normally at this position it would be for debounce. Try something in the range of 100nF. Another idea would be to increase R8 to 10k.

https://www.g7smy.co.uk/2015/09/multiple-buttons-on-one-pin-with-an-arduino/
> 2 votes

# Answer
I have fixed the issue by connecting the two grounds on the opposite site of the arduino nano with a thick solder connection on the bottom side of my perfboard. Seems like it really had to do with the big capacitance an the rapid discharge when shorting it to ground.

Maybe it had a "charge pump" like effect with decoupling cap and the debouncing cap, because those are on the same side of the board.

To further avoid this problem i will not short the cap an discharge it through a low ohm resistor. Furthermore i could lower the capacitance as it was stated before and up the resistor values.
> 2 votes

---
Tags: serial, analogread, adc
---


# Question
Title: ESP32 send data to another ESP32 without establishing a wifi connection
Originally I was creating a project consisting of the Atmega328P and NRF24L01 to create multiple arduinos that could talk to each other. Basically I was creating something like this:

As the network grows I am starting to run out of memory when using the atmega328P. I have to be careful about allocating memory and more. So I will like to replace the NRF24L01 with the ESP32. The price of the ESP-WROOM-32 by itself is also cheaper than buying an NRF24L01 + the atmega328.

---

## Question

**How can I send data from one ESP32 to another ESP32 without establishing a WiFi connection?** Just like the NRF24L01 where you specify a writting pipe where you want to send the data and the other NRF24L01 is listening on that pipe.

---

I know I can do that with ESP-NOW. This video explains how. The problem with ESP NOW is that I have to know in advance the mac address of the ESP32 where I intend to send a message. I plan to be able to keep adding smart home devices without having to know the mac address.

My algorithm with NRF24 that I already created is as follows:

1. There is a master node listening on address 2
2. If I add a new node `A` to the network it listens on address 1.
3. Master discovers all devices that have address 1 every few seconds.
4. So eventually node `A` receives a discovery packet message that comes from master. Node `A` listens now on a random address and replies to master with that random anddress.
5. So node `A` is now connected to the network.

The cool thing about this algorithm is that I can keep adding new nodes to the network without knowing in advance its address. I will like to do the same thing with the ESP32. **How can I send a simple message betweenn 2 ESP32 modules?**

# Answer
> 1 votes
Finally I found a way how to do it. If you use the mac address FF:FF:FF:FF:FF:FF that works as a broadcast address. This is the working code on how to send a message from the master to another esp32 without knowing its mac address. Later the slave can reply with its real mac address:

**Code for master (tx)**

```
#include <Arduino.h>
#include <esp_now.h>
#include "WiFi.h"

uint8_t broadcastAddress[] = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF};

void OnDataSent(const uint8_t *mac_addr, esp_now_send_status_t status) {
  Serial.println(status == ESP_NOW_SEND_SUCCESS ? "Delivery Success 1" : "Delivery Fail 1");
  if (status ==0){
    Serial.println("Delivery Success 2");
  }
  else{
    Serial.println("Delivery fail 2");
  }

  Serial.println();
}

void setup()
{

  Serial.begin(115200);

  Serial.println("Starting...\n");

  // Set device as a Wi-Fi Station
  WiFi.mode(WIFI_STA);

  Serial.println(WiFi.macAddress());

  // Init ESP-NOW
  if (esp_now_init() != ESP_OK) {
    Serial.println("Error initializing ESP-NOW");
    for(;;) {      delay(1);  } // do not initialize wait forever
  }

  Serial.println("initialized ESP-NOW");

  // Once ESPNow is successfully Init, we will register for Send CB to
  // get the status of Trasnmitted packet
  esp_now_register_send_cb(OnDataSent);

   // Register peer
  esp_now_peer_info_t peerInfo;
  memcpy(peerInfo.peer_addr, broadcastAddress, 6);
  peerInfo.channel = 0;
  peerInfo.encrypt = false;

   // Add peer
  if (esp_now_add_peer(&peerInfo) != ESP_OK){
    Serial.println("Failed to add peer");
    for(;;) {      delay(1);  } // do not initialize wait forever
  }
}

int dataToSend = 1;
void loop()
{
    dataToSend++;

    // Send message via ESP-NOW (size of an int is 4 bytes on ESP32)
    esp_err_t result = esp_now_send(broadcastAddress, (uint8_t *) &dataToSend, 4);

    if (result == ESP_OK) {
      Serial.println("Sent with success");
    }
    else {
      Serial.println("Error sending the data");
    }

    //Serial.println(WiFi.macAddress());
    delay(1000);
}

```

**Code for slave (Rx)**

```
#include <Arduino.h>
#include <esp_now.h>
#include "WiFi.h"

// Callback when data is received
void OnDataRecv(const uint8_t * mac, const uint8_t *incomingData, int len)
{
  int dataReceived;
  memcpy(&dataReceived, incomingData, sizeof(dataReceived));

  Serial.print("Data Received: ");
  Serial.println(dataReceived);

  Serial.println();
}

void setup()
{

  Serial.begin(115200);
  delay(100);

  Serial.println("Starting...\n");

  // Set device as a Wi-Fi Station
  WiFi.mode(WIFI_STA);

  // print our mac address
  Serial.println(WiFi.macAddress());

  // Init ESP-NOW
  if (esp_now_init() != ESP_OK) {
    Serial.println("Error initializing ESP-NOW");
    for(;;) {      delay(1);  } // do not initialize wait forever
  }

  Serial.println("initialized ESP-NOW");

  // Register for a callback function that will be called when data is received
  esp_now_register_recv_cb(OnDataRecv);

}

void loop()
{
}

```

You can also reply back on the receiver code if you want. It will be the same code.

---
Tags: c++, esp32, nrf24l01+, network
---


# Question
Title: Using different processors when it comes to arduino
I decided to learn Arduino in this quarantine so I am still a newbie when it comes to micro controllers. Basically I been doing all my projects based on the ATMEGA328P-PU:

I even converted my breadboard designs to custom PCBs like this one:

**I am running out of Atmega328P-PU processors and I am about to buy more. But instead of going with the traditional Atmega328P should I buy other processors?**

This are my alternatives:

---

They all are about the same price. For example the ESP32 is 10 times faster and it was a lot more sram and pins. Anyways this are my questions:

1. Why do people buy the Atmega328P when there are faster and more powerfull processors for the same price?
2. I been saving a lot of money by buying the Atmega328P processor by itself and then building Arduino using the crystal, ceramic capacitors etc. There are so many tutorials on how to build that such as on THIS LINK and many more. But how can I build an ESP32 running arduino code on a breadboard? I have not been able to find that tutorial. All the tutorials I find use the ESP32 already soldered to a PCB. I want to build my custom PCB using a ESP32 for example. Where can I find that tutorial?
3. If I decide to buy the ESP32 or ESP8266 should I build my code using the arduino IDE? I will have to add stuff to arduino IDE so it works with the ESP32. What are the benefits of using other IDEs?
4. I am thinking about the ESP32 and ESP8266 because I see a lot of people using them on the internet and they are much more powerfull than the Atmega328P for the same price. What other processors do you guys recommend?

# Answer
For learning it really doesn't matter much of which MCU to choose from. For actually embedded project development, it really depends on what you want to do with your dev board. I thought that I would just offers some of my thoughts and experiences here as a reference, there is no right or wrong answers. I'm sure many people have their own favourites and considerations when picking their MCU.

> Why do people buy the Atmega328P when there are faster and more powerfull processors for the same price?

ATmega328p get popular for its long history (it is 2-decades old) and Arduino, personally I feel that there are better MCU with compatible features, memory size, etc. even within the AVR series to replace ATmega328p, I actually developed an ATtiny3217-based Arduino board last month, it is cheaper (on chip BOM cost) and it does not need crystal for running at 20MHz with decent accuracy, it offers almost similar I/O pins, memory size, UART/I2C/SPI as ATmega328, but it is a much modern chip with many features that are not available in ATmega328 (such as DAC, touch support, event system, etc.). ATmega3208/4809 is another interesting candidate for my next project.

> All the tutorials I find use the ESP32 already soldered to a PCB. I want to build my custom PCB using a ESP32 for example. Where can I find that tutorial?

ESP32 (and ESP8266 like ESP-12F as well) come with a compact form factor that is ready to be integrated into your design, most of the design needs are USB-interface, power supply and some peripheral (such as auto-reset circuitry, power and blinking LEDs, etc.). You can take a look at Adafruit HUZZAH ESP8266 which is basically based upon an ESP-12E module with added circuit for reset, voltage regulator.

> If I decide to buy the ESP32 or ESP8266 should I build my code using the arduino IDE? I will have to add stuff to arduino IDE so it works with the ESP32. What are the benefits of using other IDEs?

Arduino IDE is not the only IDE for programming an Arduino, PlatformIO is one of the alternatives IDE for Arduino programming, one of the main benefits is better project and dependency(libraries) management and the flexibility on compiling/building process (e.g. pull in the floating point supports on AVR chips). Take a look at these two YouTube videos to see how it looks like and how to set it up:

> I am thinking about the ESP32 and ESP8266... What other processors do you guys recommend?

As I mentioned at the beginning, it really depend on your selection criteria. ESP8266 and ESP32 is generally the choice for its WiFi capability, however, you won't chose ESP8266 for anything related to ADC because it has only one ADC with a reference voltage of 1v. ESP32 looks great for for its faster CPU, it however generated a lot of noise when you want to reading sensor data even though it offers 12-bit ADC resolution versus 10-bit in ATmega328p. Its ADC also has non-linear issue on some of the old batch of ESP32 chips.

On the question of "what other processors do you guys recommend"? If no requirements for wireless connectivity, I personally like STM32F103 Blue Pill, for its better ADC (12-bit), more memory, and multiple UARTs, and cheap but there are things that you need to be aware of (such as fake STM32 chip and design faults).

Whatever you decided for your next choice of MCU, I'm sure it won't be your last one, as your experience grow and your project get more complex, you will know that there is no perfect MCU that fit it all.
> 1 votes

# Answer
1. Sometimes faster and more powerful is not needed. If you just needed a simple timer, and it needed to be battery operated, a processor like the ATmega328 would be the better choice. It really depends on the application.

The ESP32 is a great device. But the A/D converter on it is less than stellar. It is not as consistent compared to the A/D in the Atmega328P.

2. The ESP32 is more fussy about the power supply requirements compared to the Atmega328P. Lots of people get themselves into trouble when they use poor design practices with the ESP32/ESP8266 modules. Poor practices that worked well enough for lower power and lower speed processors like the Atmega328P. Most people don't bother with reading the datasheet for the processors. They just try and copy stuff they fine on the Internet. And the Internet is full of poor quality information by people who don't really understand much of what they are working with.

If you want to start using the ESP32, then do yourself a favor and buy a working board with a power supply and not just buy a module. It will save you many hours of grief.

3. The Arduino IDE makes it easy to get stuff working. There also is Python, but it is less popular. There is a lot more information available for the Arduino IDE, and available libraries. And that makes development a lot easier. There are other ways, but the learning curve is much steeper.
4. The "Blue Pill" STM32F103C8T6 based board is a lot of capability for little money. The CPU runs on 3.3 volts like the ESP devices. It has gain a lot of popularity in the last few years but there isn't as much information as for the Atmega328P.

The STM32F103C8T6 and the ESP devices are 3.3 volt based designs. And they require 3.3 volt devices to interact with. There are some devices that are mostly 5 volt only devices. Like a character LCD. It is easier to interface that to a 5 volt processor.

There is lots that I could still say but it would take hours. But what you should do before deciding on a part is to decide what the needs of the project are. That will often guide you towards the part you should use.

One more note. The ESP devices are running a lot of code on top of the Setup and Loop functions. There is lots of stuff going on in the background to support the WiFi capability. And you don't have the kind of control that you could have with a non-ESP device. But if you want that part then you need to accept that limitation.
> 1 votes

---
Tags: esp8266, atmega328, esp32
---


# Question
Title: How can I create an analog signal which is similar to PMT (Photo Multiplier Tube) pulse using analog write?
I have developed a circuit to process the PMT pulse output. For the testing, I need an artificial signal which is similar to the PMT pulse. How can I use `AnalogWrite()` to create such type of signal?

# Answer
> 0 votes
Short answer: You can't.

The Arduino can't do analog output at all, much less matching a specific analog waveform of ≈40ns duration.

PWM on the Arduino simulates **constant** analog voltages using square wave pulses of variable duty cycle. It has no support for creating analog waveforms of any type, much less ones with such a short duration.

**EDIT**

As mentioned in this thread: Generate a ramp input with an Arduino Uno

You could use a resistor ladder to create a roll-your-own DAC, and then use direct port register manipulation (not digitalWrite) to set the pins controlling your resistor ladder and get a crude approximation of your waveform.

**Edit #2**

There is no way you'll be able to generate nanosecond scale waveforms with a normal Arduino. It just isn't fast enough.

# Answer
> 0 votes
I doubt very much AVR-based Arduinos could do that.

SAMD21-based Arduinos do have a DAC, but their conversion time is about 2.85 μs. Their timer/counters can be clocked at 96 MHz, so about 10.5 ns/tick, but would yield a square pulse (that may or may not degenerate into what you need 8-).

Overall, I don't think an Arduino is the right tool for the job. Maybe something like the (very fast) Teensy 4.0 could do it, but I don't know much about those.

---
Tags: analogwrite
---


# Question
Title: How to convert my Arduino setup to a PIC setup?
I have an arduino setup with LCD, RTC, EEPROM, Reed Switch, AC/DC Buck Converter, 4X4 Keypad. What PIC IC will let me connect with all these(40 Pins), and yet accept Arduino Code. I don't want to rewrite the code. I learn Arduino only recently, So shifting to another coding language is near impossible, since am not a coder.

# Answer
The PIC32 has full (or nearly full) support for the Arduino API through the chipKIT project. If you want to use one of the smaller PIC chips (PIC16 / PIC18 etc) then you're out of luck. There just isn't a freely available C++ compiler for those chips, so the Arduino API can never really be ported to them.

I have, in the past, cobbled together an Arduino-style API layer for a handful of selected PIC18s which uses structs to emulate a couple of the Arduino C++ objects, but it only worked in a very basic way with no function overloading for things like `Serial.print()`.

One of the problems from a low-end user's perspective is that the PIC32 only comes in harder to use TQFP and QFN etc packages in anything larger than 28 pins. That means you can't breadboard without a development board. Fortunately there are some breadboard friendly options in the chipKIT ecosystem, such as the Fubarino series of boards. For more pins though you'd be wanting one of the bigger boards, such as the MAX32 which is in a Mega footprint (but with even more pins).

It's important to note though that the PIC32 is a 3.3V device and, owing to physical differences in the way that some of the internals work, there are incompatibilities in some of the libraries and functionality (such as no "LOW" or "CHANGE" interrupt support, only "RISING" and "FALLING").
> 4 votes

---
Tags: lcd, atmega328, eeprom, rtc
---


# Question
Title: Arduino Analog Input: why the weird fluctuation?
I am using an Arduino Uno. `analogRead(A0)` (or whichever channel I use) returns 0 when it is grounded with Arduino Gnd, and 1023 when connected to Arduino 5v. But when I connect it to a current sensor (ACS712) it is always fluctuating like this:

> 0, 0, 0, 0, 0, 0, 1023, 1023, 1023, 1023, 1023, 441, 446, 0, 0, 0, 0, 1023, 1023...

I also tried it with a potentiometer (10K) and analog joystick: the results are the same. I tried changing different power supplies (both Arduino's and the sensor's (ACS712, potentiometer, joystick)). I even tested it on an Arduino Mega, but no luck. Such extreme fluctuation are making no sense to me. Kindly help me what could be the issue.

My wiring diagram is attached to this post. And I use an external supply to the ACS712. Is it possible that Static electricity is causing this issue?

Code:

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

void loop() {
  float value = analogRead(A0);
  Serial.print("Raw:");
  Serial.println(value);
  delay(500);
}

```

Thanks.

# Answer
You need to connect together the grounds from your external power supply and the Arduino.

At the moment the two devices are floating - there's no commonly-agreed 0v point.
> 4 votes

# Answer
I had a similar issue with fluctuating values. Make sure you are setting in your code the analog PIN as `INPUT` pin. On some boards you have to specify it explicitly, like this:

```
pinMode(A1, INPUT);

```
> 0 votes

---
Tags: arduino-uno
---


title: Assigning value to a struct byte order

text:
# Question
Title: Assigning value to a struct byte order
So i have struct:

```
typedef struct sendPacketStruct {
  byte header = headerByte;//0x55
  unsigned int time;//2 bytes
  int height;//2 bytes
};

```

And i do this:

```
    sendPacketStruct sendPacket;

    sendPacket.time = 84;//0x54
    sendPacket.height = 100;//0x65

    Serial.write((byte*)&sendPacket, sizeof(sendPacket));

```

But when i receive it at the other end the hex bytes are:

55 54 00 64 00

So the first byte is correct as the header 0x55, but the 2x 2 byte values time and height are there but shifted.

eg it should be 00 54 not 54 00

# Answer
> 0 votes
The answer is that arduino is little endian, so the byte order is correct. I was just expecting big endian order as ive seen in some other network protocols. If that is desired instead I can just do some bit shifting and re-arranging.

---
Tags: serial, data-type, struct
---


# Question
Title: I cannot get my code to play music in a or manner. I have to open one switch then the other. Music should play with either door open
Problem is if I open the necklaceDoor first, nothing happens. I have to open the ringDoor first. That turns everything on. Then with the necklaceDoor open, the stepper motor will turn off and the lights and music will continue to play. But I want to be able to open the necklaceDoor first and play the music with the lights. I do not want it to matter which one is opened first. I also realized that if I can get an or statement to work within an and statement I could do away with the fourth if statement completely. Both ringDoor open and necklaceDoor open, as well as ringDoor closed and necklaceDoor open have the same outcome. Now if I switch the door states in the third if statement, I get necklaceDoor only plays audio after closed(original problem) but if both doors are open and then ringDoor is closed, the music will shut off after the stepper timer is done and then start again after necklaceDoor is closed?!?!?!?

```
#include <SD.h>
#include <TMRpcm.h>
#include <Stepper.h>
TMRpcm tmrpcm;

const int stepsPerRevolution = 2048;   //Number of pulses per revolution
const int ringDoor=2;                  //Ring door
const int necklaceDoor=7;              //Necklace door
const int relayPower=22;               //Turn relay on

Stepper myStepper = Stepper(stepsPerRevolution, 8, 10, 9, 11);

void setup() {
  Serial.begin(9600);                         //Start connection with computer

  if (!SD.begin(53))                         //Chip pin on card
  {
    Serial.println("failed!");                //SD card did not read
    return;
  }

  tmrpcm.speakerPin = 46;                      //Speaker output pin
  myStepper.setSpeed(5);                       //Stepper speed
  pinMode(ringDoor,INPUT);                     //Check state of ring door magnetic switch, NO
  pinMode(necklaceDoor,INPUT);                 //Check state of necklace door magnetic switch, NO
  pinMode(relayPower,OUTPUT);                  //Relay enable for 12V LED
  digitalWrite(ringDoor,HIGH);                 //Make door closed read high on start up
  digitalWrite(necklaceDoor,HIGH);             //Make door closed read high on start up
  digitalWrite(relayPower,LOW);                //Make relay off on start up
}

void loop() {

  if ((digitalRead(ringDoor)==HIGH)&&(digitalRead(necklaceDoor)==HIGH))
  {                                                                                //ring door and necklace door is closed, everything is off
    digitalWrite(relayPower,LOW);
  }

  if ((digitalRead(ringDoor)==LOW)&&(digitalRead(necklaceDoor)==HIGH))
  {                                                                                //ring door is open and necklace door is closed, lights on, stepper motor spinning, music playing
    digitalWrite(relayPower,HIGH);
    tmrpcm.play("music.wav");
    myStepper.step(stepsPerRevolution);
    delay(500);
    myStepper.step(-stepsPerRevolution);
    delay(500);
  }

  if ((digitalRead(ringDoor)==LOW)&&(digitalRead(necklaceDoor)==HIGH))
  {                                                                                //ring door closed and necklace door open, lights on, stepper motor off, music playing
    digitalWrite(relayPower,HIGH);
    tmrpcm.play("music.wav");
  }

  if ((digitalRead(ringDoor)==LOW)&&(digitalRead(necklaceDoor)==LOW))
  {                                                                                //ring door and necklace door open, lights on, stepper motor off, music playing
    digitalWrite(relayPower,HIGH);
    tmrpcm.play("music.wav");
  }
}

```

Please and thank you to any and all who help. It is greatly appreciated. Yes, I asked the the original question and the answer I received not only did not work, somehow neither latch worked anymore.

# Answer
> 1 votes
First of all, you have to find out how your magnetic switches work. Are they opened or closed if you attach a magnet to them? Do they behave the same or is one closed and the other opened if you attach a magnet? Your code above is written for active LOW switches i.e. if the respective door is closed the switch is opened and therefore the logic level of the pin is HIGH. The level is LOW if the door is opened (activated; hence active LOW).

In order your code had a chance to work, the switches must be connect the right way: on one side connect them to GND and on the other side to the respective Arduino pin. If this is not the case, the code must be changed or the switches must be conneted the right way. You did not show us your schematic, so I can not check it for you.

Here is some code to try: But first find out if the switches you use are LOW or HIGH active. I also have no access to an IDE at the moment, so I can not try out the code. Take it as a hint on how to do it.

And one tip from a guy that does the job for 30 years now: Don't comment variables if their names say it all:

```
//  this sort of comments makes the code unreadable --V
const int ringDoor=2;                          //Ring door

```

I know it is a common behavior in the Arduino community, but don't write comments after a statement. In your code above I did realize that there are comment for the `if` statements only when I copied the code in my answer. Comments are only usefull if they say something new and can be read without problems.

```
#include <SD.h>
#include <TMRpcm.h>
#include <Stepper.h>
TMRpcm tmrpcm;

const int stepsPerRevolution = 2048;
const int ringDoor = 2;
const int necklaceDoor = 7;
const int relayPower = 22;

Stepper myStepper = Stepper( stepsPerRevolution, 8, 10, 9, 11 );

void setup()
{
  Serial.begin( 9600 );
  if ( ! SD.begin( 53 ) )
  {
    Serial.println( "failed!" );
    return;
  }

  tmrpcm.speakerPin = 46;
  myStepper.setSpeed( 5 );
  pinMode( ringDoor, INPUT );
  pinMode( necklaceDoor, INPUT );
  pinMode( relayPower, OUTPUT );

  digitalWrite( ringDoor, HIGH );
  digitalWrite( necklaceDoor, HIGH );

  digitalWrite( relayPower, LOW );
}

void loop() {

  // the following code works if both switches are LOW active
  // (i.e. LOW if the door is open)
  // if the "ringDoor-switch is HIGH active change
  // digitalRead( ringDoor ) == LOW to
  // digitalRead( ringDoor ) == HIGH
  // if the "necklaceDoor-switch is HIGH active change
  // digitalRead( necklaceDoor ) == LOW to
  // digitalRead( necklaceDoor ) == HIGH
  // and
  // digitalRead( necklaceDoor ) == HIGH to
  // digitalRead( necklaceDoor ) == LOW

  if ( ( digitalRead( ringDoor )     == LOW ) ||
       ( digitalRead( necklaceDoor ) == LOW ) )
  {
    // one of the doors is open
    digitalWrite( relayPower, HIGH );
    tmrpcm.play( "music.wav" );
    if ( digitalRead( necklaceDoor ) == HIGH )
    {
      // only the ring door is opend
      myStepper.step( stepsPerRevolution );
      delay( 500 );
      myStepper.step( -stepsPerRevolution );
      delay( 500 );
    }
  }
  else
  {
    digitalWrite( relayPower, LOW );
  }
}

```

---
Tags: audio, stepper-motor, tmrpcm
---


# Question
Title: How can i develop a fish tank automation using arduino
As a part of my final year Engineering project I would like to develop a fish tank automation system. In my project I need to check the quality of water concurrently and also I need to check the sedimentation of my fish tank. Which are the different types of sensors used for this? How can i connect it to my arduno uno?

# Answer
> 4 votes
You're starting from the wrong end of the problem (the electronics).

First, you need to decide the requirements for your system.

* Write down what your system is supposed to do: measure something? When & how often? Save or display the measurements? Control something based on the data? How precise must that control be (e.g. +/- .5 degC) (precision can be expensive)? Control something based on something other than measurements (except, perhaps, time?
* Once you understand the requirements, then you can write down the steps the system should take to meet them; it doesn't need to be code (and probably shouldn't be, just yet).
* Decide on what to measure and how to measure it. Can't figure out a sensor for something? Maybe you can infer it from something you can sense. Or perhaps learn how quickly or how often that 'something' goes out of spec and restore it without a measurement (e.g. you presumably already know how often and how much to food to dispense).
* Now you can start thinking about electronics, sensors, and code, having a pretty good idea of what you will need to know, to acquire, and to create, to build your project (whether or not you'll be expected to actually build one).

This is an Engineering approach to design and it is almost certain your project is intended to show that you know how to do this, much more than to show you can run a fish tank.

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


# Question
Title: global volatile variable not being updated in ISR
Running on atmega168p, I've got an interesting behavior I can't explain. A global volatile var that's called `pos` over here is not updated as it should. Once I add some code below the assignment, it starts working.

```
#define ENCODER_DO_NOT_USE_INTERRUPTS
#include <Encoder.h>

Encoder myEnc(A2, A3);

void setup() {
  Serial.begin(115200);
  while (!Serial); Serial.println("Started.");
  PCMSK1 |= bit(PCINT10) | bit(PCINT11) | bit(PCINT12);
  PCIFR  |= bit (PCIF1);   // clear any outstanding interrupts
  PCICR |= bit(PCIE1);
}

volatile int pos  = 0;
int oldpos = 0;

void loop() {
  if (oldpos != pos) {
    oldpos = pos;
    Serial.println(pos);
  }
  delay(100);
}

// PCINT10, PCINT11
ISR(PCINT1_vect) {
  pos = myEnc.read();
  //  adding digitalRead(A0)
  // or even Serial.println(pos) updates the var correctly
}

```

Switching from `int` to `byte` doesn't change anything. Encoder library is https://github.com/PaulStoffregen/Encoder. Any clues?

# Answer
> 0 votes
Well, the long awaited answer to this question is simple - the library that I've tried to use in my code was over-optimizing things by going full ASM and interfering with my stuff. Using C version straightened things up.

For anyone getting strange behaviour I recommend taking a quick glance at the lib's code you're using, maybe it's not your fault after all.

# Answer
> 1 votes
You are using pos outside of the interrupt without turning the interrupt off. pos is two bytes, so it takes the Arduino more than one cycle to read in that variable no matter how it is handled. If an interrupt occurs during that time, you get a corrupted value.

You need to have a cli() and then make a copy of pos to another variable and then a sei() and then use that copy in your calculations in loop.

# Answer
> 0 votes
# How to recognize and fix race conditions in Arduino by using atomic access guards:

> Switching from int to byte doesn't change anything. Encoder library is https://github.com/PaulStoffregen/Encoder. Any clues?

Your code here:

```
void loop() {
  if (oldpos != pos) {
    oldpos = pos;
    Serial.println(pos);
  }
  delay(100);
}

```

has an unaddressed race condition, which leads to undefined behavior and data corruption. Making `oldpos` into a `uint8_t` or `int8_t`, each of which is 1 byte, instead of `int`, which is 2 bytes, won't fix it, because you need the whole section from `if (oldpos != pos) {` through `Serial.println(pos);` to be atomic so that the value of `pos` you use to enter the `if` block does not get changed by the interrupt while you are in the `if` block. I'll explain more later. This is reminds me of a problem I had a few years back, here: C++ decrementing an element of a single-byte (volatile) array is not atomic! WHY? (Also: how do I force atomicity in Atmel AVR mcus/Arduino).

So, let's walk through a case where making a 2-byte variable into a 1-byte variable WILL solve the problem, first, to ensure we understand why one might think making it a 1-byte variable is the solution.

Let's look at this example. **It has a race condition and undefined behavior. Can you spot it?**

```
volatile uint16_t isr_counter = 0;

void setup()
{
    // enable the ISR here
}

// Any ISR
ISR()
{
    my_var++;
}

void loop()
{
    Serial.println(isr_counter); // <== race condition!
}

```

The answer is that `isr_counter` is a 2-byte variable, and AVR microcontrollers have 8-bit (1-byte) CPUs, so, it is possible that as `isr_counter` is being read in `loop()` to be printed, 1 of the 2 bytes is read out correctly to be printed, then the ISR fires, changes the variable, and gives control back to the main loop. The 2nd byte, now not what it was supposed to be, is read out, leading to a corrupted variable! Ex: let's assume `isr_counter` was 0xFFFF, or 65535, at the moment it is supposed to be printed, and lets say the low byte is read out correctly as 0xFF, then the ISR fires, the variable is incremented to 0x0000 since it overflows, then the control goes back to the main loop, and the 2nd byte is read out, it is now corrupted. What will be printed would be the contents of the variable containing 0x00FF, or 255, when what *should* have been printed out was 65535, and the next value after that to be printed out would have been 0. And what if the high byte was read out correctly before the low byte? (I'm not sure which order AVR mcus read the bytes), then your corrupted value would be 0xFF00, or 65280, when what *should* have been printed out was 65535 (0xFFFF), and the next value after that to be printed out would have been 0 (0x0000).

So, simply making the variable a `uint8_t` magically solves this race condition **for this one particular case** because 8-bit variables on 8-bit CPUs are read or written atomically, which means "as an atomic, or whole, single, unit, not broken up or corrupted by interrupts or other threads". **All operations which take 1 single CPU instruction cycle are automatically atomic, because they cannot be interrupted.** For any multi-instruction-cycle code block which we need to be atomic, we must **force it to be atomic by using what I call "atomic access guards".** Reading a 1-byte variable on an 8-bit CPU, or writing a 1-byte variable on an 8-bit CPU, is 1 instruction, so it is naturally atomic. Incrementing or decrementing a 1-byte variable, however, is NOT an atomic operation, since the variable must be read, modified, and written. Reading a 2-or-more-byte varible on an 8-bit CPU, or writing a 2-or-more-byte varible on an 8-bit CPU, is also NOT atomic, since it takes one instruction per byte. This means just reading a 2-byte variable or writing a 2-byte variable can be interrupted by an ISR in the middle of the operation, which leads to data corruption if you do not use atomic access guards!

Now, your case: would making `pos` into a 1-byte variable as `volatile int8_t pos = 0;` solve the race condition? No, not at all. Let's look at your code again, this time imagining that `pos` is an `int8_t` instead of an `int` (which is `int16_t` on AVR Arduino):

```
void loop() {
  if (oldpos != pos) {
    oldpos = pos;
    Serial.println(pos);
  }
  delay(100);
}

```

Let's walk through a potential scenario: `pos` is 7. `oldpos` is 6. So, `oldpos != pos` is true, and you enter the `if` statement. Now, right as you enter, the ISR fires, `pos` is changed by the ISR to 6 (or to any other number--it's still a race condition and undefined behavior), `oldpos` is now set to 6, which is what it already was, and you have data corruption because *it should have been set to 7!* Note that when I say this is undefined behavior in this case, I simply mean we cannot predict what will happen. This is buggy code. Code should *always* be predictable. Undefined behavior is a bug! Note also that when talking about "undefined behavior" according to C or C++ standards, we mean "the standard doe not *define* what will happen", which means your code may act one way on one architecture or with one compiler, and differently on another architecture or with a different compiler. This is not what I am talking about here. Here, when I say "undefined behavior" I don't mean "according to the C or C++ standard", I mean, "according to the rules of logic."

The solution to fix your race condition is to *enforce* atomic access using what I like to call **"atomic access guards"**. On multi-threaded systems, this means to use **locks, mutexes, and semaphores**. On single-threaded systems, such as this, it means to **disable any interrupt which could interfere and cause the race condition** (you can think about interrupts interacting with the main loop as a parallel to one thread interacting with another thread, so it is as though you had a multi-threaded system just by having a single-threaded system + interrupts). For AVR microcontrollers, disabling interrupts to act as atomic access guards is usually done by disabling global (or all) interrupts. BUT, disabling interrupts introduces jitter by delaying the processing of the ISR, so it should be done *for as short of a time period as possible!* **That means you should just disable interrupts, make copies of volatile variables, and re-enable interrupts.** This is an important point though: sometimes, in the case of using a 1-byte volatile variable, using a *copy* of your variable, which can NOT be changed at any moment by an ISR, also, in and of itself, acts as a form of "atomic access guards" and solves the problem all by itself. I'll post an example of this below.

But: **DANGER DANGER!** It's a "best practice" to always back up the interrupt state, disable interrupts, then restore the interrupt state, rather than just turning interrupts off then back on all the time. Why? Because what if you write a function which sometimes gets called *from within an ISR itself?* If you enable interrupts inside an ISR, you just enabled *nested interrupts*, which leads to *more race conditions.* If you know exactly what you are doing and you *want* nested interrupts, this is fine! But, chances are one is just making a mistake here and *accidentally* enabling nested interrupts without even realizing it, leading to really-hard-to-track down data corruption due to nested interrupts. Safety-critical systems can crash and hurt people when this happens, so we can't ever allow unmanaged race conditions.

So, do it like this:

1. Force atomicity in `loop()` by backing up the interrupt state.
2. Make copies of the volatile variables.
3. Then restore the global interrupt state.
4. Use only the copy of the varible in the rest of your code. This (using the copy) is also a form of "atomic access guards" all by itself for later code blocks using the variable because using the copy instead of the volatile variable means that the variable can NOT be changed at any moment by an ISR. This enforces atomicity as well!

Making a copy of the volatile variable and nothing else, while interrupts are disabled, *minimizes time where interrupts are disabled*, making your code the best it can possibly be! It should now look like this:

**1 of 3: THE BEST WAY!:**

```
volatile int pos  = 0; // assume this variable is still an `int`, which is 2-bytes

void loop() {
    uint8_t SREG_bak = SREG; // back up the global interrupt state
    noInterrupts(); // disable interrupts
    // make copies of your volatile variables here
    int pos_copy = pos;
    // restore interrupt state, turning them back ON if they were ON before,
    // or leaving them OFF if they were OFF before.
    SREG = SREG_bak;

    // Now do what you want with the copy, using pos_copy ONLY,
    // to avoid race conditions! (ie: using this copy here enforces
    // this entire block to be naturally atomic now, and by itself
    // is a form of "atomic access guards", as explained above.)
    if (oldpos != pos_copy) {
        oldpos = pos_copy;
        Serial.println(pos_copy);
    }
    delay(100);
}

```

Solved!

Let's look at 2 other examples, however, for completeness.

Here, we force the whole `if` statement block to be atomic. This looks correct at first, but has two problems: 1) \[a true bug\] `Serial.println` will block forever if the outgoing serial buffer is full, as it relies on interrupts to empty it, and if interrupts are off, that will ever happen, and 2) \[an undesirable effect leading to performance issues, but *not* a bug\] it keeps interrupts off for a longer time period than is necessary. The code above was best: it kept interrupts off the absolute minimum time possible by just making copies of the volatile variables, and it ensured this whole `if` statement block was atomic by simply using the copy there, which automatically acts as an "atomic access guard" by itself and enforces atomicity in the `if` statement block.

**2 of 3: this still has 2 problems: one is a bug, and one is a performance issue but not a bug:**

```
volatile int pos  = 0; // assume this variable is still an `int`, which is 2-bytes

void loop() {
    uint8_t SREG_bak = SREG; // back up the global interrupt state
    noInterrupts(); // disable interrupts

    if (oldpos != pos) {
        oldpos = pos;
        Serial.println(pos);
    }

    // restore interrupt state, turning them back ON if they were ON before,
    // or leaving them OFF if they were OFF before.
    SREG = SREG_bak;

    delay(100);
}

```

And lastly, what if the volatile variable was a 1-byte variable? Well, then you could simplify to this, since reading a 1-byte variable is naturally an atomic operation!

**3 of 3: this works too (without bugs and without performance issues), but ONLY if your volatile variable here is 1-byte!:**

```
// this variable is now a 1-byte variable, which has naturally atomic read and
// write operations! (but not increment or decrement)
volatile int8_t pos  = 0;

void loop() {
    // Make copies of your volatile variables here.
    // Being a 1-byte variable on an 8-bit (1-byte) CPU architecture, this operation
    // is already naturally atomic, so no need for "atomic access interrupt guards".
    int8_t pos_copy = pos;

    // Now do what you want with the copy, using pos_copy ONLY,
    // to avoid race conditions! (ie: using this copy here enforces
    // this entire block to be naturally atomic now, and by itself
    // is a form of "atomic access guards", as explained above.)
    if (oldpos != pos_copy) {
        oldpos = pos_copy;
        Serial.println(pos_copy);
    }
    delay(100);
}

```

For *3 other ways to create atomic access guards in 8-bit AVR-based Arduinos*, see my answer from 2016 here: https://stackoverflow.com/questions/36381932/c-decrementing-an-element-of-a-single-byte-volatile-array-is-not-atomic-why/39693278#39693278.

*Last comment:* Paul Stoffregen is one of the most-expert in Arduino in our day. I'm sure he makes mistakes, but my default is to trust anything he's written. He's a most-excellent software developer and engineer: one of the absolute best in the entire world. Look for bugs in what he writes, and let him know if you found any, but you have unaddressed race conditions here, so that's what I'd look at first.

# References:

1. My own race condition problem: https://stackoverflow.com/questions/36381932/c-decrementing-an-element-of-a-single-byte-volatile-array-is-not-atomic-why
2. My own race condition solution, demonstrating 3 (or 4, depending on how you look at it) ways to enforce **"atomic access guards"** on AVR-based 8-bit Arduinos: https://stackoverflow.com/questions/36381932/c-decrementing-an-element-of-a-single-byte-volatile-array-is-not-atomic-why/39693278#39693278

---
Tags: arduino-ide
---


# Question
Title: Can the Mouse library scroll horizontally?
I'm using the Mouse library with an ATmega32U4 connected to Linux via USB.

I would like to issue horizontal scroll commands, but the Mouse.move() function only seems to accept X movement, Y movement and vertical scroll parameters.

How can I send horizontal scroll commands from the Arduino to the computer?

# Answer
As suggested in the comments, I edited the core libraries to achieve this.

I'm using PlatformIO, so the library files I needed to edit were here:

```
~/.platformio/packages/framework-arduinoavr/libraries/Mouse/src/

```

And the required changes (to change a `wheel` parameter for horizontal (`h`) and vertical (`v`) scroll parameters were as follows:

**Mouse.h**

Change the declaration of `move()`:

```
...
void move(signed char x, signed char y, signed char h = 0, signed char v = 0);
...

```

**Mouse.cpp**

Add the following to the report descriptor after the last `INPUT` message:

```
...
0x05, 0x0c,        //       USAGE PAGE (Consumer Devices)
0x0a, 0x38, 0x02,  //       USAGE (AC Pan)
0x15, 0x81,        //       LOGICAL_MINIMUM (-127)
0x25, 0x7f,        //       LOGICAL_MAXIMUM (127)
0x75, 0x08,        //       REPORT_SIZE (8)
0x95, 0x01,        //       REPORT_COUNT (1)
0x81, 0x06,        //       INPUT (Data, Var, Rel)
...

```

Change the definition of `move()`:

```
void Mouse_::move(signed char x, signed char y, signed char h, signed char v)
{
    uint8_t m[5];
    m[0] = _buttons;
    m[1] = x;
    m[2] = y;
    m[3] = v;
    m[4] = h;
    HID().SendReport(1, m, 5);
}

```

---

The following terminal commands were also useful in testing these changes:

```
# List input devices
xinput --list

# List device capabilities
xinput --list <device-id>

# Watch for data sent from the device
watch -n 0.1 xinput query-state <device-id>

```
> 2 votes

# Answer
Horizontal Scroll is achieved by holding shift when scrolling vertically.

Do this instead:

```
Keyboard.press(KEY_LEFT_SHIFT);
    Mouse.move(0, 0, 1);
    Keyboard.releaseAll();

```
> 0 votes

---
Tags: usb, linux, atmega32u4, mouse
---


# Question
Title: Better way for connecting to Arduino pins to a sensor than jumper cable
Well I have an dht21 and arduino mega. Dht21 leads look like this

If I use jumper cable and soldering dht21 leads with jumper cable than plug-in my arduino's socket. it looks like this below image. It dont looks safe. If the device falls to the ground or something, the cables may come out of place or the place may loosen over time. If I solder the cables under the arduino, it will be hard and looks like ugly. What is the best solution to plug-in a sensor to arduino board.

# Answer
There is also the option of a Prototyping Screw Shield which converts the Arduino pins into terminal screw blocks. This makes a more permanent connection without being completely permanent.
> 1 votes

# Answer
Remember the Arduino is a prototyping system and it should be easy to plug, unplug and move around connectors.

If you want a permanent solution, you should make your own PCB and you will have a huge choice of connectors suited for all imaginable purposes (for example the JST family of connectors).

There are some connectivity systems like the Grove connector that have attempted to standardize connectivity on Arduino and related platforms.
> 1 votes

# Answer
One option you have is to solder your sensor leads to a set of header pins. The friction of multiple pins secured in a header will be greater than that of individual jumpers. When soldering to the header pins, use a method to secure the pins from movement, as the heat of the soldering iron may soften the plastic holding the pins.

The image below, from Digikey, is representative and does not imply correct spacing or fit for an Arduino.

Arduino solder shields are also available. This is a complete circuit board, akin to StarCat's recommendation of a custom PCB, but off-the-shelf. It allows access to all pins on the specific Arduino for which it was designed. I consider this option excessive for three connections, but include it for completeness.
> 1 votes

---
Tags: arduino-mega, sensors, connector
---


title: How to ssh via USB Ethernet adapter

text:
# Question
Title: How to ssh via USB Ethernet adapter
For a few days now, I have been connecting to my board which is hooked up to my router through a clutter of wires, over Wi-Fi. To spare my family from the risk of tripping, or hogging the extension cords all to myself, I'm looking for a way to establish an ssh connection directly from my computer (either via a USB Ethernet or a Thunderbolt Ethernet adapter).

My question is *what address* will I be looking for? Is it something like `arduinoname.local`?

# Answer
```
ssh root@[arduinoname].local

```

does the trick. Just replace \[arduinoname\] with your board's name: `ssh root@myboard.local`

Seems to take a minute or two to initialize, so if it doesn't work immediately don't give up right away!

This however won't allow you to access your internet, so I'll still have to connect to my router if I'm going to be downloading anything.
> 1 votes

---
Tags: arduino-galileo, ssh, connector
---