# Question
Title: Program Arduino via UART from ESP8266 SPIFFS
I have built a custom board that has an ATmega328p connected to an ESP8266 module via UART. I am currently programming the ATmega328p using a USBtiny programmer via an SPI header. The ESP8266 module is programmed via an FTDI cable connected the the UART.

Firmware for both are created in Arduino IDE.

I have set up a webserver on the ESP that allows for files to be uploaded to the SPIFFS via FTP. I would like to be able to upload a hex file for the ATmega and then have the ESP program the ATmega via the UART connection. A GPIO on the ESP controls a transistor that can pull the reset pin on the ATmega to ground.

I know I need a bootloader on the ATmega (e.g. optiboot), but I don't know what I need to make the ESP do to trigger the bootloader and flash the ATmega. I'm thinking I need something like:

```
void initialiseAtmegaFlash () {
  // Trigger the bootloader to accept incoming hex over UART
}

void flashHexToAtmega (File atmegaHex) {
  for (uint32_t i = 0; i < atmegaHex.size(); ++i) {
    // Handle timing of sending byte by byte over serial... or chunk by chunk?
  }
}

```

# Answer
To answer my own question in case someone else ends up here, the library Juraj suggested (https://github.com/ciminaghi/libdfu) looks like it does the job. I also found another project doing something similar (https://github.com/rene-win/esp\_avr\_programmer). Also the STK500 docs linked to by Majenko (http://ww1.microchip.com/downloads/en/AppNotes/doc2591.pdf) are really useful for understanding the nuts and bolts!
> 1 votes

---
Tags: esp8266, uart, flash
---


# Question
Title: What do the numbers behind lcd (0x27) mean?
I can't seem to figure out what the numbers after 0x27 mean. I understand that 0x27 stands for the I2C address and POSITIVE stands for the backlight, but what do the other number mean?

> LiquidCrystal\_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE)

# Answer
> 3 votes
Assuming You're using the same LCD library I'm using, there is a longer form of the constructor that takes pin assignments for the different pins on the I2C module, as Majenko says.

I'm at work, so I don't have access to my code, but your constructor looks a whole lot like the one I use for my module, which has non-standard pin assignment. (I got my LCD modules from oddWires, and they came without documentation. I had to do quite a bit of detective work to figure out how to make them work.)

**EDIT**

I use the Newliquidcrystal\_1.3.5 library in my project, to interface the above-mentioned oddWires I2C LCD display. That library has various constructors, one of which takes all the parameters you list. Those extra numbers indicate the pins that connect to the I2C module.

My oddWires LCDs need exactly the settings you list in the constructor. Your milage may vary.

The long form is defined in the library header with

```
LiquidCrystal_I2C(
    uint8_t lcd_Addr,
    uint8_t En,
    uint8_t Rw,
    uint8_t Rs,

    uint8_t d4,
    uint8_t d5,
    uint8_t d6,
    uint8_t d7,
    uint8_t backlighPin,
    t_backlighPol pol
);

```

From the naming of the parameters you can deduce most of them:

* En is an enable line
* Rw is a read/write line?
* Rs is ?
* d4-47 are the data pins
* backlightPin is the pin that turns backlight on and off
* pol indicates the backlight polarity (`POSITIVE` probably means pull the line high to enable the backlight.

---
Tags: i2c, lcd
---


title: Hold button / press button/ push button

text:
# Question
Title: Hold button / press button/ push button
I want to control a servo motor in a way that

* if you push the button, you can control it by potentiometer a
* if you push double time, you can control servo with infrared
* if you hold button step motor start to to rotate from one position to another

I have a problem that when I press button it goes to an infinite loop and I can not stop it . I try different button library but I still have a same problem. Here is my code :

```
// includes the Servo library
#include <Servo.h>
#include <IRremote.h>
#include <OneButton.h>

int state = 0;
int RECV_PIN = 12;
const char type ='W';// W for white, B for black. Must keep single quotes like 'B' or 'W'
const boolean PCB = 0;// if receiver is PCB set to 1, if not set to 0. See video for details
boolean displayCode = true;// to display remote code. if not, set to false

const int SERVO_PIN = 8;  // analog pin used to connect the potentiometer
int angle =90;    // initial angle  for servo
int angleStep =10;
const int ANGLE_CENTRE =90;// the centre/reset angle of your servo
//**** Servo settings settings ends

// remote settings
const String RIGHT="CH+";// move servo to the right with this key on remote
const String LEFT ="CH-";// move servo to the left with this key on remote
const String CENTRE ="CH";// move servo to centre with this key on remote
// remote settings end

IRrecv irrecv(RECV_PIN);
// Defines Tirg and Echo pins of the Ultrasonic Sensor
const int trigPin = 10;
const int echoPin = 11;
const int potPin = 0;
const int pushButton = 8;
OneButton button(A1, true);
int value;

// Variables for the duration and the distance
long duration;
int distance_cm;
Servo myServo; // Creates a servo object for controlling the servo motor

// this is array holding codes for White Remote when used with non-PCB version of receiver
unsigned int whiteRemote[] ={
            0xFFA25D, // CH-
            0xFF629D,   // CH
            0xFFE21D,  // CH+

            0xFF22DD, // |<<
            0xFF02FD, // >>|
            0xFFC23D, // >||

            0xFFE01F, // -
            0xFFA857, // +
            0xFF906F, // EQ

            0xFF6897, // 0
            0xFF9867, // 100+
            0xFFB04F, // 200+

            0xFF30CF, // 1
            0xFF18E7, // 2
            0xFF7A85, // 3

            0xFF10EF, // 4
            0xFF38C7, // 5
            0xFF5AA5,  // 6

            0xFF42BD, // 7
            0xFF4AB5, // 8
            0xFF52AD  // 9
            };
// key lables of white remote
 String whiteRemoteKey[] ={
            "CH-",
            "CH",
            "CH+",

            "|<<",
            ">>|",
            ">||",

            "-",
            "+",
            "EQ",

            "0",
            "100+",
            "200+",

            "1",
            "2",
            "3",

            "4",
            "5",
            "6",

            "7",
            "8",
            "9"
            };

// this is array holding codes for Black Remote when used with non-PCB version of receiver
 unsigned int blackRemote[] ={
            0xFF629D, // ^
            0x38D3975C,   // <
            0x9334F738,  // OK
            0x320412D8, // >
            0xFFA857, // v

            0xFF6897, // 1
            0xFF9867, // 2
            0xF0C41643, // 3

            0xFF30CF, // 4
            0xFF18E7, // 5
            0xFF7A85,  // 6

            0xFF10EF, // 7
            0xFF38C7, // 8
            0xFF5AA5,  // 9

            0xFF42BD, // *
            0xFF4AB5, // 0
            0xFF52AD  // #
            };
// Black remote key names
 String blackRemoteKey[] ={
            "^",
            "<",
            "OK",
            ">",
            "v",

            "1",
            "2",
            "3",

            "4",
            "5",
            "6",

            "7",
            "8",
            "9",

            "*",
            "0",
            "#"
            };

decode_results results;

void setup() {
  pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
  pinMode(echoPin, INPUT); // Sets the echoPin as an input
  Serial. begin(9600);
  irrecv.enableIRIn(); // Start the receiver
  myServo.attach(SERVO_PIN); // Defines on which pin is the servo motor attached

  button.attachDoubleClick(doubleClick);            // link the function to be called on a doubleClick event.
  button.attachClick(singleClick);                  // link the function to be called on a singleClick event.
  button.attachLongPressStop(longClick);            // link the function to be called on a longpress event.

}
void loop() {
  button.tick();                                    // check the status of the button
  delay(10);                                        // a short wait between checking the button
}

// Function for calculating the distance measured by the Ultrasonic sensor
int calculateDistance(){
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  // Sets the trigPin on HiGH state for 10 micro seconds
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH); // Reads the echoPin, returns the sound wave travel time in microseconds
  //Comment by me!
  //distance= duration*0.034/2;
  //
  distance_cm = (duration/2) / 29.1;
  return distance_cm;
}
void doubleClick() {                                // what happens when button is double-clicked
  while(1) {
    if (irrecv.decode(&results)) {
      if(displayCode)Serial.println(results.value, HEX);
      validateCode(results.value);// used the "robojaxValidateCode" bellow
      irrecv.resume(); // Receive the next value
    }
    delay(50);// 50 melisecond delay
    break;
  }
}

void singleClick(){                                 // what happens when the button is clicked
  while(1) {
    value = analogRead(potPin);
    value = map(value, 0, 1023, 15, 165);
    myServo.write(value);
    delay(30);
    distance_cm = calculateDistance();

    Serial.print(value); // Sends the current degree into the Serial Port
    Serial.print(","); // Sends addition character right next to the previous value needed later in the Processing iDE for indexing
    Serial.print(distance_cm); // Sends the distance value into the Serial Port
    Serial.print("."); // Sends addition character right next to the previous value needed later in the Processing iDE for indexin
  }
}

void longClick(){                                   // what happens when buton is long-pressed
  for(int i=15;i<=165;i++){
    myServo.write(i);
    delay(30);
    distance_cm = calculateDistance();// Calls a function for calculating the distance measured by the Ultrasonic sensor for each degree

    Serial.print(i); // Sends the current degree into the Serial Port
    Serial.print(","); // Sends addition character right next to the previous value needed later in the Processing iDE for indexing
    Serial.print(distance_cm); // Sends the distance value into the Serial Port
    Serial.print("."); // Sends addition character right next to the previous value needed later in the Processing iDE for indexin
  }
  // Repeats the previous lines from 165 to 15 degrees
  for(int i=165;i>15;i--){
    myServo.write(i);
    delay(30);
    distance_cm = calculateDistance();

    Serial.print(i);
    Serial.print(",");
    Serial.print(distance_cm);
    Serial.print(".");
  }
}
/*
 * function: validateCode
 * validates the remote code and prints correct key name
 * cd is code poassed from the loop
 * Written by A. S. for Robojax
 */
void validateCode(int cd)
{

  // Robojax IR Remote decoder
  int found=0;

 if(type =='W' && !PCB)
 {
    // Robojax IR White Remote decoder
    // if tyepe is set to 'W' (white remote) and PCB=0 then check Black remote code
      for(int i=0; i< sizeof(whiteRemote)/sizeof(int); i++)
      {
        if(whiteRemote[i] ==cd)
        {

          Serial.print("Key pressed:");
          Serial.println(whiteRemoteKey[i]);
          servoAction(whiteRemoteKey[i]);// take action
          found=1;
        }// if matched
      }// for
 }else{

      // if tyepe is set to 'B' (black remote) and PCB =0 then check Black remote code
       for(int i=0; i< sizeof(blackRemote)/sizeof(int); i++)
      {
        // Robojax IR black Remote decoder
        if(blackRemote[i] ==cd)
        {

          Serial.print("Key pressed:");
          Serial.println(blackRemoteKey[i]);
          servoAction(blackRemoteKey[i]);// take action

          found=1;
        }// if matched
      }// for
 }// else
  if(!found){
    if(cd !=0xFFFFFFFF)
      {
    Serial.println("Key unkown");
      }
  }// found
}// validateCode end

/*
 *
 * servoAction()
 * receives string "value" as input and based on the settings,
 * sends translates it to servo value and controls servo
 * either
 * rotates servo to right
 * rotates servo to left
 * moves the servo to middle
 *
 */
void servoAction(String value){
  // Servo button demo with IR remote by Robojax.com
  while(value == RIGHT){

    if (angle > 0 && angle <= 180) {
      angle = angle - angleStep;
       if(angle < 0){
        angle = 0;
       }else{
      myServo.write(angle); // move the servo to desired angle
      Serial.print("Moved to: ");
      Serial.print(angle);   // print the angle
      Serial.println(" degree");
       }
    }// if
    value =".";
    delay(100);
  }// while for RIGHT
  while(value == LEFT){

    // Servo button demo with IR remote by Robojax.com
    if (angle >= 0 && angle <= 180) {
      angle = angle + angleStep;
      if(angle >180){
        angle =180;
       }else{
      myServo.write(angle); // move the servo to desired angle
      Serial.print("Moved to: ");
      Serial.print(angle);   // print the angle
      Serial.println(" degree");
       }
    }
    value =".";
    delay(100);
  }// while for LEFT

  if(value == CENTRE)
  {
    angle = ANGLE_CENTRE;
    myServo.write(angle); // move the servo to centre at 90 degree angle
  }
    // Robojax IR Servo control
}//relayAction end

```

sorry about my English. I hope someone help me.

# Answer
> 0 votes
You have infinite loops in the click event call functions, after a button event you never return to the main loop.

Use the event functions just to set a status variable then, in the main loop use switch case case to select the code used by the servo control like this:

```
 ....
 unsigned int status = 0;
 ....
 void doubleClick(){
    status = 0;
 }
 void singleClick(){
    status = 1;
 }
 void longClick(){
    status = 2;
 }
 void setup() {
 ....
 }
 void loop {
   button.tick();                                    // check the status of the button
   //delay(10); // this is not needed.
   switch (status){
     case 0:{
       //action for double click
     }
     case 1:{
       //action for single click
     }
     case 2:{
       //action for long click
     }
 }

```

Inside each case insert the corresponding code code you have in the while(1) loops of the button event functions.

Another option is to insert inside the forever loops a return when the button is pressed like this:

if (button pressed) return;

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


# Question
Title: Will this buck converter power my arduino?
I'm thinking of using something like this: https://www.amazon.ca/Dolity-Converter-Isolated-Switching-Transformer/dp/B07CSZ1174?SubscriptionId=AKIAILSHYYTFIVPWUY6Q&tag=duc12-20&linkCode=xm2&camp=2025&creative=165953&creativeASIN=B07CSZ1174

or this: https://www.amazon.ca/Voltage-Regulator-Converter-Transformer-Protection/dp/B07LC1C4ZZ?SubscriptionId=AKIAILSHYYTFIVPWUY6Q&tag=duc12-20&linkCode=xm2&camp=2025&creative=165953&creativeASIN=B07LC1C4ZZ

to power my arduino.

The reason for this is I have a contained box with a few pieces of equipment (all on ac power) controlled by an Uno. There is a single AC power cord (North American) running from the box to power the whole unit. Obviously this just leaves the Uno.

Sure the standard 5V barrel adapter prongs could be shrink wrapped to the raw AC wires but that's not very clean. I was imagining a module like those converters that could be wired into the VIN pin and gnd after converting the AC input from the main power line going to the box.

The uno is powering an ethernet shield, 4 port relay, sht20 sensor, mh-z16 sensor, and 16x2 lcd display.

Thoughts? Honestly this isn't really my call. My boss doesn't want any plugs or standard outlets inside the box. It's like he only wants it to be formal circuit boards and soldering. No shrink wrap or electrical tape. Yes I realize standard adapters that plug into a wall are already at a price that won't be possible to beat.

# Answer
> Sure the standard 5V barrel adapter prongs could be shrink wrapped to the raw AC wires but that's not very clean.

Also very deadly. **DO NOT DO THIS!!!!** The Arduino will explode (literally. I am **NOT** joking here!!!) and potentially electrocute you.

---

Those modules you show are not "buck" regulators. They are SMPS modules - an entirely different thing.

Yes, one of those would be suitable for powering an Arduino from a mains supply, but given your supposition above I rather suspect your skills and knowledge would make wiring it up a dangerous prospect.

Better would be to use a proper off-the-shelf power plug and have someone qualified install a suitable socket inside the enclosure.
> 1 votes

---
Tags: arduino-uno, power
---


# Question
Title: How should I combine the codes for two sensors in 1 Arduino sketch?
Name of study: AUTOMATIC ELECTRIC FAN

We used an ultrasonic sensor for the switching on/off of our Fan and an LM35 SENSOR to control the speed regulation. During our experiment, we use a LED instead of a Fan before we proceed to fan. Here is our code:

Description: Codes for LM35 Sensor using LED and Arduino Uno as Microcontroller)

```
#define led 9
float temp;

void setup ()
{
   pinMode(led, OUTPUT);
   Serial.begin(9600);
}

 void loop ()
{
    temp = analogRead (A0);
    temp = temp*0.48828125;
     if (temp < 31 )
  {
    digitalWrite(led, HIGH);
  }
  else {

    digitalWrite(led, LOW);
  }
    Serial.print("TEMPERATURE: ");
    Serial.print(temp);
    Serial.print("*C");
     Serial.println();
     delay(1000);
 }

```

Description: Code for ULTRASONIC SENSOR using two LED’s AND Arduinbo Uno as Microcontroller

```
#define trigPin 13
#define echoPin 12
#define led 6
#define led 5
{
  digitalWrite(trigPin, LOW);
  delayMicroseconds (2);

  digitalWrite(trigPin, HIGH);
  delayMicroseconds (10);
  digitalWrite(trigPin, LOW);

  duration = pulseIn(echoPin, HIGH);
  distance = duration*0.034/2;
  if (distance < 100 )
  {
    digitalWrite(led, HIGH);
  }
  else {

    digitalWrite(led, LOW);
  }
  Serial.print("Distance:");
  Serial.println(distance);
  Serial.print("cm");
  delay(1000);
}

```

# Answer
> 2 votes
You don't have two codes; the 2nd section has no setup() or loop().

If it did, then you could do this:

* The stuff before setup() gets put together.
* The stuff in setup() from one gets moved into the other. The empty setup() gets deleted.
* The stuff in loop() from one gets moved into the other. The empty loop() gets deleted.

Take care of any duplicate names, pin assignments, etc.

Review the combined loop() code and adjust as needed to do what you want.

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


title: Cannot read modbus data repetitively

text:
# Question
Title: Cannot read modbus data repetitively
I try to communicate with 2 RS485 sensors (pH and EC), but I have some troubles with my code. First, I tried to get data from just one:

The function in charge of request sending:

```
String GET_probe(String probe){

if(probe == "pH"){
Serial.println("Sending request pH...");
digitalWrite(modbusModuleRE, RS485Transmit);  // Init Transceiver
digitalWrite(modbusModuleDE, RS485Transmit);  // Init Transceiver
byte  RTUrequest[] = {0x00, 0x03, 0x00, 0x00, 0x00, 0x01, 0x85, 0xDB};
RS485Serial.write(RTUrequest, sizeof(RTUrequest));
}

if(probe == "EC"){
Serial.println("Sending request EC...");

digitalWrite(modbusModuleRE, RS485Transmit);  // Init Transceiver
digitalWrite(modbusModuleDE, RS485Transmit);  // Init Transceiver
byte  RTUrequest[] = {0x01, 0x03, 0x00, 0x00, 0x00, 0x02, 0xC4, 0x0B};
RS485Serial.write(RTUrequest, sizeof(RTUrequest));
}

RS485Serial.flush();
RS485Serial.listen();
}

```

The function in charge of reading sensor's answer:

```
void ReadRx() {
     digitalWrite(modbusModuleRE, RS485Receive);
     digitalWrite(modbusModuleDE, RS485Receive);
     if(RS485Serial.available()) {
     Serial.print("Answer: ");
      for(int i=0; i<7; i++){
          String myByte = String(RS485Serial.read(), HEX);// Read the byte

          if (myByte.length() == 1)
          {
            myByte = "0"+myByte;
          }
          modbusHexBuffer[i] = myByte;

          Serial.print(myByte);
          Serial.print(" ");
      }
      Serial.println();
    }
   }

```

And the loop, sending the request each 5s:

```
void loop(){

  static uint32_t ts = millis();

  if (millis() - ts >= 5000) {
      ts = millis();
      GET_probe("pH");
  }

ReadRx();
}

```

The loop runs fine once and fails the second time, as shown in terminal. Can you tell me why and help me to fix it?

```
Sending request pH...
Answer: 00 03 02 05 78 86 f6
Sending request pH...

```

# Answer
> 1 votes
I have found why !!!

1st: buf\[8\] instead buf\[7\] in declaration 2nd: reinit byte buf\[8\] before EC request part.

So the code who works fine is:

```
byte buf[8];
void loop(){

      Serial.print("pH: ");
      digitalWrite(modbusModuleRE, RS485Transmit);  // Init Transceiver
      digitalWrite(modbusModuleDE, RS485Transmit);  // Init Transceiver
      byte  pHrequest[] = {0x00, 0x03, 0x00, 0x00, 0x00, 0x01, 0x85, 0xDB};
      RS485Serial.write(pHrequest, sizeof(pHrequest));
      RS485Serial.flush();
      digitalWrite(modbusModuleRE, RS485Receive);
      digitalWrite(modbusModuleDE, RS485Receive);
      RS485Serial.readBytes(buf, 8);
     Serial.print(buf[3], HEX);Serial.println(buf[4], HEX);

byte buf[8];

      Serial.print("EC: ");
      digitalWrite(modbusModuleRE, RS485Transmit);  // Init Transceiver
      digitalWrite(modbusModuleDE, RS485Transmit);  // Init Transceiver
      byte  ECrequest[] = {0x01, 0x03, 0x00, 0x00, 0x00, 0x02, 0xC4, 0x0B};
      RS485Serial.write(ECrequest, sizeof(ECrequest));
      RS485Serial.flush();
      digitalWrite(modbusModuleRE, RS485Receive);
      digitalWrite(modbusModuleDE, RS485Receive);
      RS485Serial.readBytes(buf, 8);
      Serial.print(buf[3], HEX);Serial.print(buf[4], HEX);Serial.print(buf[5], HEX);Serial.println(buf[6], HEX);

Serial.println();

}

```

---
Tags: rs485, modbus
---


# Question
Title: Looking for a cheap small arduino ish board
I'm looking for a cheap and small bluetooth board for a project. I found this one, but I find this one too expensive, are there cheaper alternatives, in similar size?

Thank you!

# Answer
> 2 votes
I'd suggest investigating the ESP32.

It's not only a far more powerful chip than any normal Arduino, but it has both WiFI *and* Bluetooth Low Energy, all on the one chip.

It's available as surface mount modules, similar to the ESP8266, and there are a number of small development boards that have been created around it as well.

---
Tags: bluetooth, project
---


title: Blinking LEDs in sequence with a class

text:
# Question
Title: Blinking LEDs in sequence with a class
I am trying to make a program that accepts four digit password using a 3\*4 keypad.

The program should start with flashing LED1 and when password 1 is entered it switches this LED and blinks LED2. If password 2 is entered it switches to LED3 and so on.

Here is the code:

```
#include <Keypad.h>
#include <TimedBlink.h>

#define Password_Length 5

TimedBlink led1(14);
TimedBlink led2(15);
TimedBlink led3(16);
TimedBlink led4(17);

const unsigned long PERIOD1 = 1000;
char  buffers[4][4] = {{'1', '2', '3', '4'}, {'6', '5', '4', '3'}, {'9', '8', '7', '6'}, {'1', '2', '5', '6'}}; // this is how to initialise a 2d array
unsigned long previousMillis[5]; //[x] = number of leds
char Data[Password_Length]; // 6 is the number of chars it can hold + the null char = 7

byte data_count = 0;
bool Pass_is_good;
char customKey;

const byte ROWS = 4;
const byte COLS = 3;
char keys[ROWS][COLS] = {
  {'1', '2', '3'},
  {'4', '5', '6'},
  {'7', '8', '9'},
  {'*', '0', '#'}
};

byte rowPins[ROWS] = {2, 3, 4, 5}; //connect to the row pinouts of the keypad
byte colPins[COLS] = {6, 7, 8}; //connect to the column pinouts of the keypad
int ledservos[4] = {14, 15, 16, 17};
Keypad customKeypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS); //initialize an instance of class NewKeypad

void setup() {
  pinMode(14, OUTPUT);
  pinMode(15, OUTPUT);
  pinMode(16, OUTPUT);
  pinMode(17, OUTPUT);
  led1.blink(150, 50); // On for 150ms, off for 50ms
  led2.blink(150, 50);
  led3.blink(150, 50); // On for 150ms, off for 50ms
  led4.blink(150, 50);
  Serial.begin(9600);
  Serial.print("Enter Password");
  Serial.println();
}

void loop() {
  led1.blink();
  led2.blink();
  led3.blink();
  led4.blink();
  customKey = customKeypad.getKey();
  if (customKey) {
  // makes sure a key is actually pressed, equal to (customKey != NO_KEY)
    Data[data_count] = customKey; // store char into data array
    data_count++; // increment data array by 1 to store new char, also keep track of the number of chars entered
  }
  if (data_count == Password_Length - 1) {
    // if the array index is equal to the number of expected chars, compare data to master
    Serial.print("Password is ");
    for (byte i = 0; i < Password_Length; i++)
      Serial.print(Data[i]);
    for (x = 0; x < 4; x++) { //this loop for number of passwords in the array
      for (y = 0; y < 4; y ++) { //this loop for number of characters in each of the password array
        if (strcmp(Data[y], buffers[x][y]) != 0) {
          break;
        }
      }
      if (y == 4) {
        break;
      }
    }
    if (x < 4) {
      Serial.print(" Found at index ");
      Serial.println(x);
      switch (x) {
        case 0:
          led1.blinkOff();
          break;
        case 1:
          led2.blinkOff();
          break;
        case 2:
          led3.blinkOff();
          break;
        case 3:
          led4.blinkOff();
          break;
      }
    }
    clearData();
  }
}

void clearData() {
  Serial.println();
  while (data_count != 0) {
    // This can be used for any array size,
    Data[data_count--] = 0; //clear array for new data
  }
}

void BlinkLed (int led, int interval, int arry) {
  //(long) can be omitted if you dont plan to blink led for very long time I think
  if (((long)millis() - previousMillis[arry]) >= interval) {
    previousMillis[arry] = millis(); //stores the millis value in the selected array
    digitalWrite(led, !digitalRead(led)); //changes led state
  }
}

```

Now I can make the program, but all LEDs start blinking and switch off after the password is entered and I got stuck at this point.

Here is a link to the TimedBlink Library.

I have tried the `millis()` function to be used to blink LEDs in the next code:

```
#include <Keypad.h>
#include <Wire.h>

#define buzzer 13
#define greenled 20
#define redled 21
#define Password_Length 5

unsigned long previousMillisLED14 = 0;
unsigned long previousMillisLED15 = 0;
unsigned long previousMillisLED16 = 0;
unsigned long previousMillisLED17 = 0;
// different intervals for each LED
int intervalLED14 = 500;
int intervalLED15 = 600;
int intervalLED16 = 700;
int intervalLED17 = 800;
// each LED gets a state varaible
boolean LED14state = false;     // the LED will turn ON in the first iteration of loop()
boolean LED15state = false;     // need to seed the light to be OFF
boolean LED16state = false;     // need to seed the light to be OFF
boolean LED17state = false;     // need to seed the light to be OFF
const unsigned long PERIOD1 = 1000;
char  buffers[4][4] = {{'1', '2', '3', '4'}, {'6', '5', '4', '3'}, {'9', '8', '7', '6'}, {'1', '2', '5', '6'}}; // this is how to initialise a 2d array
unsigned long previousMillis[5]; //[x] = number of leds
byte i, x, y;
char Data[Password_Length]; // 6 is the number of chars it can hold + the null char = 7
byte data_count = 0;
bool Pass_is_good;
char customKey;
const byte ROWS = 4;
const byte COLS = 3;
char keys[ROWS][COLS] = {
  {'1', '2', '3'},
  {'4', '5', '6'},
  {'7', '8', '9'},
  {'*', '0', '#'}
};
byte rowPins[ROWS] = {2, 3, 4, 5}; //connect to the row pinouts of the keypad
byte colPins[COLS] = {6, 7, 8}; //connect to the column pinouts of the keypad
int ledservos[4] = {14, 15, 16, 17};
Keypad customKeypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS); //initialize an instance of class NewKeypad

void setup() {
  pinMode(14, OUTPUT);
  pinMode(15, OUTPUT);
  pinMode(16, OUTPUT);
  pinMode(17, OUTPUT);
  Serial.begin(9600);
  pinMode(buzzer, OUTPUT);
  pinMode(redled, OUTPUT);
  pinMode(greenled, OUTPUT);
  Serial.print("Enter Password");
  Serial.println();
}

void loop() {
  unsigned long currentMillis = millis();
  if ((unsigned long)(currentMillis - previousMillisLED14) >= intervalLED14) {
    LED14state = !LED14state;
    digitalWrite(14, LED14state);
    // save current time to pin 12's previousMillis
    previousMillisLED14 = currentMillis;
  }
  customKey = customKeypad.getKey();
  if (customKey) {
    // makes sure a key is actually pressed, equal to (customKey != NO_KEY)
    Data[data_count] = customKey; // store char into data array
    data_count++; // increment data array by 1 to store new char, also keep track of the number of chars entered
  }
  if (data_count == Password_Length - 1) {
    // if the array index is equal to the number of expected chars, compare data to master
    Serial.print("Password is ");
    for (byte i = 0; i < Password_Length; i++)
      Serial.print(Data[i]);
    for (x = 0; x < 4; x++) {
      //this loop for number of passwords in the array
      for (y = 0; y < 4; y ++) {
        //this loop for number of characters in each of the password array
        if (strcmp(Data[y], buffers[x][y]) != 0) {
          break;
        }
      }
      if (y == 4) {
        break;
      }
    }
    if (x < 4) {
      Serial.print(" Found at index ");
      Serial.println(x);
      switch (x) {
        case 0:
          digitalWrite(14, LOW);
          digitalWrite(16, LOW);
          digitalWrite(17, LOW);
          if ((unsigned long)(currentMillis - previousMillisLED15) >= intervalLED15) {
            LED15state = !LED15state;
            digitalWrite(15, LED15state);
            // save current time to pin 12's previousMillis
            previousMillisLED15 = currentMillis;
          }
          break;
        case 1:
          digitalWrite(15, LOW);
          digitalWrite(14, LOW);
          digitalWrite(17, LOW);
          if ((unsigned long)(currentMillis - previousMillisLED16) >= intervalLED16) {
            LED16state = !LED16state;
            digitalWrite(16, LED15state);
            // save current time to pin 12's previousMillis
            previousMillisLED16 = currentMillis;
          }
          break;
        case 2:
          digitalWrite(15, LOW);
          digitalWrite(14, LOW);
          digitalWrite(16, LOW);
          if ((unsigned long)(currentMillis - previousMillisLED17) >= intervalLED17) {
            LED17state = !LED17state;
            digitalWrite(17, LED17state);
            // save current time to pin 12's previousMillis
            previousMillisLED17 = currentMillis;
          }
          break;
        case 3:
          digitalWrite(15, LOW);
          digitalWrite(14, LOW);
          digitalWrite(16, LOW);
          digitalWrite(17, LOW);
          break;
      }
    }
    clearData();
  }
}

void clearData() {
  Serial.println();
  while (data_count != 0) {
    // This can be used for any array size,
    Data[data_count--] = 0; //clear array for new data
  }
}

```

But it blinks the first LED only, then each of the following LEDs according to the condition got permanent on. I have tried the solution that Adafruit suggested, to use a class in code but unfortunately I got the same result as the previous code.

Here is the code:

```
#include <Keypad.h>
#include <Wire.h>

class Flasher {
    // Class Member Variables
    // These are initialized at startup
    int ledPin;      // the number of the LED pin
    long OnTime;     // milliseconds of on-time
    long OffTime;    // milliseconds of off-time
    // These maintain the current state
    int ledState;                 // ledState used to set the LED
    unsigned long previousMillis;   // will store last time LED was updated
    // Constructor - creates a Flasher
    // and initializes the member variables and state
  public:
    Flasher(int pin, long on, long off) {
      ledPin = pin;
      pinMode(ledPin, OUTPUT);
      OnTime = on;
      OffTime = off;
      ledState = LOW;
      previousMillis = 0;
    }
    void Update() {
      // check to see if it's time to change the state of the LED
      unsigned long currentMillis = millis();
      if ((ledState == HIGH) && (currentMillis - previousMillis >= OnTime)) {
        ledState = LOW;  // Turn it off
        previousMillis = currentMillis;  // Remember the time
        digitalWrite(ledPin, ledState);  // Update the actual LED
      } else if ((ledState == LOW) && (currentMillis - previousMillis >= OffTime)) {
        ledState = HIGH;  // turn it on
        previousMillis = currentMillis;   // Remember the time
        digitalWrite(ledPin, ledState);   // Update the actual LED
      }
    }
};

Flasher led1(14, 100, 400);
Flasher led2(15, 350, 350);
Flasher led3(16, 100, 400);
Flasher led4(17, 350, 350);

#define buzzer 13
#define greenled 20
#define redled 21
#define Password_Length 5

char  buffers[4][4] = {{'1', '2', '3', '4'}, {'6', '5', '4', '3'}, {'9', '8', '7', '6'}, {'1', '2', '5', '6'}}; // this is how to initialise a 2d array
unsigned long previousMillis[5]; //[x] = number of leds
byte i, x, y;
char Data[Password_Length]; // 6 is the number of chars it can hold + the null char = 7

byte data_count = 0;
bool Pass_is_good;
char customKey;
const byte ROWS = 4;
const byte COLS = 3;
char keys[ROWS][COLS] = {
  {'1', '2', '3'},
  {'4', '5', '6'},
  {'7', '8', '9'},
  {'*', '0', '#'}
};
byte rowPins[ROWS] = {2, 3, 4, 5}; //connect to the row pinouts of the keypad
byte colPins[COLS] = {6, 7, 8}; //connect to the column pinouts of the keypad
int ledservos[4] = {14, 15, 16, 17};
Keypad customKeypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS); //initialize an instance of class NewKeypad

void setup() {
  Serial.begin(9600);
  pinMode(buzzer, OUTPUT);
  pinMode(redled, OUTPUT);
  pinMode(greenled, OUTPUT);
  Serial.print("Enter Password");
  Serial.println();
}

void loop() {
  led1.Update();
  customKey = customKeypad.getKey();
  if (customKey) {
    // makes sure a key is actually pressed, equal to (customKey != NO_KEY)
    Data[data_count] = customKey; // store char into data array
    data_count++; // increment data array by 1 to store new char, also keep track of the number of chars entered
  }
  if (data_count == Password_Length - 1) {
    // if the array index is equal to the number of expected chars, compare data to master
    Serial.print("Password is ");
    for (byte i = 0; i < Password_Length; i++)
      Serial.print(Data[i]);
    for (x = 0; x < 4; x++) {
      //this loop for number of passwords in the array
      for (y = 0; y < 4; y ++) {
        //this loop for number of characters in each of the password array
        if (strcmp(Data[y], buffers[x][y]) != 0) {
          break;
        }
      }
      if (y == 4) {
        break;
      }
    }
    if (x < 4) {
      Serial.print(" Found at index ");
      Serial.println(x);
      switch (x) {
        case 0:
          led2.Update();
          digitalWrite(14, LOW);
          digitalWrite(16, LOW);
          digitalWrite(17, LOW);
          break;
        case 1:
          led3.Update();
          digitalWrite(15, LOW);
          digitalWrite(14, LOW);
          digitalWrite(17, LOW);
          break;
        case 2:
          led4.Update();
          digitalWrite(15, LOW);
          digitalWrite(14, LOW);
          digitalWrite(16, LOW);
          break;
        case 3:
          digitalWrite(15, LOW);
          digitalWrite(14, LOW);
          digitalWrite(16, LOW);
          digitalWrite(17, LOW);
          break;
      }
    }
    clearData();
  }
}

void clearData() {
  Serial.println();
  while (data_count != 0) {
    // This can be used for any array size,
    Data[data_count--] = 0; //clear array for new data
  }
}

```

Any idea why is this happening?

# Answer
> 1 votes
**EDIT**

Now that you added a link to the TimedBlink library I was able to go look at it. That is not a very well written library, and its documentation is **horrible**.

It seems that `blink(int,int)` starts a TimedBlink LED blinking, and blinkOff stops it. So you should not call `LEDx.blink(150,50)` on any of your LEDs until you want them to start blinking.

You need to refactor your code to only call `LEDx.blink(150,50)` on one LED at a time. You probably want your switch statement to call `LEDx.blink(150,50)` on the LED that you want to blink and ledOff() on the others.

---
Tags: arduino-uno
---


# Question
Title: Need little bit of help on testing I2C sketch
I have this code I got from YouTube for communicating between two Arduinos. By typing 'R' manually into the serial monitor of the 'master' Arduino, the 'slave' will print "Success". I'm trying all this for the basis of a project I'm starting.

After success with the code, I am now trying to make it automatic. I want the 'master' Arduino to print "R" itself and for the 'slave' to read this and print "Success". `println` doesn't work here, maybe it'll work if the slave code is changed? Both original codes are below, any ideas on how to do what I need?

Master:

```
#include <Wire.h>
char incomingByte;
int x = 0;

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

void loop()
{
  Wire.beginTransmission(9);
  if (Serial.available()) {
    while (Serial.available() > 0) {
      incomingByte = Serial.read();
      Wire.write(incomingByte);
      Serial.println(incomingByte);
      Wire.endTransmission();
  }
  }

}

```

Slave:

```
#include <Wire.h>

int x = 0;

void setup() {
  Wire.begin(9);
  Wire.onReceive(recieveEvent);
  Serial.begin(9600);
}

void recieveEvent(int bytes) {
  x = Wire.read();

}

void loop() {

  if (x == 'R'){
    Serial.println("Success");
    delay(100);
  }
}

```

# Answer
The I2C communication is not easy and there are many things that can go wrong. Two Arduino boards instead of one board are often used for the wrong reason in the first place.

Using a serial port is easier. The Arduino Leonardo has an extra hardware serial port, you could use the serial port to communicate between two Arduino boards. The Arduino Mega 2560 has three extra serial ports.

Sometimes two Arduino boards are used because multiple things have to be done at the same time.
When you use the Blink Without Delay example with `millis`, then the Arduino can do many things at the same time.

Sometimes two Arduino boards are used because there is some distance between the Arduino boards.
The I2C bus is a "bus", but that does not mean that you can use a long cable. You can go up to 20 inch (50 cm).

When two Arduino Uno boards are connected with the I2C bus, then three wires are needed:

1. GND to GND
2. SDA to SDA *(plus pullup resistor)*
3. SCL to SCL *(plus pullup resistor)*

For a small test with short jumper wires, it is possible to do that without pullup resistors. For the final project pullup resistors should be used for SDA and SCL, for example 4k7 or 10k.

The example below uses a flag in the Slave Arduino. That extra variable makes it easier.
In the Slave `receiveEvent` function, there is a extra check to check if exactly one byte is received. That extra check is not required, but it can be useful.

I show this example as something to start with, because there are too many bad examples for I2C between Master and Slave.

**Master**

```
#include <Wire.h>

byte dataTransmit;

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

void loop() {
  Wire.beginTransmission(9);   // sending to slave with i2c address 9
  Wire.write(dataTransmit);    // the data to send
  Wire.endTransmission();

  dataTransmit++;              // all numbers from 0 to 255

  delay(250);                  // 250ms delay, to send 4 times per second
}

```

**Slave**

```
#include <Wire.h>

volatile byte dataReceive;
volatile bool newData;    // a flag to indicate that new data has arrived

void setup() {
  Wire.begin(9);          // create i2c slave at i2c address 9
  Wire.onReceive(receiveEvent);
  Serial.begin(9600);
}

void loop() {
  if(newData) {           // is there new data?
    Serial.print("Received: ");
    Serial.println(int(dataReceive)); // convert to integer to print the number
    newData = false;      // reset flag
  }
}

void receiveEvent(int howMany) {
  if(howMany == 1) {      // extra check, to check if one byte is received
    dataReceive = Wire.read();
    newData = true;       // set flag, there is new data
  }
}

```
> 2 votes

# Answer
Here is my proposal to solve your issue:

* Use the second Serial communication line of the master by connecting Rx and Tx Pins of Serial2 (this done only on master, practically a shortcut between Rx and Tx on Master)
* Setup Serial2 if necessary: `HardwareSerial Serial2(2);` (that how it is necessary/done for my M5Stack)
* Define baud rate for Serial2: `Serial2.begin(9600);`
* Start your Automation by `Serial2.write("R\n");` at an appropriate place in your code
* Change conditions of `if(..)` and `while(..)` in your master's code from `Serial.available()` to `Serial2.available()`
* Change `incomingByte = Serial.read();` to `incomingByte =
Serial2.read();`

With that solution you can still see your start signal printed out on your Serial monitor via the first Serial communication line. The communication to the slave is still working over IC2, Serial2 is only the proposal for the automation solution on master. Looks complicated, but this is how I understood the question, of course you also could directly use `incomingByte="R\n";` to start your Automation and skip all that stuff with Serial2 :-)
> 0 votes

---
Tags: arduino-uno, i2c
---


title: What is /dev/tty.usbserial-1420

text:
# Question
Title: What is /dev/tty.usbserial-1420
I'm a complete newbie with Arduino. I've bought a couple of Nano clones from China. According to supplier description, it is Arduino Nano V3.0 ATMEGA328P ATMEGA328 CH340. Not sure why they list both 328 and 328P, but my struggle is to make it work anyway: IDE doesn't see it.

Power LED is on, L-LED is blinking regularly.

After some online reading, I conclude that the root cause may be in the USB-serial chip. My question is: if, when connecting this device to my Mac, I see a `/dev/tty.usbserial-1420` device appearing, does it mean that the USB-serial interface actually works correctly? Or does it not, and I should continue trying with installing some extra drivers etc.?

I am on Macbook Pro 2015, Mac OS 10.14.3. Many thanks in advance.

The error I am getting in IDE is:

> avrdude: stk500\_recv(): programmer is not responding
>
> avrdude: stk500\_getsync() attempt 1 of 10: not in sync: resp=0x00

Note: In a similar question the user didn't have the usbserial device in his /dev list.

# Answer
> 1 votes
These China clones are frequently shipped with no bootloader burned to the chip. There is a way to get it working but, you need a working Arduino or programmer to burn the bootloader. I have used an Arduino Uno to burn a bootloader on my nano. The Uno and nano were both purchased from the same seller, on the same order, from AliExpress. Here are the instructions that worked for me.

The instructions provide a link to download the Windows drivers so here’s a link to the macos drivers. CH341\_MAC.ZIP (CH340 uses CH341 drivers)

---
Tags: serial, arduino-nano, clones
---


# Question
Title: How to execute operation once till a condition then restart it from start
I am making a project using IR sensor,servomotor and Push button. I am not able write code for the logic as stated: it will execute the operation when it reads the digital value of IR high and rotates the servomotor till a threshold and then rotates the servo reverse on using push button.It will perform no actions till the push button is used altough IR sensor is reading value.Then it will again perform the same action after push button is used.

# Answer
> 1 votes
My suggestion is, even if it seems to be a simple example, to start with an analysis of what you really want to achieve. In this example I would try to start with an state diagramm. With this you could clarify simple questions, e.g. what happens if the IR goes low while the motor is turning. In my draft, the motor would keep running, but maybe the IR is for safety reason and you want to stop motor if something approaches. If that is your intention, you can easy add aditional transitions at all states to return to state 00.

Such an approach helps you in creating code easy to maintain and change to new requirements

After having your state diagramm finished it is often easy to start programming with switch/case sturctures for first learning experiences.

```
Switch(state) {
  case 00:
  // if IR set state = 10;
  break;
  case 10:
  // if button was pressed set state = 11
  break;
  case 11:
  // turn motor
  // if treshold set state = 12
  break;
.
.
.

}

```

---
Tags: programming, servo
---


title: Assigning formatted value to variable

text:
# Question
Title: Assigning formatted value to variable
Look at this snippet of code (from TinyGPS++ library):

```
Serial.print(gps.location.lat(), 6);

```

It prints the latitude location with 6 decimal points. I want, instead of printing that value, to have it assigned to a variable.

But i want it assigned just like above, with six decimal points. Is there a way to do this?

# Answer
Merely expanding on what ConnorWolf has said (which I saw yesterday), look at the link he gave you, it gives you a run down on the command you're after.

> The dtostrf() function returns the pointer to the converted string s.
>
> `char* dtostrf ( double __val,
>  signed char __width,
>  unsigned char __prec,
>  char * __s
>  )`
> The dtostrf() function converts the double value passed in val into an ASCII representationthat will be stored under s. The caller is responsible for providing sufficient storage in s.
>
> Conversion is done in the format "\[-\]d.ddd". The minimum field width of the output string (including the '.' and the possible sign for negative values) is given in width, and prec determines the number of digits after the decimal sign. width is signed value, negative for left adjustment.

From that, I wrote a short sketch that divides `millis()` by 1000 and saves this in a float, we then use this float as a source for `dtostrf()` to do it's work and store the result in a char array.

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

void loop(){
  char c[12];
  float f = millis()/1000.0;
  dtostrf(f,11,3,c);
  Serial.println(c);
  delay(111);
}

```

I have picked arbitrary values, you're going to have to do the calculations on the size of the array to create (don't forget the leading negative sign, the digits before the decimal, the decimal and your precision digits *as well as the null terminator!*
> 0 votes

# Answer
I had the same problem and I found answer

```
char latitude[20];
char longitude[20];

dtostrf(gps.location.lat(),8,6,latitude);
dtostrf(gps.location.lng(),8,6,longitude);

```
> -1 votes

---
Tags: variables
---


# Question
Title: Possible to connect 3 MPU9250 to Node MCU without multiplixer?
Is the idea of connecting AD0 pins of MPU9250 is still valid like the 2nd answer of this question? - How to change i2c address for mpu9250?

I have connected 2 sensor as test. SCL & SDA of both parallel with D1 & D2 of node mcu. Then connected AD0 of both sensors to different I/O pin of node mcu but it didnt work. What could be the solution?

Code to control 1 sensor:- It worked when I set AD0 to high and changed address to 0x69

```
#include "MPU9250.h"

// an MPU9250 object with the MPU-9250 sensor on I2C bus 0 with address 0x68
MPU9250 IMU(Wire,0x68);
int status;

void setup() {
  // serial to display data
  Serial.begin(115200);
  while(!Serial) {}

  // start communication with IMU
  status = IMU.begin();
  if (status < 0) {
    Serial.println("IMU initialization unsuccessful");
    Serial.println("Check IMU wiring or try cycling power");
    Serial.print("Status: ");
    Serial.println(status);
    while(1) {}
  }
}

void loop() {
  // read the sensor
  IMU.readSensor();
  // display the data
  Serial.print(IMU.getAccelX_mss(),6);
  Serial.print("\t");
  Serial.print(IMU.getAccelY_mss(),6);
  Serial.print("\t");
  Serial.print(IMU.getAccelZ_mss(),6);
  Serial.print("\t");
  Serial.print(IMU.getGyroX_rads(),6);
  Serial.print("\t");
  Serial.print(IMU.getGyroY_rads(),6);
  Serial.print("\t");
  Serial.print(IMU.getGyroZ_rads(),6);
  Serial.print("\t");
  Serial.print(IMU.getMagX_uT(),6);
  Serial.print("\t");
  Serial.print(IMU.getMagY_uT(),6);
  Serial.print("\t");
  Serial.print(IMU.getMagZ_uT(),6);
  Serial.print("\t");
  Serial.println(IMU.getTemperature_C(),6);
  delay(100);
}

```

Code to control 2 sensors:-

```
#include "MPU9250.h"

// an MPU9250 object with the MPU-9250 sensor on I2C bus 0 with address 0x68
MPU9250 IMU1(Wire,0x68);
MPU9250 IMU2(Wire,0x68);

int status;

void setup() {
  // serial to display data
  Serial.begin(115200);
  pinMode(D7, OUTPUT);
  pinMode(D8, OUTPUT);

}

void IMU_1() {
  digitalWrite(D7, LOW);
  digitalWrite(D8, HIGH);
  IMU1.begin();
  IMU1.readSensor();
  Serial.print("IMU 1 is active: "); Serial.print(IMU1.getAccelX_mss(),6);
  digitalWrite(D8, LOW);
}

void IMU_2() {
  digitalWrite(D7, HIGH);
  digitalWrite(D8, LOW);
  IMU2.begin();
  IMU2.readSensor();
  Serial.println("IMU 2 is active: "); Serial.print(IMU2.getAccelX_mss(),6);
  digitalWrite(D7, LOW);
}

void loop() {

IMU_1();
IMU_2();

  delay(500);

}

```

Result:- It Shows reading on one sensor but the 2nd sensor shows '0' every time.

What's the best way to use 3 I2C sensors when there is only 1 I2C bus?

# Answer
> 0 votes
It sounds like the MPU9250 has a pin, AD0, that lets you switch the device between 2 fixed I2C addresses.

That gives you an easy solution if you need to use 2 of them.

For more, the post you linked suggests keeping them all at the same AD0 state except the one you want to talk to. You’d switch that one’s AD0 pin to the other state, which would cause it’s I2C address, and then talk to it at that address, which would be unique on the I2C bus.

That approach should work, but it’s a bit of a hack.

You say "I have connected 2 sensor as test. SCL & SDA of both parallel with D1 & D2 of node mcu. Then connected AD0 of both sensors to different I/O pin of node mcu but it didn't work." What didn't work? What happens? What output do you get What pins on your mcu are connected to AD0 on your 3 different MPU9250 modules? Where is the code that manipulates the digital pins to select one and only one of your MPU9250 modules for reading?

You need to throughly explain your setup, including the different pin assignments and how they are supposed to work. Don't leave us to read your code and try and figure out your intentions.

Looking at your code it looks like you're using D7 and D8 on your mcu to try to control which MPU9250 is active. However i don't see any code the sets D7 and D8 as outputs.

Why don’t you want to use an I2C address mapping chip? They are readily available, and the ones I’ve seen would let you address up to 8 I2C devices that are hard-wired with the same address.

---
Tags: i2c, nodemcu, multiplexer, imu
---


# Question
Title: ESP8266 won't receive messages after a while
There are 5 ESP8266s being used. Three act as a middleman (in AP\_STA mode), one sends the message, and the last one receives the message after being passed over the middlemans (imagine it as a line, starting with nr. 1 in STA mode, sending the date to middleman 1. M1 sends it to M2, M2 sends it to M3, M3 sends it to the receiver, set in AP mode).

After like 10 min. of sending a message, one chip always stops. Stops as in, not receiving or sending the message. Every time a message is send, I use the command `Client21.flush()` (Client21 is just a name).

My idea is that I have to somehow also flush() after recieving a message, not just after sending one. Is there like a "receive buffer" that I can `flush()`, and how is it possible?

(no code provided)

**Update 1:** This is what the first middleman (chip no.3) printed in serial monitor when he "crashed":

```
Exception (29):
epc1=0x4000e1c3 epc2=0x00000000 epc3=0x00000000 excvaddr=0x00000018 depc=0x00000000

ctx: sys
sp: 3fffebc0 end: 3fffffb0 offset: 01a0

stack
3fffed60:  3fffc278 40101fe8 3fffc200 00000000
3fffed70:  3ffed93c 3fffb374 000000c0 401004e4
3fffed80:  40000f83 3fffb374 402384b0 401068b0
3fffed90:  402268ac 00000023 00000000 402268d1
3fffeda0:  000000c0 4021403b 00000018 3ffed6cc
3fffedb0:  00000000 00000000 00000020 40100f22
3fffedc0:  4021881e 4021873c 3ffef80c 40100f22
3fffedd0:  01004e43 4010000d 3ffee034 4021cb7d
3fffede0:  00000018 3ffed750 3ffed6cc 00000000
3fffedf0:  402188df 3ff20a00 3ffef80c 3ffe9be6
3fffee00:  3ffe9bcc 3fffee90 3fffee90 00000000
3fffee10:  4c4c4148 3331324f 40102200 3ffe9bcc
3fffee20:  3ffe9be6 0000002c 00000004 40100518
3fffee30:  3ffe9bd6 3ffefc74 402154a0 3ff20a00
3fffee40:  3ffef80c 3fffbfcc 00000015 40215373
3fffee50:  4000050c 3ffef45c 00000000 4021b377
3fffee60:  40106afd 00000030 00000011 ffffffff
3fffee70:  00000000 4bc6a7f0 7645a1ca 00000000
3fffee80:  00000000 00000000 4bc6a7f0 00000000
3fffee90:  4020cb8c 3ffe8f84 40106520 00190810
3fffeea0:  00000000 4bc6a7f0 3ffe8f84 40212cbc
3fffeeb0:  1cf15308 00000000 00000002 4020bad8
3fffeec0:  4021d149 ffffffa2 00000000 000001f4
3fffeed0:  40214baf 3ffe9bcc 3ffecd80 3ffef80c
3fffeee0:  00000000 3ffe9bd6 3ffe9bf0 3ffeeec4
3fffeef0:  4020cb8c 00000000 00000000 3ffe9bd6
3fffef00:  61c78017 000000c3 00000000 3ffefc74
3fffef10:  3ffe9bc0 00000000 00000002 4022463a
3fffef20:  3ffecd80 3ffe9bc0 3fffdcc0 3ffe9370
3fffef30:  3ffe9bdc 3ffefab4 00000040 3ffe9370
3fffef40:  00000040 3ffecd80 00000000 3ffe85e0
3fffef50:  40223f17 3fffdab0 00000000 40204ac7
3fffef60:  3ffe9370 40000f49 3fffdab0 40000f49
3fffef70:  40000e19 40001878 00000002 00000000
3fffef80:  3fffff10 aa55aa55 0000008f 40104424
3fffef90:  4010442a 00000002 00000000 056f21c7
3fffefa0:  4010000d 31c0f00e 8b4afbe9 f30f0180
3fffefb0:  00000000 3fffef4c 00000000 3fffff28
3fffefc0:  3fffffd0 00000000 00000000 feefeffe
3fffefd0:  feefeffe feefeffe feefeffe feefeffe
3fffefe0:  feefeffe feefeffe feefeffe feefeffe
3fffeff0:  feefeffe feefeffe feefeffe feefeffe
3ffff000:  feefeffe feefeffe feefeffe feefeffe
3ffff010:  feefeffe feefeffe feefeffe feefeffe
3ffff020:  feefeffe feefeffe feefeffe feefeffe
3ffff030:  feefeffe feefeffe feefeffe feefeffe
3ffff040:  feefeffe feefeffe feefeffe feefeffe
3ffff050:  feefeffe feefeffe feefeffe feefeffe
3ffff060:  feefeffe feefeffe feefeffe feefeffe
3ffff070:  feefeffe feefeffe feefeffe feefeffe
3ffff080:  feefeffe feefeffe feefeffe feefeffe
3ffff090:  feefeffe feefeffe feefeffe feefeffe
3ffff0a0:  feefeffe feefeffe feefeffe feefeffe
3ffff0b0:  feefeffe feefeffe feefeffe feefeffe
3ffff0c0:  feefeffe feefeffe feefeffe feefeffe
3ffff0d0:  feefeffe feefeffe feefeffe feefeffe
3ffff0e0:  feefeffe feefeffe feefeffe feefeffe
3ffff0f0:  feefeffe feefeffe feefeffe feefeffe
3ffff100:  feefeffe feefeffe feefeffe feefeffe
3ffff110:  feefeffe feefeffe feefeffe feefeffe
3ffff120:  feefeffe feefeffe feefeffe feefeffe
3ffff130:  feefeffe feefeffe feefeffe feefeffe
3ffff140:  feefeffe feefeffe feefeffe feefeffe
3ffff150:  feefeffe feefeffe feefeffe feefeffe
3ffff160:  feefeffe feefeffe feefeffe feefeffe
3ffff170:  feefeffe feefeffe feefeffe feefeffe
3ffff180:  feefeffe feefeffe feefeffe feefeffe
3ffff190:  feefeffe feefeffe feefeffe feefeffe
3ffff1a0:  feefeffe feefeffe feefeffe feefeffe
3ffff1b0:  feefeffe feefeffe feefeffe feefeffe
3ffff1c0:  feefeffe feefeffe feefeffe feefeffe
3ffff1d0:  feefeffe feefeffe feefeffe feefeffe
3ffff1e0:  feefeffe feefeffe feefeffe feefeffe
3ffff1f0:  feefeffe feefeffe feefeffe feefeffe
3ffff200:  feefeffe feefeffe feefeffe feefeffe
3ffff210:  feefeffe feefeffe feefeffe feefeffe
3ffff220:  feefeffe feefeffe feefeffe feefeffe
3ffff230:  feefeffe feefeffe feefeffe feefeffe
3ffff240:  feefeffe feefeffe feefeffe feefeffe
3ffff250:  feefeffe feefeffe feefeffe feefeffe
3ffff260:  feefeffe feefeffe feefeffe feefeffe
3ffff270:  feefeffe feefeffe feefeffe feefeffe
3ffff280:  feefeffe feefeffe feefeffe feefeffe
3ffff290:  feefeffe feefeffe feefeffe feefeffe
3ffff2a0:  feefeffe feefeffe feefeffe feefeffe
3ffff2b0:  feefeffe feefeffe feefeffe feefeffe
3ffff2c0:  feefeffe feefeffe feefeffe feefeffe
3ffff2d0:  feefeffe feefeffe feefeffe feefeffe
3ffff2e0:  feefeffe feefeffe feefeffe feefeffe
3ffff2f0:  feefeffe feefeffe feefeffe feefeffe
3ffff300:  feefeffe feefeffe feefeffe feefeffe
3ffff310:  feefeffe feefeffe feefeffe feefeffe
3ffff320:  feefeffe feefeffe feefeffe feefeffe
3ffff330:  feefeffe feefeffe feefeffe feefeffe
3ffff340:  feefeffe feefeffe feefeffe feefeffe
3ffff350:  feefeffe feefeffe feefeffe feefeffe
3ffff360:  feefeffe feefeffe feefeffe feefeffe
3ffff370:  feefeffe feefeffe feefeffe feefeffe
3ffff380:  feefeffe feefeffe feefeffe feefeffe
3ffff390:  feefeffe feefeffe feefeffe feefeffe
3ffff3a0:  feefeffe feefeffe feefeffe feefeffe
3ffff3b0:  feefeffe feefeffe feefeffe feefeffe
3ffff3c0:  feefeffe feefeffe feefeffe feefeffe
3ffff3d0:  feefeffe feefeffe feefeffe feefeffe
3ffff3e0:  feefeffe feefeffe feefeffe feefeffe
3ffff3f0:  feefeffe feefeffe feefeffe feefeffe
3ffff400:  feefeffe feefeffe feefeffe feefeffe
3ffff410:  feefeffe feefeffe feefeffe feefeffe
3ffff420:  feefeffe feefeffe feefeffe feefeffe
3ffff430:  feefeffe feefeffe feefeffe feefeffe
3ffff440:  feefeffe feefeffe feefeffe feefeffe
3ffff450:  feefeffe feefeffe feefeffe feefeffe
3ffff460:  feefeffe feefeffe feefeffe feefeffe
3ffff470:  feefeffe feefeffe feefeffe feefeffe
3ffff480:  feefeffe feefeffe feefeffe feefeffe
3ffff490:  feefeffe feefeffe feefeffe feefeffe
3ffff4a0:  feefeffe feefeffe feefeffe feefeffe
3ffff4b0:  feefeffe feefeffe feefeffe feefeffe
3ffff4c0:  feefeffe feefeffe feefeffe feefeffe
3ffff4d0:  feefeffe feefeffe feefeffe feefeffe
3ffff4e0:  feefeffe feefeffe feefeffe feefeffe
3ffff4f0:  feefeffe feefeffe feefeffe feefeffe
3ffff500:  feefeffe feefeffe feefeffe feefeffe
3ffff510:  feefeffe feefeffe feefeffe feefeffe
3ffff520:  feefeffe feefeffe feefeffe feefeffe
3ffff530:  feefeffe feefeffe feefeffe feefeffe
3ffff540:  feefeffe feefeffe feefeffe feefeffe
3ffff550:  feefeffe feefeffe feefeffe feefeffe
3ffff560:  feefeffe feefeffe feefeffe feefeffe
3ffff570:  feefeffe feefeffe feefeffe feefeffe
3ffff580:  feefeffe feefeffe feefeffe feefeffe
3ffff590:  feefeffe feefeffe feefeffe feefeffe
3ffff5a0:  feefeffe feefeffe feefeffe feefeffe
3ffff5b0:  feefeffe feefeffe feefeffe feefeffe
3ffff5c0:  feefeffe feefeffe feefeffe feefeffe
3ffff5d0:  feefeffe feefeffe feefeffe feefeffe
3ffff5e0:  feefeffe feefeffe feefeffe feefeffe
3ffff5f0:  feefeffe feefeffe feefeffe feefeffe
3ffff600:  feefeffe feefeffe feefeffe feefeffe
3ffff610:  feefeffe feefeffe feefeffe feefeffe
3ffff620:  feefeffe feefeffe feefeffe feefeffe
3ffff630:  feefeffe feefeffe feefeffe feefeffe
3ffff640:  feefeffe feefeffe feefeffe feefeffe
3ffff650:  feefeffe feefeffe feefeffe feefeffe
3ffff660:  feefeffe feefeffe feefeffe feefeffe
3ffff670:  feefeffe feefeffe feefeffe feefeffe
3ffff680:  feefeffe feefeffe feefeffe feefeffe
3ffff690:  feefeffe feefeffe feefeffe feefeffe
3ffff6a0:  feefeffe feefeffe feefeffe feefeffe
3ffff6b0:  feefeffe feefeffe feefeffe feefeffe
3ffff6c0:  feefeffe feefeffe feefeffe feefeffe
3ffff6d0:  feefeffe feefeffe feefeffe feefeffe
3ffff6e0:  feefeffe feefeffe feefeffe feefeffe
3ffff6f0:  feefeffe feefeffe feefeffe feefeffe
3ffff700:  feefeffe feefeffe feefeffe feefeffe
3ffff710:  feefeffe feefeffe feefeffe feefeffe
3ffff720:  feefeffe feefeffe feefeffe feefeffe
3ffff730:  feefeffe feefeffe feefeffe feefeffe
3ffff740:  feefeffe feefeffe feefeffe feefeffe
3ffff750:  feefeffe feefeffe feefeffe feefeffe
3ffff760:  feefeffe feefeffe feefeffe feefeffe
3ffff770:  feefeffe feefeffe feefeffe feefeffe
3ffff780:  feefeffe feefeffe feefeffe feefeffe
3ffff790:  feefeffe feefeffe feefeffe feefeffe
3ffff7a0:  feefeffe feefeffe feefeffe feefeffe
3ffff7b0:  feefeffe feefeffe feefeffe feefeffe
3ffff7c0:  feefeffe feefeffe feefeffe feefeffe
3ffff7d0:  feefeffe feefeffe feefeffe feefeffe
3ffff7e0:  feefeffe feefeffe feefeffe feefeffe
3ffff7f0:  feefeffe feefeffe feefeffe feefeffe
3ffff800:  feefeffe feefeffe feefeffe feefeffe
3ffff810:  feefeffe feefeffe feefeffe feefeffe
3ffff820:  feefeffe feefeffe feefeffe feefeffe
3ffff830:  feefeffe feefeffe feefeffe feefeffe
3ffff840:  feefeffe feefeffe feefeffe feefeffe
3ffff850:  feefeffe feefeffe feefeffe feefeffe
3ffff860:  feefeffe feefeffe feefeffe feefeffe
3ffff870:  feefeffe feefeffe feefeffe feefeffe
3ffff880:  feefeffe feefeffe feefeffe feefeffe
3ffff890:  feefeffe feefeffe feefeffe feefeffe
3ffff8a0:  feefeffe feefeffe feefeffe feefeffe
3ffff8b0:  feefeffe feefeffe feefeffe feefeffe
3ffff8c0:  feefeffe feefeffe feefeffe feefeffe
3ffff8d0:  feefeffe feefeffe feefeffe feefeffe
3ffff8e0:  feefeffe feefeffe feefeffe feefeffe
3ffff8f0:  feefeffe feefeffe feefeffe feefeffe
3ffff900:  feefeffe feefeffe feefeffe feefeffe
3ffff910:  feefeffe feefeffe feefeffe feefeffe
3ffff920:  feefeffe feefeffe feefeffe feefeffe
3ffff930:  feefeffe feefeffe feefeffe feefeffe
3ffff940:  feefeffe feefeffe feefeffe feefeffe
3ffff950:  feefeffe feefeffe feefeffe feefeffe
3ffff960:  feefeffe feefeffe feefeffe feefeffe
3ffff970:  feefeffe feefeffe feefeffe feefeffe
3ffff980:  feefeffe feefeffe feefeffe feefeffe
3ffff990:  feefeffe feefeffe feefeffe feefeffe
3ffff9a0:  feefeffe feefeffe feefeffe feefeffe
3ffff9b0:  feefeffe feefeffe feefeffe feefeffe
3ffff9c0:  feefeffe feefeffe feefeffe feefeffe
3ffff9d0:  feefeffe feefeffe feefeffe feefeffe
3ffff9e0:  feefeffe feefeffe feefeffe feefeffe
3ffff9f0:  feefeffe feefeffe feefeffe feefeffe
3ffffa00:  feefeffe feefeffe feefeffe feefeffe
3ffffa10:  feefeffe feefeffe feefeffe feefeffe
3ffffa20:  feefeffe feefeffe feefeffe feefeffe
3ffffa30:  feefeffe feefeffe feefeffe feefeffe
3ffffa40:  feefeffe feefeffe feefeffe feefeffe
3ffffa50:  feefeffe feefeffe feefeffe feefeffe
3ffffa60:  feefeffe feefeffe feefeffe feefeffe
3ffffa70:  feefeffe feefeffe feefeffe feefeffe
3ffffa80:  feefeffe feefeffe feefeffe feefeffe
3ffffa90:  feefeffe feefeffe feefeffe feefeffe
3ffffaa0:  feefeffe feefeffe feefeffe feefeffe
3ffffab0:  feefeffe feefeffe feefeffe feefeffe
3ffffac0:  feefeffe feefeffe feefeffe feefeffe
3ffffad0:  feefeffe feefeffe feefeffe feefeffe
3ffffae0:  feefeffe feefeffe feefeffe feefeffe
3ffffaf0:  feefeffe feefeffe feefeffe feefeffe
3ffffb00:  00000000 00000000 00000020 40100f22
3ffffb10:  3ffe92f0 40104304 3ffefd44 feefeffe
3ffffb20:  00000001 40103523 3ffed470 feefeffe
3ffffb30:  40103986 feefeffe feefeffe feefeffe
3ffffb40:  feefeffe feefeffe feefeffe feefeffe
3ffffb50:  4010346a 0000007f 7fffffff 00000000
3ffffb60:  0000007f feefeffe feefeffe feefeffe
3ffffb70:  401022eb 00080000 00000020 40100f22
3ffffb80:  00000000 00000000 00000000 4000050c
3ffffb90:  3fffc278 40101fe8 3fffc200 00000022
3ffffba0:  3ffffbb0 00000030 00000008 ffffffff
3ffffbb0:  00000000 00000000 0000001f 40104bfd
3ffffbc0:  4000050c 3ffedf28 00000002 00008e88
3ffffbd0:  40226856 00000030 00000008 ffffffff
3ffffbe0:  4021744b 00000000 00000001 3ffec950
3ffffbf0:  00000002 00000000 3fffab2a 00000001
3ffffc00:  00000003 00020021 00000001 3fff02f8
3ffffc10:  00000000 00000000 0000001f 40104bfd
3ffffc20:  4000050c 00ffffff 0000003f 3ffeca10
3ffffc30:  40000f83 00000030 00000008 ffffffff
3ffffc40:  4020b372 00000023 3fffdcc0 3fffb452
3ffffc50:  0000003a 000000f1 000000b9 00000003
3ffffc60:  00000001 fffffffd 00000001 3ffeee88
3ffffc70:  00000000 00000000 0000001f 40104bfd
3ffffc80:  4000050c 00000000 40225077 00000001
3ffffc90:  40000e86 00000030 0000001f fffffffe
3ffffca0:  40000e86 00000023 00000002 00000010
3ffffcb0:  00000010 00000000 3fffdbc0 3ffe93a8
3ffffcc0:  00000000 3fffc6fc 00000002 00000000
3ffffcd0:  3ffed440 00000001 00000000 00000030
3ffffce0:  00000000 3ffed470 20110486 00000000
3ffffcf0:  ffffffff 3fffc6fc 00000000 3ffefd44
3ffffd00:  3ffed440 00000001 00000000 00000030
3ffffd10:  3fffb41c 00000000 00000020 40100f22
3ffffd20:  3ffe92f0 4020b391 3ffeee88 3ffefc74
3ffffd30:  3fffb452 0000003a 3ffed470 40100f22
3ffffd40:  0000000c 00000000 00000020 3ffef2e1
3ffffd50:  000005e0 00000000 40103125 3ffed470
3ffffd60:  0000003c 00000000 3fffb452 00000100
3ffffd70:  0000001c 00000001 4010426a 3ffed470
3ffffd80:  3ffed440 4010431f 00000000 3ffed094
3ffffd90:  00000005 00000000 00000020 40100f22
3ffffda0:  3ffe92f5 4010431f 3ffecd80 40100f22
3ffffdb0:  40101c3d 3ffecd80 3ffefd44 40100f22
3ffffdc0:  00000023 61c7d6c4 3ffed750 40101e0e
3ffffdd0:  3ffe9b70 00000000 00000000 40100f22
3ffffde0:  00000023 61c7d6c4 4010224e 00000100
3ffffdf0:  7fffffff 3ffe9b70 3ffe9b70 00000001
3ffffe00:  00000001 00000040 3ffed750 40101e0e
3ffffe10:  3ffe9ba0 61c7d6c4 00000000 4000050c
3ffffe20:  3fffc278 40101fe8 3fffc200 00000022
3ffffe30:  3ffe9bac 3ffe9ba0 3ffe9ba0 00000001
3ffffe40:  40204bf3 00000030 00000010 ffffffff
3ffffe50:  40204bf3 00000001 00000001 00000000
3ffffe60:  00000000 00000000 00000000 fffffffe
3ffffe70:  ffffffff 3fffc6fc 00000001 00000064
3ffffe80:  3ffeebc8 3ffeeb98 3ffeec60 00000030
3ffffe90:  40204b9b 00000000 3ffeee68 00000000
3ffffea0:  00000000 00000000 00000000 fffffffe
3ffffeb0:  ffffffff 3fffc6fc 00000001 00000000
3ffffec0:  00000000 3fffdad0 3ffeed20 00000030
3ffffed0:  00000000 00000000 00000001 3ffeed18
3ffffee0:  00000000 3fffdad0 3ffeed20 00000030
3ffffef0:  ffffffff 3fffc6fc 00000001 3ffeed18
3fffff00:  00000000 3fffdad0 3ffeed20 00000030
3fffff10:  00000000 3fffdad0 3ffeed20 00000030
3fffff20:  3ffeeb98 3ffeebc8 3fffff60 401006dc
3fffff30:  3ffeeb98 3ffeec60 40204b0c 40204734
3fffff40:  4020158e 00000000 3ffeed18 40204f14
3fffff50:  3ffeeb98 3ffeebc8 3ffeed18 40202b38
3fffff60:  00000000 00000000 00000000 0106a8c0
3fffff70:  00000000 00000000 00000000 00000000
3fffff80:  00000000 3ffeec14 3ffeec60 40202a43
3fffff90:  40205198 6407a8c0 00000000 3ffeed20
3fffffa0:  00000000 00000000 00000001 40204b2d
stack

last failed alloc call: 3FFED93C(192)

 ets Jan  8 2013,rst cause:2, boot mode:(3,6)

load 0x4010f000, len 1384, room 16
tail 8
chksum 0x2d
csum 0x2d
vbb28d4a3
~ld

```

**Update 2:** It isn't only the first middleman (chip no.1) which crashes, now it happened to be the second one (chip no.4)

# Answer
> 0 votes
I've swapped through 25 ESP8266-12 chips hoping I just had bad luck when receiving these things. I also tried changing the baud-rate, which resulted into some chips becoming a so called "brick" (don't set the baud-rate to 9600, or else you will have to flash them again). Changing the power supply wasn't helpful too. I tried to see if this was caused by a memory leak, so I included the method `ESP.getFreeHeap()` and printed the results. They didn't seem suspicious at all.

What I think did the trick was to put a `delay(1)` at the end of the loop and reduce the time interval of messages being sent from five seconds to one. For now this seems stable and reliable.

**Update:** I changed the `delay(1)` to the method `yield()`. As the ESP8266 runs a lot of utility functions in the background (keeping WiFi connected, managing the TCP/IP stack, and performing other duties) blocking these functions from running can cause the ESP8266 to crash and reset itself. To avoid these mysterious resets, avoid long, blocking loops in your sketch. Blocking loops can be for example sending messages with the TCP/IP.

Still `delay(1)` also worked for me because delays don't "freeze" the chip completely. There are multiple layers, some which are reachable for us and some which are not (keeping WiFi connected etc.), so `delay()` has a similar outcome as `yield()`. You can even find `yield()` in the `delay()` method in wiring.c.

```
void delay(unsigned long ms)
{
    uint32_t start = micros();

    while (ms > 0) {
        yield();                       //<-------
        while ( ms > 0 && (micros() - start) >= 1000) {
            ms--;
            start += 1000;
        }
    }
}

```

But to set a `delay()` one needs to know how long it has to be so the duties get finished in time. `yield()` on the other hand pauses reading the script until the background duties are finished (that doesn't take too long).

Editing your script so that the chip keeps executing the `yield()` method often enough per run fixed it for me.

---
Tags: esp8266
---


title: Cascaded Control loop Arduino

text:
# Question
Title: Cascaded Control loop Arduino
I am trying to implement cascaded control system, with velocity inner loop and position outer loop.

Separately and without cascaded control, I have implemented position control and velocity control easily, thanks to the "pid library."

I have no idea how to convert position output from position pid to reference velocity.

Any help would be appreciated, since I am blank on this topic. Thanks and best regards

# Answer
This is not an Arduino specific topic, but here is just a pragmatic answer:

Use the output of the PID controller directly as your reference velocity, subtract your actual velocity and use it as input for the PID velocity. Units do not care in this case.

You have to make sure that the paramters of your PID position are well adjusted, this will set the problem with the units.

Here is an example to understand (only P gain considered):

If you want to drive from A to B with your car and the distance from A to B is 10 km, then your desired position is 10km and i would choose to drive about 100km/h. So in this example you start with a control deviation of 10km - 0km = 10km. If you choose a P gain of 10 the output of the PID will be 100, which is an ideal refernce Velocity, if velocity is given in km/h.

But if you are measuring your distance not in km but in m, the control deviation will be (10.000m - 0m = 10.000m), with a P gain of 10 you will end up with a refernce velocity of 100.000km/h, which is not an appropriate reference velocity in this case.

Now someone may object that in my example if you want do drive from A to C and C is 1.000km away, you will end up with an reference velocity of 10.000km/h, which is also not appropriate, but that is where the limitations in a PID controller are usefull, just set them for this example to 130km/h and you will end up stil with an appropriate reference velocity, and also your integrator part will not wind up endlessly.

You can look at I and D gain in a similar manner.
> 1 votes

---
Tags: arduino-mega, pid
---


title: Blinking LED's at changing rate

text:
# Question
Title: Blinking LED's at changing rate
I am trying to blink two LED's, starting at slow rate then increasing to fast s follows: 1 on, 1&2 on, 2 on, 1&2 on, 1 on, etc. The blinks go through the loop twice then speed up and repeat until both are on continuously. Then I want LED's 3 & 4 to come on. I got the 1 & 2 LED's to blink as I want but anything I put following my for / if loop goes into the loop. This works for blinking the 1 & 2 LED's:

```
int led1 = 9;
int led2 = 10;
int led3 = 11;
int led4 = 12;
int delay1 = 700;
int delayAmount1 = delay1 / 10;

void setup() {

pinMode(led1, OUTPUT);
pinMode(led2, OUTPUT);
pinMode(led3, OUTPUT);
pinMode(led4, OUTPUT);
}

void loop() {{
delay1 = delay1 - delayAmount1;

for (int i=0 ; i <2 ; i++) {

if (delay1 > 10)

digitalWrite(led1, HIGH); //yellow on (yellow)

delay(delay1);

digitalWrite(led2, HIGH); //red and yellow on (orange)

delay(delay1);

digitalWrite(led1, LOW); //yellow off (red)

delay(delay1);

digitalWrite(led1, HIGH); //yellow on (orange)

delay(delay1);

digitalWrite(led2, LOW); //red off (yellow)

digitalWrite (led1, LOW); //yellow off (all off)

}
}

// digitalWrite(led3, HIGH); //blue on

//delay(1000);

//digitalWrite(led4, HIGH); //green on

}

```

If I remove the // from

```
// digitalWrite(led3, HIGH); //blue on
//delay(1000);
//digitalWrite(led4, HIGH); //green on

```

they become part of the loop. Can someone tell me what I am doing wrong? Kind of new to this.

# Answer
> 0 votes
The `if(delay1>10)` does not have the conditional code in {}, so it should look like

```
if(delay1>10) {
//conditional code, what happens if statement == true
}

```

And if I understood your project and code correctly, when `delay1 <= 10` then you want the led3 and led4 to light up. So you want to add an optional `else{}` block. This optional block will be skipped, if the if statement is executed. If the if statement is not executed, because for example your delay1 is smaller or equal to 10, then the else block will be executed.

```
else{
//led3 and led4 light up
}

```

# Answer
> 0 votes
You have a number of code formatting problems, some aesthetic, and some structural.

You need to indent your code, and you need to use braces. If you don't format your code well you will have a very hard time figuring out what you are doing.

Here is an attempt to clean up your code:

void loop() {

```
delay1 = delay1 - delayAmount1;

for (int i=0 ; i <2 ; i++) {
    if (delay1 > 10) {
        digitalWrite(led1, HIGH); //yellow on (yellow)
        delay(delay1);
        digitalWrite(led2, HIGH); //red and yellow on (orange)
        delay(delay1);
        digitalWrite(led1, LOW); //yellow off (red)
        delay(delay1);
        digitalWrite(led1, HIGH); //yellow on (orange)
        delay(delay1);
        digitalWrite(led2, LOW); //red off (yellow)
        digitalWrite (led1, LOW); //yellow off (all off)
    }
}
// digitalWrite(led3, HIGH); //blue on
//delay(1000);
//digitalWrite(led4, HIGH); //green on

```

}

(I'm not sure what's supposed to be inside the if statement or not since you didn't have an opening brace.)

You also had 2 opening braces on your loop statement, which is very odd.

Note that using `delay()` to try to control more than one thing at a time is a bad idea. The delay() function causes your program to freeze everything until the delay is over. If you try to blink different LEDs at different rates, you can't. If you try to detect button presses while you are also blinking LEDs, you miss the button presses while your code is in a delay. There are lots of threads on the various Arduino boards on how to avoid using delay. Search on "Arduino blink no delay" to find the basics.

---
Tags: loop
---


title: Higher precision logarithms

text:
# Question
Title: Higher precision logarithms
I need to produce a log to base 10 with at least 4 decimal places. However, the log10 inbuilt function is giving the output with only two decimal places. What do I do? Is there a different function or a library that I can use?

# Answer
You should be able to get 6 or 7 decimal places out of the Arudino float type. Try using Serial.print for floats with a number of decimal places. Something like this:

```
float x = log10(3.141592658);
Serial.print(x, 6);

```
> 4 votes

---
Tags: arduino-ide, library
---


# Question
Title: Connecting DAC output from Arduino Due to another arduino
I have an Arduino Due and I want to connect the output from the DAC as an input to an Arduino Uno's analog input pin. From this link http://forum.arduino.cc/index.php?topic=164763.0, user DuaneB suggested that a resistor should be used in series with the DAC output to prevent an excessive flow of current that could damage the pin. But he was talking about this when the question was about powering a motor using the current generated from the DAC's voltage.

However, is this series resistor required when simply connecting the output of the pin to the input of another pin? I haven't seen any issue when connecting the output of my Raspberry Pi's GPIO to an arduino's input.

# Answer
> 0 votes
The inputs to Arduino pins are CMOS inputs, and present very high impedance. (There is a tiny capacitor on every CMOS input, and the only current into the input is the very small amount needed to charge that capacitor.)

You don't need resistors when connecting inputs and outputs (digital or analog) between Arduinos. Should be the same with Raspberry Pi GPIO lines, or any other CMOS devices.

---
Tags: current, resistor, digital-analog-conversion
---


title: nRF24L01+ Unable to set address

text:
# Question
Title: nRF24L01+ Unable to set address
I'm trying to communicate between Arduino Nano and Arduino Uno using nRF24L01+.

I tried using RF24 by ManiacBug and TMRH20, but when I open the serial monitor after uploading the Example Programs Getting Started from ManiacBug and pingpair Program from TMRH20, it does not change its address.

The addresses for reading and writing I'm using are 0xF0F0F0F0E1LL and 0xF0F0F0F0D2LL, but the response I'm receiving is as follows:

I check all the connection and tried different examples available on the internet, but nothing worked at all.

# Answer
> 1 votes
You can set addresses using SPI commands. For example a 5-byte transmitter address could be written as (MSB first):

```
  digitalWrite(CSN_pin, LOW);
  SPI.transfer(0x30); // write TX_ADDR register
  SPI.transfer(tx_addr[0]);
  SPI.transfer(tx_addr[1]);
  SPI.transfer(tx_addr[2]);
  SPI.transfer(tx_addr[3]);
  SPI.transfer(tx_addr[4]);
  digitalWrite(CSN_pin, HIGH);

```

where `tx_addr` is an array of 5 bytes. Similarly you can write to the RX\_ADDR registers, see the nRF24L01+ datasheet, section 9 for the register map.

Furthermore, the following code allows you to read the TX\_ADDR register:

```
  digitalWrite(CSN_pin, LOW);
  SPI.transfer(0x10); // read TX_ADDR register
  data_out[0] = SPI.transfer(0x0);
  data_out[1] = SPI.transfer(0x0);
  data_out[2] = SPI.transfer(0x0);
  data_out[3] = SPI.transfer(0x0);
  data_out[4] = SPI.transfer(0x0);
  digitalWrite(CSN_pin, HIGH);

  Serial.print("TX_ADDR=");
  Serial.print(data_out[0]);
  Serial.print(data_out[1]);
  Serial.print(data_out[2]);
  Serial.print(data_out[3]);
  Serial.println(data_out[4]);

```

---
Tags: arduino-uno, arduino-nano, communication, nrf24l01+, wireless
---


# Question
Title: Arduino acts odd when disconnected from computer
I'm building an self-navigating robot with an arduino, an ultrasonic sensor, and two DC motors. I'm currently within the process of coding the robot but I've discovered I have an unusual problem; whenever I run the project via the USB cable operations run fine, however once I take the cable out and run the system on batteries alone performance diminishes.

I have checked the code thoroughly, however I don't understand how this could be an issue that's coding related. I also (as part of the testing) built a basic program which only operated the motors, and was able to run this via USB and via batteries alone with no difference in performance.

So what possible reasons could there be for a drop in performance? I have included a link to a youtube video I had taken of it earlier below to maybe give a better understanding of how performance diminishes:

https://youtu.be/Tp5LtOKBKHw

(Also it could be important to note if I take the cable out while motors are currently moving performance stays at where it should be)

Thanks!

# Answer
> 1 votes
What seems is that you are facing an power shortage while working with on board power supply. While running DC motors and Arduino on same battery set your Arduino is not getting enough power.

Try switching to a better power supply which can maintain a constant EMF, as eventually you'll always run out of power. Try an adaptor to use wall socket current. This way you'll not lose any functionality of Arduino project.

---
Tags: arduino-uno, motor, robotics
---


# Question
Title: HC-05 with ELM327 mini OBD2 Bluetooth adapter connection problem
I am using Arduino Uno and HC05 Zs-040 Bluetooth module to establish a connection with ELM327 mini OBDII Bluetooth adaptor.

I have tried more than 15 different sequences of AT commands and most of them works successfully and HC05 reply with "ok" with no errors.

When I switch off the power from the HC05 and reconnect it again to connect automatically to the MAC address stored in it during configuration, the HC05 connects to the ELM327 OBDII adaptor for a time interval ranges from 2 to 5 seconds then the connection is lost.

I was able to notice that from the LED blinking on the HC05. This process of connection and disconnection is repeated automatically and the LED on the HC05 blinks in different patterns.

Also, I was able to connect to the ELM327 OBDII adaptor using a python script and it connects to it (I did that at the same time when the HC05 was trying to connect to OBDII adaptor which confirms that the connection between HC05 and the adaptor was not established).

In addition, I was able to connect to ELM 327 adaptor using Torque application and Bluetooth terminal application and both work fine.

Can anyone help me figuring out why does the connection is lost as soon as it is established?

# Answer
> 1 votes
I faced a similar problem when working with HC-05 module with an Android terminal application and connection was lost after some time and many it was just not able to connect. Upon some hit and trials I found that it was just an power issue with HC-05 and as soon as I tried it out by reducing load on HC-05 by connecting it alone on 5V supply from Arduino and switching others to a 3V supply it worked like butter and I didn't faced any problem till now.

This worked for me try this out.

---
Tags: hc-05, adapter
---


# Question
Title: I want to reset a variable after each 1 second on an Arduino
I want to reset this counter variable which I created after each 1 second, but I don't want to disturb the `if` statement.

Here is the code:

```
int button=A0;
int val;
int count=0;
int presss;

void setup() {
  pinMode(button,INPUT);
  Serial.begin(9600);
}

void loop() {
  val=analogRead(button);
  if(val>1000){
   presss=count++;
   delay(200);
 }
  Serial.println(presss);
  delay(1000);
 }

```

# Answer
> 2 votes
I would do it the following way:

* Use a variable declared as: `unsigned long time_passed;`
* In the setup() section I would add the line `time_passed = millis();`
* In the loop() section I would add the if condition:

`if(millis()-time_passed > 1000) {
 time_passed = millis();
 presss = 0;
 }`

I think this is still not working properly with your example, I recommend to make two changes in your code:

* you have a delay of 1000 implemented, which means the cycle time of your loop is minimum 1000ms,that means you are never able to count more than 1, since your counter is resetted every loop
* I cannot understand how `presss = count++;` should work. For proper counting I would suggest to do it this way: `presss = presss + 1;`
* Note: max. value of your counter would be 5, since the delay in the if Statement will enable maximum 5 detections of your button within 1000ms

# Answer
> 0 votes
You could do something like this:

```
void loop() {
  for (int i = 0; i < 5; i++) {
    val = analogRead(button);
    if (val > 1000) count++;
    delay(200);
  }
  Serial.println(count);
  count = 0;
 }

```

This will sample the button five times and count the number of times the value is larger than 1000, with a 200 ms delay between each read. This give approx. 1 s.

But this might not be the logic you are looking for.

Cheers!

# Answer
> 0 votes
If I understood the project, you want to count how many button clicks you did in one second, so I've adjusted your code a little bit. If you don't want your program to do something after a certain amount of time, but don't want it to wait don't use `delay(ms)` use `millis()` instead (see https://www.arduino.cc/reference/en/language/functions/time/millis/ )

```
int button=A0;
int val;
int presss=0;

int millisBegin = 0;
int millisNow;
int millisBorder = 1000;

void setup()
{
  pinMode(button,INPUT);
  Serial.begin(9600);
}

void loop()
{
  val=digitalRead(button);

  if(val==HIGH)
  {
    presss++;     //If the button is pressed it will count + 1

    while(val==HIGH)
    {
      val=digitalRead(button); //It will wait till you release the button here
    }
  }

  Serial.println(presss);

  millisNow = millis();

  if(millisNow-millisBegin >= millisBorder)
  {
    presss = 0;
    millisBegin = millisNow;
    Serial.println("~1 second passed");
  }
}

```

I checked it and it worked for me (I changed the `if(val>1000)` to `if(val==HIGH)`, otherwise it might not always detect a button press

---
Tags: arduino-uno, variables
---


title: A waterproof Chlorine Sensor

text:
# Question
Title: A waterproof Chlorine Sensor
Does anyone know where I can find a Chlorine Sensor to use with the Arduino? It would need to be water proof. I've googled, but I couldn't find anything.

**EDIT** Requirements: relatively inexpensive (under $100us), works with Arduino, waterproof and used to detect chlorine in water.

# Answer
> 3 votes
Your best bet would probably be to interface with a colorimeter. There is a tutorial for an open source colorimeter here:

http://www.appropedia.org/Open-source\_colorimeter

IORodeo also sells a shield:

http://www.iorodeo.com/colorimeter

Vernier sells a colorimeter that may be suitable for your project & Sparkfun sells a shield to interface with Vernier sensors.

If a colorimeter doesn't work you would have to use an electrode, which is pretty expensive and has a shelf life.

# Answer
> 0 votes
Maybe measure conductivity instead? I think, in freshwater pools, one of the active parts of working chlorine is an OCL ion - which I guess is conductive.

---
Tags: sensors
---


# Question
Title: Parsing Data and Comparing two string in arduino
I am working on my final assignment. The problem is I want to make a prototype tool, with 2 string compare. If I send data "OK DISC DISCLOSED: 341513DB689AOK RSSI: -056 OK NAME: CarBT1 OK DISCE" will be parsed and bring up data "CarBT1 OK DISCE" if the data is correct then the LED will turn on, but my program isn't working? does anyone know the problem?

```
String dataIn;
String dt[10];
int i;
boolean parsing=false;
const int pinLED = 8;
String readString;

void setup (){
  Serial.begin(9600);
  pinMode(pinLED, OUTPUT);
  Serial.print("Sketch:   ");   Serial.println(__FILE__);
  Serial.print("Uploaded: ");   Serial.println(__DATE__);
  Serial.println(" ");
  while(!Serial){
    ;
  }
}

void loop (){
  if(Serial.available()>0) {
  char inChar = (char)Serial.read();
  dataIn += inChar;
  if (inChar == '\n'){
  parsing = true;
  }
}
if(parsing){
  parsingData();
  parsing=false;
  dataIn="";
}
while(Serial.available()){
  delay(3);
  char c =  Serial.read();
  readString += c;
}
readString.trim();
  if(readString.length()>0){
    if(readString == "CarBT1 OK+DISCE"){
      digitalWrite(pinLED, HIGH);
      Serial.println("Switching On");
   }
  if(readString == "off"){
      digitalWrite(pinLED, LOW);
      Serial.println("Switching Off");
   }
readString = "";
 }
}

void parsingData(){
int j=0;
Serial.print("data masuk : ");
Serial.print(dataIn);
Serial.print("\n");
dt[j]="";
for(i=1;i<dataIn.length();i++){
  if ((dataIn[i] == ':') || (dataIn[i] == ':')){
  j++;
  dt[j]="";
}
  else{
  dt[j] = dt[j] + dataIn[i];
  }
 }
}
Serial.print("data 1 : ");
Serial.print(dt[0]);
Serial.print("\n");
Serial.print("data 2 : ");
Serial.print(dt[1]);
Serial.print("\n");
Serial.print("data 3 : ");
Serial.print(dt[2]);
Serial.print("\n\n");
Serial.print("data 4 : ");
Serial.print(dt[3]);
Serial.print("\n\n");
}

```

# Answer
I think that the biggest problem that you are encountering is that reading a line from serial is not as straightforward as you would like. I don't have a quick and easy solution for you, but there is much on this issue that you can look at.

You have two serial read while loops. The first exits as soon as there are no characters to read (even though some may be on the way). When "\n" is read, you set parsing but it does not mean that \n is removed from dataIn.

The second serial read while loop is using a delay(3) after detecting that a character is available, but that character could have arrived after the first read and be the only character in the buffer, for example.

I suspect that the reason that your String comparison does not work is simply because the Strings are not equal.

Your String looks like something read from an HM-10/11 or something similar. I have had some success reading those transmissions by doing the following:

Make sure the serial buffer is empty. When a character is available, read it into your building String, but continue looking for characters that are available for a set amount of time (maybe a couple of seconds). Continue looking for characters until the time has elapsed and not as soon as there are no characters available (because more may be coming). Alternatively, keep building the string until you recognize the "DISCE" marking the end of that transmission.

A problem, however, is that, in my experience, if it is a very long line (that can occur when there are many devices out there), you will never get that "DISCE". I assumed that this was a firmware issue.

Hope it helps.
> 1 votes

---
Tags: programming, string
---


# Question
Title: Sending data to UART using Atmel Studio with Attiny84
I want to send data to TFDI. It can be `hello world` or any value of variable. But I can't do. I haven't found example code on the internet. Some examples doesn't work. I am using Atmel Studio.

# Answer
> 1 votes
The ATTiny84 does not have a hardware UART peripheral. Instead it has a USI (universal serial interface), which does not have all the capabilities needed for UART ("serial") interface.

You don't need to burn the Arduino bootloader to use libraries, that were written for the Arduino IDE. You only might need some of the definitions, which you can get by including the arduino.h file.

I think your best bet is to use existing libraries, like the SoftwareSerial library. There are also lots more libraries, that provide bit banged serial interfaces. You can also get them running in Atmel Studio, by including the source files. This is the easy way.

If you want to go the hard way, you might be able to program a hybrid software/hardware UART interface by utilizing some functions of the USI. In a search I found this site, which is about implementing UART with the USI. They also link to Atmel's Application Note AVR307, which is a good source for understanding this. From this starting point you might also find a ready to go implementation for the USI. If not, you will have to do the work yourself.

---
Tags: serial, uart, atmel-studio
---


# Question
Title: Data received by Arduino from ESP8266 01 Module is not complete
I am sending some data from ESP8266 01 module to Arduino. But the data received by Arduino is not complete.

Below are the images of the output from ESP8266 01 module and Arduino.

Here is the ESP8266 01 Module code:-

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

char c,e;                       //stores the bytes coming from the server
int DEBUG = 0;

int co=0;                       //control the sending of Alert

const char* ssid     = "ssid";            //your SSID of WIFI
const char* password = "password";       // password of Wifi
//--------------------------------------------

const char* host = "api.thingspeak.com";

void setup() {
  //dht.begin();
    Serial.begin(115200);
    delay(10);
  // We start by connecting to a WiFi network

    if (DEBUG){
      Serial.println();
      Serial.println();
      Serial.print("Connecting to ");
      Serial.println(ssid);
  }

  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    if (DEBUG){
      Serial.print(".");
    }
  }

    if (DEBUG){
      Serial.println("");
      Serial.println("WiFi connected");
      Serial.println("IP address: ");
      Serial.println(WiFi.localIP());
    }
}

int value = 0;

void loop() {
  delay(1000);
  ++value;

  if (DEBUG){
    Serial.print("connecting to ");
    Serial.println(host);
  }

  // Use WiFiClient class to create TCP connections
  WiFiClient client;
  const int httpPort = 80;
  if (!client.connect(host, httpPort)) {
    Serial.println("connection failed");
    return;
  }

  if (DEBUG){
    Serial.print("Requesting URL: ");
  }

//============================================================================================================
//                                Sending Control info to arduino Serially
//============================================================================================================
  // This will send the request to the server
  client.print(String("GET ")  + "/channels/******/feeds.json?api_key=*****************&results=2 HTTP/1.1\r\n" +
               "Host: " + host + "\r\n" +
               "Connection: close\r\n\r\n");         // get information about device control
  unsigned long timeout = millis();
  while (client.available() == 0) {
    if (millis() - timeout > 5000) {
      Serial.println(">>> Client Timeout !");
      client.stop();
      return;
    }
  }

  // Read all the lines of the reply from server and print them to Serial
  while(client.available()){
    String line = client.readStringUntil('\r');
    Serial.print(line);                         // received by arduino serially
  }
 //Serial.println("closing connection");
}

```

Here is the Arduino code:-

```
    //This sketch in the implementation of home automation
#include <SoftwareSerial.h>// import the serial library
#include<String.h>
//-----------------------------------------
//    pin definations
//-----------------------------------------
#define Light 2              // pin 2 to control light
#define fan 3                 // pin 3 to control fan
//------------------------------------------
//       variables
//------------------------------------------
char e;
int p=0,q=0;        //these variables prevent switching ON/OFF of already turned ON/OFF devices
int DEBUG = 1;

SoftwareSerial home_monitor(10, 11); // RX, TX

char control_data; // the data transmitted over Bluetooth

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

void loop() {
  // put your main code here, to run repeatedly:
  if (home_monitor.available()){
     control_data=home_monitor.read();   // getting control information from ESP8266 serially
     e=control_data;
     if (DEBUG){
      Serial.print(control_data);
     }
     //Serial.print(e);
 //============================================================================================================
 //                                        Device Control
 //============================================================================================================

 // Performing required operations based on the value of channel
    //-------------------------------------------------------------
    //                        LIGHT
    //-------------------------------------------------------------

    if(e=='0'&&p==0)         //Light ON
    {
      if (DEBUG){
        Serial.println("Light ON");
      }
      digitalWrite(Light,LOW);
      p=1;
    }
     if(e=='1'&&p==1)        //Light off
    {
      if (DEBUG){
        Serial.println("Light OFF");
      }
      digitalWrite(Light,HIGH);
      p=0;
    }

    //-------------------------------------------------------------
    //                        Heater
    //-------------------------------------------------------------

    if(e=='2'&&q==0)
    {
      if (DEBUG){
        Serial.println("Fan ON");
      }
      digitalWrite(fan,LOW);
      q=1;
    }
    if(e=='3'&&q==1)
    {
      if (DEBUG){
        Serial.println("Fan OFF");
      }
      digitalWrite(fan,HIGH);
      q=0;
    }
  }
}

```

# Answer
You are using `client.print()` and the Arduino uses `home_monitor.read()` to receive the message (if I understood correctly). What I did in my sketch was change the `home_monitor.read()` to `home_monitor.readStringUntil('\n')`.

Also before your ESP sends a message via `client.print()` it is recommended to run the `client.flush()` method so it waits until all outgoing characters in the buffer have been sent, before sending the next.

When using the ESP you should be aware of the useful `yield()` method (call it at the end of the loop). This let's the ESP get his background duties finished before going on (not calling this method may result in some issues.
> 0 votes

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


title: L293D with arduino's 5V

text:
# Question
Title: L293D with arduino's 5V
I am trying to use `L293D` with relay to power a 12V DC motor. Can I use arduino's 5V to provide L293D inputs 4 and 8 such as in the drawing? Or do I need to use a separate source, e.g. a power module?

# Answer
it looks like that motor controller chip has separate logic level and motor power inputs.

VCC1, at pin 16, is a low current logic level power input. You should be able to drive that from the Arduino's power supply.

VCC2, at pin 8 is the motor power input. You should **NOT** drive that from your Arduino's power supply. You should have a separate power supply for that (+5V with enough current for all the motors you are powering - 600mA is the max that chip can drive for a single motor, so a 1A power supply for VCC2 would be fine.

It looks like you are feeding the Arduino's +5V line into VCC2. **DON'T DO THAT.**
> 0 votes

---
Tags: motor, relay, l293d
---