body:
Can anyone help me with the following codes? I have attached sensors to detect either plastic or metal materials. If the sensor detected a metal, the first servo will rotate at least 90 degrees. If not, it will not rotate. If its a plastic material, the other servo will do the same. Kindly consider the following codes.
```
// Include Libraries
#include "Arduino.h"
#include "Button.h"
// Pin Definitions
#define REFLECTIVEIR_PIN_COLL  A1
#define REFLECTIVEIR_PIN_COLL_M  A3
// object initialization
Button ReflectiveIR(REFLECTIVEIR_PIN_COLL);
Button ReflectiveIR_M(REFLECTIVEIR_PIN_COLL_M);
// define vars for testing menu
const int timeout = 10000;       //define timeout of 10 sec
char menuOption = 0;
long time0;

#include <Servo.h>
#define redpin 2
#define bluepin 3
#define greenpin 4
#define redpin_M 5
#define bluepin_M 6
#define greenpin_M 7
int metalsensor = A0;
int metalsensor_M = A2;
int plasticsensor = A4;
//int anothersensor = A2;

Servo myservo;  // create servo object to control a servo
Servo myservo_M;  // create servo object to control a servo
// twelve servo objects can be created on most boards

int pos = 165;    // variable to store the servo position
int pos_M = 158;    // variable to store the servo position

void setup() {
  myservo.attach(9);  // attaches the servo on pin 9 to the servo object
  myservo_M.attach(10);  // attaches the servo on pin 9 to the servo object
  pinMode(redpin, OUTPUT);
  pinMode(bluepin, OUTPUT);
  pinMode(greenpin, OUTPUT);
  //metal sensor
  pinMode(redpin_M, OUTPUT);
  pinMode(bluepin_M, OUTPUT);
  pinMode(greenpin_M, OUTPUT);

  pinMode(metalsensor, INPUT_PULLUP);
  pinMode(metalsensor_M, INPUT_PULLUP);
  pinMode(plasticsensor, INPUT_PULLUP);
  //  pinMode(anothersensor, INPUT_PULLUP);
  Serial.begin(9600);
  analogWrite(redpin, 255);
  analogWrite(bluepin, 255);
  analogWrite(greenpin, 255);
  analogWrite(redpin_M, 255);
  analogWrite(bluepin_M, 255);
  analogWrite(greenpin_M, 255);
  //ReflectiveIR.init();
  //ReflectiveIR_M.init();
}

void loop() {

  int sensor_read_m = digitalRead(metalsensor);
  int sensor_read_mm = digitalRead(metalsensor_M);
  int sensor_read = digitalRead(plasticsensor);
  Serial.println("metal sensor");
  Serial.println(sensor_read_m);
  Serial.println(sensor_read_mm);
  Serial.println("plastic sensor");
  Serial.println(sensor_read);

  bool ReflectiveIR_Val = ReflectiveIR.read();
  bool ReflectiveIR_Val_M = ReflectiveIR_M.read();
  //Plastic bin
  if ((sensor_read == 0) && (sensor_read_m != 1)) {
    for (pos = 160; pos >= 90; pos -= 1) { // goes from 0 degrees to 180 degrees
      // in steps of 1 degree
      myservo.write(pos);              // tell servo to go to position in variable 'pos'
      delay(1);                       // waits 15ms for the servo to reach the position
    }
    analogWrite(redpin, 255);
    analogWrite(bluepin, 0);
    analogWrite(greenpin, 255);
    delay(2500);
    for (pos = 90; pos <= 160; pos += 1) { // goes from 180 degrees to 0 degrees
      myservo.write(pos);              // tell servo to go to position in variable 'pos'
      delay(1);                       // waits 15ms for the servo to reach the position

    }
    analogWrite(redpin, 0);
    analogWrite(bluepin, 0);
    analogWrite(greenpin, 0);

  }

  else if (ReflectiveIR_Val == 1) { //checking the volume of the trash
    analogWrite(redpin, 0);
    analogWrite(bluepin, 255);
    analogWrite(greenpin, 255);

  }

  else {
    // goes from 180 degrees to 0 degrees
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    // waits 15ms for the servo to reach the position

    analogWrite(redpin, 255);
    analogWrite(bluepin, 255);
    analogWrite(greenpin, 255);

  }

  //metal sensor

  if (sensor_read_mm == 1) {
    for (pos_M = 160; pos_M >= 90; pos_M -= 1) { // goes from 0 degrees to 180 degrees
      // in steps of 1 degree
      myservo_M.write(pos_M);              // tell servo to go to position in variable 'pos'
      delay(1);                       // waits 15ms for the servo to reach the position
    }
    analogWrite(redpin_M, 255);
    analogWrite(bluepin_M, 0);
    analogWrite(greenpin_M, 255);
    delay(2500);
    for (pos_M = 90; pos_M <= 160; pos_M += 1) { // goes from 180 degrees to 0 degrees
      myservo_M.write(pos_M);              // tell servo to go to position in variable 'pos'
      delay(1);                       // waits 15ms for the servo to reach the position

    }
    analogWrite(redpin_M, 0);
    analogWrite(bluepin_M, 0);
    analogWrite(greenpin_M, 0);

  }

  else if (ReflectiveIR_Val_M == 1) {
    analogWrite(redpin_M, 0);
    analogWrite(bluepin_M, 255);
    analogWrite(greenpin_M, 255);

  }

  else {
    // goes from 180 degrees to 0 degrees
    myservo_M.write(pos_M);              // tell servo to go to position in variable 'pos'
    // waits 15ms for the servo to reach the position

    analogWrite(redpin_M, 255);
    analogWrite(bluepin_M, 255);
    analogWrite(greenpin_M, 255);

  }

}
```

Thank you for the help.

title: Two Servo motors don't work as required (Arduino Mega 2560)

Answers: 0


body:
I'm using nodemcu and neo6m gps module. I can't send data to firebase. As a library using tinygps++. Can anyone please help me how can i pass data to firebase.

    #include <ESP8266WiFi.h>
    #include <FirebaseArduino.h>
    #include "TinyGPS++.h"
    #include "SoftwareSerial.h"

    // Set these to run example.
    #define FIREBASE_HOST "vessel-monitoring-a21f4.firebaseio.com"
    #define FIREBASE_AUTH "EYUZc64JyLMR5cbJc99nZzjah8uwEDxSp3m93Lvr"
    #define WIFI_SSID "H17"
    #define WIFI_PASSWORD "pass@router"

    //GPS
    SoftwareSerial serial_connection(4, 0); //tx,rx
    TinyGPSPlus gps;// GPS object to process the NMEA data

    float latt, lngg;

    void setup() {
      Serial.begin(9600);
      serial_connection.begin(9600);
      // connect to wifi.
      WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
      Serial.print("connecting");
      while (WiFi.status() != WL_CONNECTED) {
        Serial.print(".");
        delay(500);
      }
      Serial.println();
      Serial.print("connected: ");
      Serial.println(WiFi.localIP());
      Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH);
    }

    void loop() {
        while (serial_connection.available()) {
          gps.encode(serial_connection.read());
        }
        if (gps.location.isUpdated()) {
          latt = gps.location.lat();
          lngg = gps.location.lng();
          Serial.println(latt, 6);
          Serial.println(lngg, 6);
          delay(1000);
        }
        char location_str[25]={0};
        sprintf(location_str, "%f, %f", latt, lngg);
        String name = Firebase.push("location", location_str);
        if (Firebase.failed()) {
          Serial.print("setting /location failed:");
          Serial.println(Firebase.error());
          return;
        }
        delay(1000);
    }

title: How to send NEO6M gps data to firebase?

Answers: 0


body:
How to extract fingerprint template from Arduino Fingerprint Sensor and store it to SD card module using adafruit library and then search/import it from SD card module when tapping the fingerprint?

Can anyone give me hope to this project I am starting to feel stressed and depressed.

I'm using Arduino R307 and AS601 fingerprint modules.

here is the code:
```c++
    #include <SPI.h>
    #include <SD.h>
    #include <SoftwareSerial.h>
    #include <Adafruit_Fingerprint.h>

    SoftwareSerial mySerial(2, 3);

    Adafruit_Fingerprint finger = Adafruit_Fingerprint(&mySerial);

    uint8_t id;
    String userName;
    uint8_t isProfessor;
    char *myFileName = "acct.txt";
    File myFile;

    void setup()
    {
      Serial.begin(9600);
      while (!Serial);  // For Yun/Leo/Micro/Zero/...
      delay(100);
      Serial.println("\n\nAdafruit Fingerprint sensor enrollment");

      Serial.print("Initializing SD card...");
      if (!SD.begin(4)) {
        Serial.print("initialization failed!");
        while (1);
      }
      Serial.print("initialization done.");

      // set the data rate for the sensor serial port
      finger.begin(57600);

      if (finger.verifyPassword()) {
        Serial.println("Found fingerprint sensor!");
      } else {
        Serial.println("Did not find fingerprint sensor :(");
        while (1) {
          delay(1);
        }
      }
    }

    uint8_t readnumber(void) {
      uint8_t num = 0;

      while (num == 0) {
        while (! Serial.available());
        num = Serial.parseInt();
      }
      return num;
    }

    void loop()                     // run over and over again
    {
      Serial.println("Ready to enroll a fingerprint!");
      Serial.println("Please type in the ID # (from 1 to 127) you want to save this finger as...");
      id = readnumber();
      if (id == 0) {// ID #0 not allowed, try again!
        return;
      }
      Serial.print("Enrolling ID #");
      Serial.println(id);

      while (!getFingerprintEnroll() );
    }

    void writeReadSDCard(){

        delay(2000);
        // open the file. note that only one file can be open at a time,
        // so you have to close this one before opening another.
        myFile = SD.open(myFileName, FILE_WRITE);
        // if the file opened okay, write to it:
        if (myFile) { //if myFile is open, you can write
          Serial.print("Writing to "); Serial.println(myFileName);
          //myFile.print(id); myFile.print(","); myFile.print(userName); myFile.print(","); myFile.println("Professor");
          myFile.print(id); myFile.print(","); myFile.println(userName);
          // close the file:
          myFile.close();
          Serial.println("done.");
        } else {
          // if the file didn't open, print an error:
          Serial.print("error opening when writing on "); Serial.println(myFileName);
        }

        delay(2000);

        // re-open the file for reading:
        myFile = SD.open(myFileName);
        if (myFile) {
          Serial.print("Reading SD Card file named "); Serial.println(myFileName);

          // read from the file until there's nothing else in it:
          while (myFile.available()) {
            Serial.write(myFile.read());
          }
          // close the file:
          myFile.close();
          Serial.flush(); // wait for last transmitted data to be sent

        } else {
          // if the file didn't open, print an error:
          Serial.println("error opening for reading");   Serial.print(myFileName);
        }
    }

    uint8_t getFingerprintEnroll() {

      int p = -1;
      Serial.print("Waiting for valid finger to enroll as #"); Serial.println(id);
      while (p != FINGERPRINT_OK) {
        p = finger.getImage();
        switch (p) {
          case FINGERPRINT_OK:
            Serial.println("Image taken");
            break;
          case FINGERPRINT_NOFINGER:
            Serial.println(".");
            break;
          case FINGERPRINT_PACKETRECIEVEERR:
            Serial.println("Communication error");
            break;
          case FINGERPRINT_IMAGEFAIL:
            Serial.println("Imaging error");
            break;
          default:
            Serial.println("Unknown error");
            break;
        }
      }

      // OK success!

      p = finger.image2Tz(1);
      switch (p) {
        case FINGERPRINT_OK:
          Serial.println("Image converted");
          break;
        case FINGERPRINT_IMAGEMESS:
          Serial.println("Image too messy");
          return p;
        case FINGERPRINT_PACKETRECIEVEERR:
          Serial.println("Communication error");
          return p;
        case FINGERPRINT_FEATUREFAIL:
          Serial.println("Could not find fingerprint features");
          return p;
        case FINGERPRINT_INVALIDIMAGE:
          Serial.println("Could not find fingerprint features");
          return p;
        default:
          Serial.println("Unknown error");
          return p;
      }

      Serial.println("Remove finger");
      delay(2000);
      p = 0;
      while (p != FINGERPRINT_NOFINGER) {
        p = finger.getImage();
      }
      Serial.print("ID "); Serial.println(id);
      p = -1;
      Serial.println("Place same finger again");
      while (p != FINGERPRINT_OK) {
        p = finger.getImage();
        switch (p) {
          case FINGERPRINT_OK:
            Serial.println("Image taken");
            break;
          case FINGERPRINT_NOFINGER:
            Serial.print(".");
            break;
          case FINGERPRINT_PACKETRECIEVEERR:
            Serial.println("Communication error");
            break;
          case FINGERPRINT_IMAGEFAIL:
            Serial.println("Imaging error");
            break;
          default:
            Serial.println("Unknown error");
            break;
        }
      }

      // OK success!

      p = finger.image2Tz(2);
      switch (p) {
        case FINGERPRINT_OK:
          Serial.println("Image converted");
          break;
        case FINGERPRINT_IMAGEMESS:
          Serial.println("Image too messy");
          return p;
        case FINGERPRINT_PACKETRECIEVEERR:
          Serial.println("Communication error");
          return p;
        case FINGERPRINT_FEATUREFAIL:
          Serial.println("Could not find fingerprint features");
          return p;
        case FINGERPRINT_INVALIDIMAGE:
          Serial.println("Could not find fingerprint features");
          return p;
        default:
          Serial.println("Unknown error");
          return p;
      }

      // OK converted!
      Serial.print("Creating model for #");  Serial.println(id);

      p = finger.createModel();
      if (p == FINGERPRINT_OK) {
        Serial.println("Prints matched!");
      } else if (p == FINGERPRINT_PACKETRECIEVEERR) {
        Serial.println("Communication error");
        return p;
      } else if (p == FINGERPRINT_ENROLLMISMATCH) {
        Serial.println("Fingerprints did not match");
        return p;
      } else {
        Serial.println("Unknown error");
        return p;
      }

      Serial.print("ID "); Serial.println(id);
      p = finger.storeModel(id);
      if (p == FINGERPRINT_OK) {
        Serial.println("Stored!");

        delay(10000);

          userName = Serial.readString();// read the incoming data as string
          Serial.println(userName);

          writeReadSDCard();

      } else if (p == FINGERPRINT_PACKETRECIEVEERR) {
        Serial.println("Communication error");
        return p;
      } else if (p == FINGERPRINT_BADLOCATION) {
        Serial.println("Could not store in that location");
        return p;
      } else if (p == FINGERPRINT_FLASHERR) {
        Serial.println("Error writing to flash");
        return p;
      } else {
        Serial.println("Unknown error");
        return p;
      }
    }
```

Here is the result:

[![enter image description here][1]][1]

I hope someone can answer my question.

  [1]: https://i.stack.imgur.com/ULqLd.png

Answers: 0


body:
I am trying to build a Smarthome system with NodeMCU.
NodeMCU would wire up with relays.
How many replays can one NodeMCU control?

title: How many output pins do NodeMCU have?

Answers: 0


body:
The code is working but there is a delay when the LED turns on and off (physically). Is there a more efficient way I could write this code? I assume it is the delay in reading the DHT11 causing it.

~Issue resolved

title: Using DHT11 and EMF - Lag issue

Answers: 1

body:
Your question is a bit unclear (A delay is defined by two points in time or one point and a duration -- you only tell us one point).

Reading your code, I can only assume that you mean that an external event on `inPin` is delayed in showing up on the LED on `pin11`. This should come up when that external event is emitted just at the beginning of your `delay(1000)` (and is therefore randomly delayed between 0 and 1000ms).

You could get rid of the delay in your loop using a bit of timer math around the DHT11 reading code:

```
#define DHT11_SAMPLE_DELAY = 1000
uint32_t last_dht11_reading_ms = 0;

void loop() {
  uint32_t current_ms = millis();

  if( current_ms - last_dht11_reading_ms > DHT11_SAMPLE_DELAY ) {

    DHT.read11(dht_apin);
    Serial.println("....your output....");

    last_dht11_reading_ms = current_ms;
  }
  // also, remove the delay(1000) in your loop()
}

```
You get the current time (`millis()` gives you the uptime since boot in milliseconds) and subtract the time of last reading. If the result is bigger than a threshold (in this case: 1000 ms), you do a new reading of the DHT11 while setting the variable containing the time of last reading to the current time. When the `loop()` comes around again, the threshold will not be reached, so reading the DHT11 value is skipped until `millis()` returns a sufficiently big number again.


body: I have read other posts regarding ArduinoJson that recommend using a library version no later than 5.14.3.  That recommendation is more than a year old - is it still the recommended library version?

title: Missing ArduinoJson/DynamicJsonBuffer.hpp

Answers: 0


body:
I am making a stream-based radio clock that needs to send snippets of the stream to an external API for music recognition using an ESP-WROOM-32 DevKit.

The snippets that I record are 15 seconds long, which results in a file ~2MB in size (assuming the stream is 128Kbps, MP3). If I try to buffer this in the ESP32's RAM, it will fill it up in no time.

How can I send that snippet via HTTP without overflowing the ESP's RAM?

title: Send large files to API via HTTP

Answers: 0


body:
First post here. So I have an issue, which I have identified, but I'm not quite sure how to fix it.
I'd really appreciate some input and suggestions.
I realize that my "_pwmDelta_" is the problem, but I am not sure what to do to fix it.

I am trying to write a program that will increment the value of the pin 3 a set amount of time, in a somewhat linear fashion, _starting_ at my low point, and _finishing_ at my high point.

The issue is that my equation is incorrect and I can't output a partial bit value. Huge oversight on my part. If you read the data from the serial monitor with the code written as I have it, you'll see that it isn't coming even close to reaching my max value.

I need suggestions on how I can have the program figure out the delta in a way that I can send an integer value to the PWM output pin, yet still keep a somewhat linear increase over time. Would this even be possible?

    int motor1 = 3;         //pin for PWM output to motor
    float t = 0;            //Variable to keep Track of time
    int tLim = 30;          //Time Limit for Ramp
    float lowLim = 21;      //Low Limit, in Duty Cycle %
    float highLim = 65;     //High Limit, in Duty Cycle %
    float motorPWM = 53.55; //Starting Value of PWM, in Bits
    float pwmDelta = ((255/100)*(highLim-lowLim))/(tLim); //Delta equation, to calculate how much to change PWM value each time it is incremented
    float motorDelta;       //Variable to write value to Motor Output

    void setup() {
      pinMode(motor1, OUTPUT);
      analogWrite(motor1, 53.55); //run motor at initial value for 20 seconds before beginnning ramp
      delay(20000);
      Serial.begin(9600);
    }

    void loop() {
      motorDelta = motorPWM + pwmDelta; //incrementing output value based on Delta Equation
      motorPWM = motorDelta; //Setting new incremented value equal to old value, so incrementing can continue

      if (t <= tLim) {  //Check if time is <= time limit
        analogWrite(motor1, (motorDelta)); //write incremented value to output pin
        delay(1000);  //wait 1 second, increment t, to keep track of time
        t++;
      }
      else {
        analogWrite(motor1, motorPWM = 165.75); //set pin to high value for 60 seconds, then set to 0
        delay(60000);
        analogWrite(motor1, motorPWM = 0);
      }
      Serial.print(motorDelta);
      Serial.println();
      Serial.print(t);
      Serial.println();
    }

title: Issue with incrementing PWM over time

Answers: 4

body:
    float pwmDelta=((255/100)*(highLim-lowLim))/(tLim);

That line should be:

    float pwmDelta=((255.0/100)*(highLim-lowLim))/(tLim);

Adding the .0 tells the compiler to do that math using floats and you get 2.55.  Without it the math is done with int and the result is 1 which isn't what you want.

    analogWrite(motor1, 53.55);

Just write 54.  analogWrite only accepts integer values.

    analogWrite(motor1, motorPWM=165.75);

You should really do that as two lines, an assgnment and then an analogWrite.  This way leads to confusing code.  Also, analogWrite only accepts integer values so your decimals are useless there as well.

body:
You are trying to smoothly ramp up the PWM value from 21% to 65% over a period of 30 seconds at 1 second intervals, which does not work very well because the PWM value has to be a byte.

That means that the value written into the PWM register changes from  21*255/100  to 65*255/100, which is 53.55 to 165.75.

Use values of 53 and 166, which gives a difference of 113.

Your code is written to update the PWM value every 1000 ms, which produces 30 steps, most of which are not integers.

Instead, ramp up the PWM value in 113 steps. Each step will be an integer and each step will be 265486 μs in length.

body:
The previous responses already showed the main issue with the program.
Here I am providing a few suggestions that hopefully could still improve
it:

 - Instead of using `delay()`, you could manage the time with
   `millis()`. This will make the ramp smoother, and you will be able to
   add code to the loop if needed that will not be blocked by the
   delays.
 - Storing the times in milliseconds and the PWM value in its natural
   unit (rather than percent) makes the code simpler.
 - Remove redundant variables, such as `motorDelta`, which is the same
   as `motorPWM`.
 - Consistent indentation and removal of superfluous parentheses help
   the readability.

Here is my attempt at implementing those suggestions:

```c++
const int motor1 = 3;  // pin for PWM output to motor
const unsigned long tLim = 30000;  // duration of the PWM ramp
const float PWM_unit = 255.0/100;  // convert percent to PWM scale
const float lowLim = PWM_unit * 21;
const float highLim = PWM_unit * 65;
const float PWM_rate = (highLim-lowLim) / tLim;

unsigned long start_time;  // start of the ramp
int previousPWM = 0;

void setup() {
    pinMode(motor1, OUTPUT);
    analogWrite(motor1, round(lowLim));
    delay(20000);
    Serial.begin(9600);
    Serial.println(" t   PWM");
    Serial.println("--------");
    start_time = millis();
}

void loop() {
    unsigned long t = millis() - start_time;

    if (t >= tLim) {  // we are done
        analogWrite(motor1, round(highLim));
        delay(60000);  // keep at highLim for 60 s
        analogWrite(motor1, 0);  // then stop
        exit(0);
    }

    int motorPWM = round(lowLim + t * PWM_rate);
    if (motorPWM != previousPWM) {
        analogWrite(motor1, motorPWM);
        Serial.print(t / 1000.0);
        Serial.print("  ");
        Serial.println(motorPWM);
        previousPWM = motorPWM;
    }
}
```

body:
What's happening is that you've written a fraction in a way that the compiler treats it as integer math. C/C++ truncate fractions, so 255/100 is just 2 (and if any of the rest of those are integers, they cause truncation too). What you want to do is make some number in that calculation a decimal--it doesn't matter which one--or cast an input to a float with `(float) somevariable`.

As long as that's all on one line, all of the calculations involved (*excepting order of operations, so cast to float one of the variables being divided* if you have them in separate parenthesized terms) will be in floating point. Do note that if you set the value of an integer with this, it will only truncate **after** doing the math accurately, too, so it's more correct.

`float pwmDelta = ((255/100)*(highLim-lowLim))/(tLim);`

Should be:

`float pwmDelta = 2.55*(highLim-lowLim)/(float)tLim;`
(This also makes it all one term.)


body:
I am trying to upload a sketch to the ESP32-CAM board using Arduino IDE 1.8.12 and I get an error message:

    exec: "python": executable file not found in $PATH
    Error compiling for board AI Thinker ESP32-CAM.

My OS is Ubuntu 18.04.4.LTS.

When I type python in the console, it does open python:

    $ python
    Python 2.7.17 (default, Nov  7 2019, 10:07:09)
    [GCC 7.4.0] on linux2
    Type "help", "copyright", "credits" or "license" for more information.
    >>>
    KeyboardInterrupt
    >>>

Also python is in one of the directories referenced by PATH:

    $ which python
    /usr/bin/python
    $ echo $PATH
    /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin

I added an additional URL referring to the ESP32 boards on the Espressif website:

    Arduino IDE > File > Preferences > Settings > Additional Boards Manager URLs: > https://dl.espressif.com/dl/package_esp32_index.json

Then I added the libraries for all ESP32 boards:

    Arduino IDE > Tools > Board > Boards Manager > esp32 version 1.0.4

(I tried with version 1.0.3 and it didn't change anything...)

I selected my board in the interface:

    Arduino IDE > Tools > Board > AI Tinker ESP32-CAM

I granted all permissions to the USB port:

    sudo chmod a+rwx /dev/ttyUSB0
    ls -la /dev/ttyUSB0
    crwxrwxrwx 1 root dialout 188, 0 Mar  4 21:25 /dev/ttyUSB0

My sketch is really simple:

    void setup() {
    }

    void loop() {
    }

I get the same error for any example sketch and for any ESP32 board.

Any idea how this could be fixed ?

title: Error 'exec: "python": executable file not found in $PATH Error compiling for board AI Thinker ESP32-CAM.' in Arduino IDE 1.8.12

Answers: 2

body:
All right so I was able to fix the problem. The Arduino IDE I was using had been installed from the Ubuntu Software Center. I uninstalled it.

Then I reinstalled the Arduino IDE by downloading it from the www.arduino.cc website and doing a manual install in /opt. Now it works awesome.

body:
This was an issue with the old Arduino IDE snap on Ubuntu. You can easily fix this by installing the new [arduino snap](https://snapcraft.io/arduino):

```
snap install arduino
```

Then add your user to the `dailout` group:

```shell
sudo usermod -a -G dialout $USER
```

After this, **reboot your device** and open Arduino IDE.

## Installing additional libraries

The Arduino IDE snap runs inside of a sandbox for security and stability reasons. This means it cannot access the Python libraries on your device. The snap bundles Python 3 and the `serial` library. If you need any other Python dependencies, you can install them inside of the sandbox using the `arduino.pip` command.

```
arduino.pip install <package-name>
```

*Note: do not use `sudo` for this command*


body:
I have some arduino code I adapted from a simple 2 button 2 relay code I found online. I just multiplied everything so I could have 5 buttons/5relays. I am using a NodeMCU (ESP-12E) for this.

I have not changed anything, and now trying to upload it to other boards, and the same existing board I used before. Same results every time.

I have verified arduino is updated, the board manager link is up to date, and verified the code. Drivers re-installed. I have tried using different boards such as nodemcu 0.9, generic esp8266 module etc.
Code is verified, no error messages upon upload.

But every single time I get this error in the serial monitor over and over:

```

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

wdt reset
load 0x4010f000, len 1392, room 16
tail 0
chksum 0xd0
csum 0xd0
v3d128e5c
~ld
```

And here is the code I am using:
(But please keep in mind this WORKS and has worked before)

```
//Buttons

int button1 = 4;
int button2 = 13;
int button3 = 12;
int button4 = 15;
int button5 = 10;

//Relays
int rl1 = 5;
int rl2 = 0;
int rl3 = 14;
int rl4 = 16;
int r15 = 9;

//States for Relay and Button (1)

int state1 = HIGH;      // the current state of the output pin
int reading1;           // the current reading from the input pin
int previous1 = LOW;    // the previous reading from the input pin

//States for Relay and Button (2)

int state2 = HIGH;      // the current state of the output pin
int reading2;           // the current reading from the input pin
int previous2 = LOW;    // the previous reading from the input pin

//States for Relay and Button (3)

int state3 = HIGH;      // the current state of the output pin
int reading3;           // the current reading from the input pin
int previous3 = LOW;    // the previous reading from the input pin

//States for Relay and Button (4)

int state4 = HIGH;      // the current state of the output pin
int reading4;           // the current reading from the input pin
int previous4 = LOW;    // the previous reading from the input pin

//States for Relay and Button (5)

int state5 = HIGH;      // the current state of the output pin
int reading5;           // the current reading from the input pin
int previous5 = LOW;    // the previous reading from the input pin

// the follow variables are long's because the time, measured in miliseconds,
// will quickly become a bigger number than can be stored in an int.
long time1 = 0;          // the last time the output pin was toggled
long time2 = 0;
long time3 = 0;
long time4 = 0;
long time5 = 0;

long debounce1 = 60;   // the debounce time, increase if the output flickers
long debounce2 = 60;
long debounce3 = 60;
long debounce4 = 60;
long debounce5 = 60;

void setup()
{
  pinMode(button1, INPUT);
  pinMode(button2, INPUT);
  pinMode(button3, INPUT);
  pinMode(button4, INPUT);
  pinMode(button5, INPUT);

  pinMode(rl1, OUTPUT);
  pinMode(rl2, OUTPUT);
  pinMode(rl3, OUTPUT);
  pinMode(rl4, OUTPUT);
  pinMode(r15, OUTPUT);

}

void loop() {

  reading1 = digitalRead(button1);
  reading2 = digitalRead(button2);
  reading3 = digitalRead(button3);
  reading4 = digitalRead(button4);
  reading5 = digitalRead(button5);

  // if the input just went from LOW and HIGH and we've waited long enough
  // to ignore any noise on the circuit, toggle the output pin and remember
  // the time
  //Condition Relay 1
  if (reading1 == HIGH && previous1 == LOW && millis() - time1 > debounce1) {
    if (state1 == HIGH)
      state1 = LOW;
    else
      state1 = HIGH;

    time1 = millis();
  }

  //Condition Relay 2
    if (reading2 == HIGH && previous2 == LOW && millis() - time2 > debounce2) {
    if (state2 == HIGH)
      state2 = LOW;
    else
      state2 = HIGH;

    time2 = millis();
  }

  //Condition Relay 3
    if (reading3 == HIGH && previous3 == LOW && millis() - time3 > debounce3) {
    if (state3 == HIGH)
      state3 = LOW;
    else
      state3 = HIGH;

    time3 = millis();
  }

  //Condition Relay 4
    if (reading4 == HIGH && previous4 == LOW && millis() - time4 > debounce4) {
    if (state4 == HIGH)
      state4 = LOW;
    else
      state4 = HIGH;

    time4 = millis();
  }

  //Condition Relay 5
    if (reading5 == HIGH && previous5 == LOW && millis() - time5 > debounce5) {
    if (state5 == HIGH)
      state5 = LOW;
    else
      state5 = HIGH;

    time5 = millis();
  }

  digitalWrite(rl1, state1);
  digitalWrite(rl2, state2);
  digitalWrite(rl3, state3);
  digitalWrite(rl4, state4);
  digitalWrite(r15, state5);

  previous1 = reading1;
  previous2 = reading2;
  previous3 = reading3;
  previous4 = reading4;
  previous5 = reading5;
}
```

If I google this error I get a myriad of results that so far have not helped me. Any help or insight on how I can better understand this error, where to start, and what I need to do to get this "simple" sketch working would be awesome.  I'm at my wits end and all I want is a simple lighting panel to work.

title: Getting wdt reset + reboots every 5 seconds on simple button/relay code that has worked previously, now it does not and I changed nothing

Answers: 3

body:
First thing to realize for you is that the externally set status of three of the GPIO pins [determine the boot mode for the ESP8266][1] used on your NodeMCU. So you must take care to check that your external wiring will not interfere with the boot mode:

  * GPIO15/D8 must be LOW on boot (i.e. no external pull-up resistors may be connected between D8 and 3.3V)
  * GPIO2/D4 must be HIGH on boot (i.e. no external pull-down resistors may be connected between D4 and GND)
  * GPIO0/D3 must be free of pull-up/down resistors so that the USB-to-serial chip can switch between RUN and FLASH mode.

Also, holding GPIO16/D0 LOW for an extended amount of time while running [may have unintended side effects like triggering the watchdog][2], especially if the board manufacturer decided to add the deep sleep wakeup resistor between D0 and RST (you most certainly have a NodeMCU clone, so this might actually be possible).

So it might very well be that you need to reverse the button logic on GPIO15/D8 (i.e. connect the button between D8 and 3.3V). It also might be that the pin numbering on your NodeMCU is confusing; better [use the D0-D10 constants][3].

Depending on the type of your relays, your relays may act as a pull-up/down resistor, too, further adding to the confusion.

I'd try this sketch without anything connected (no buttons, no relays) and when it works, I'd add buttons and relays one by one until you find the culprit. Sometimes it might be sufficient to swap a relay and a button, sometimes you need to reverse the logic on a button.

I would say that using any ESP8266 with that many input/output lines requires very careful consideration on where to connect what. The GPIO pins on an Arduino Nano are not involved in boot mode nor watchdog, so at least there you'd not get any interference.

  [1]: https://github.com/esp8266/esp8266-wiki/wiki/Boot-Process#esp-boot-modes
  [2]: https://github.com/esp8266/Arduino/issues/1490
  [3]: https://github.com/esp8266/Arduino/issues/584#issuecomment-123715951

body:
According to [Esp8266 documentation][1] this is a software reset.
After a fast peek, I didn't find delay() or yield() in your code.
The esp8266 needs to attend some time to WiFi related background tasks, and it is does when your arduino code delays or yields the processor.

  [1]: https://www.google.com/url?sa=t&source=web&rct=j&url=https://www.espressif.com/sites/default/files/documentation/esp8266_reset_causes_and_common_fatal_exception_causes_en.pdf&ved=2ahUKEwjzp-zX04PoAhVms4sKHUrrDoYQFjAAegQIAhAB&usg=AOvVaw0ibtWPtwCjhMowy9Yuz7Ac&cshid=1583422506199

body: For anyone that has a similar issue, I figured it out. GPIO 9 could not be used for a relay/output for whatever reason. Wish I knew why.  Switched it to GPIO2 (D4) and the reboots stopped.


body:
I'm new to Arduino programming and haven't programmed in C++ in the past. I'm trying to create a custom library to cycle a rainbow on my NeoPixel LED strip. I want to pass a reference or pointer or whatever into the library class so I can keep the code in my project file as simple as possible.

Here is my current project code:
```
#include <YaNeoPixelCycle.h>
#include <Adafruit_NeoPixel.h>

#define CONTROL_PIN 3
#define LED_COUNT 8
Adafruit_NeoPixel neoPixel(LED_COUNT, CONTROL_PIN, NEO_RGBW + NEO_KHZ800);
YaNeoPixelCycle cycle = YaNeoPixelCycle(neoPixel,255,100,200);

void setup() {
}

void loop() {
  cycle.tryStep();
}
```

And here is the library I tried to create:
```
/*
 Youkai's Artificery NeoPixel cycle library.
 A super basic RGB LED cycle.
*/

#ifndef YaNeoPixelCycle_h
#define YaNeoPixelCycle_h

#include "Arduino.h"
#include <Adafruit_NeoPixel.h>

class YaNeoPixelCycle{
 public:
  YaNeoPixelCycle(Adafruit_NeoPixel& neoPixel, int saturation, int brightness, int hueStep);
  void tryStep();
 private:
  Adafruit_NeoPixel& _neoPixel;
  unsigned int _ledHue = 0;
  int _saturation;
  int _brightness;
  int _hueStep;
};

#endif
```

```
/*
 Youkai's Artificery timer library.
 Some basic non-blocking timer functions.
*/

#include "Arduino.h"
#include "YaNeoPixelCycle.h"

YaNeoPixelCycle::YaNeoPixelCycle(Adafruit_NeoPixel& neoPixel, int saturation, int brightness, int hueStep){
 _neoPixel = neoPixel;
 _saturation = saturation;
 _brightness = brightness;
 _hueStep = hueStep;
 _neoPixel.begin();
 _neoPixel.show();
}

void YaNeoPixelCycle::tryStep(){
 _ledHue += _hueStep;
 _neoPixel.fill(_neoPixel.ColorHSV(_ledHue, _saturation, _brightness));
 _neoPixel.show();
}
```

The first step would be getting this to function at all. Uploading this to my Sparkfun ProMicro bricks it and I have to reset it to upload code again.

After that it would be awesome if it was possible to declare the NeoPixel in the project file but not actually initialize it until the library file. I'd love to pass CONTROL_PIN and LED_COUNT as variables to the library with `YaNeoPixelCycle(..., int controlPin, int ledCount)` so I don't have to set up a bunch of duplicate variables in my main file if I'm running more than one NeoPixel strip.

This is my own custom library so I'm not too worried about it being obscure. If it's possible/easier I would be fine just moving all of the NeoPixel code entirely into the library and never creating it at all in the main file. Just passing the control pin and LED count as parameters and having to "know" that those refer to a NeoPixel would be fine too.

title: Passing a NeoPixel object reference to a custom library

Answers: 1

body:
You call `_neoPixel.begin()` and `_neoPixel.show()` in the constructor of your class. This constructor runs before the Arduino is initialized. This is why   `begin()` functions are used. Add a `begin()` function to your class and call `cycle.begin()` in `setup()`.

    void YaNeoPixelCycle::begin() {
      _neoPixel.begin();
      _neoPixel.show();
    }

Of course remove the `_neoPixel.begin()` and `_neoPixel.show()` from the constructor.


body: I was wondering if I connect a HC-SR04 to an Arduino or any other microcontroller by normal cables, what would be the maximum length of this cable so that the measurements will still be true, and not affected by the length of this cable?

title: How far can a HC-SR04 can stand from the microcontroller?

Answers: 3

body:
The signal of an HC-SR04 is the pulse on the "Echo" wire. The length of that pulse is directly proportionate to the distance from the object.

Since cable length does not affect the duration of that pulse, measurement accuracy isn't affected either.

body:
I have a couple measuring the liquid level of two tanks.

The units are distanced from the microcontroller by 12' of 18ga solid-core copper cable.

Testing was done with another microcontroller with the sensor attached by 6" cable to ensure accurate readings.

That's the longest I needed, so I haven't tested beyond that.

body:
this problem consists of 2 things :

 1. supply level drop (this one has severe effect)
 2. signal level drop (a little more forgiving)

as the signals on the cables don't have high frequencies, the problem narrows down to just voltage level drop due to cable resistance.

supply level drop: the datasheet for SR04 says a maximum active current of 20mA is required for device to work properly. the supply voltage is 4.5~5.5v. so if you provide a 5v power for it, the cable must not drop it under 4.5v. the maximum resistance for the cable is calculated

> R=V/I => R = (0.5/20)*10^3 = 25 Ohms

. you can use this value to find out maximum cable length using resistance tables provided by cable makers. e.g. if you have bought a 5ohms/meter cable, the maximum length should be under 5 meters to ensure a good power delivery.

the signals on the other hand, have very little current going between them. as the MCU/Module pins have a very high input impedance. so they are not as severe as the supply drop.

using a 100uF cap near SR04's supply pins would be great.


body:
I'm stepping into Arduino world and decided to build a small board to implement a gamepad. Prior designing the board I tested my firmware on a *Arduino Pro Micro USB* so I decided to make something similar. My board use an **ATMEGA32U4-AU** instead  **ATMEGA32U4-MU** because it's simpler to solder. Connecting the board to my PC I noticed a new device named *ATmega32U4* appear between Windows devices this sounds like the board is working.
Now the problem is how to program it with the correct bootloader (?) and make it a *real* **Arduino** board.
I found some spurious articles about how to make it but I have not a clean idea. Someone can help me?
I can share everything you need to focus on the board.

UPDATE ---------------------------------------------------------------------

Before installing Arduino bootloader I tried programming a sample firmware on the board trough Atmel FLIP (successfully). After that I never been able to program the board again (neither trough FLIP or other means)

I connected my board to Arduino ISP and since Windows seems unable to find the correct driver I had to install it manually, after that I tried to install the bootloader trough **Install bootloader** option of Arduino IDE (selecting Arduino ISP as programmer) but I had no success:
This's the log:

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

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

             Using Port                    : usb
             Using Programmer              : arduinoisp
    avrdude: usbdev_open(): Found USBtinyISP, bus:device: bus-0:\\.\libusb0-0001--0x2341-0x0049
             AVR Part                      : ATmega32U4
             Chip Erase delay              : 9000 us
             PAGEL                         : PD7
             BS2                           : PA0
             RESET disposition             : dedicated
             RETRY pulse                   : SCK
             serial program mode           : yes
             parallel program mode         : yes
             Timeout                       : 200
             StabDelay                     : 100
             CmdexeDelay                   : 25
             SyncLoops                     : 32
             ByteDelay                     : 0
             PollIndex                     : 3
             PollValue                     : 0x53
             Memory Detail                 :

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

             Programmer Type : USBtiny
             Description     : Arduino ISP Programmer
    avrdude: programmer operation not supported

    avrdude: Using SCK period of 10 usec
    avrdude: initialization failed, rc=-1
             Double check connections and try again, or use -F to override
             this check.

    avrdude done.  Thank you.

    Error during bootloader writing.

----

I can clearly see that my firmware is not running when I start the booloader process (probably because it reset the board).
From the log it seems that everything is going correctly until:
*programmer operation not supported*

What does it means? Is the programmer unable to program such chip? How can I fix this?
If I reset my board prior trying to burn again a new firmware over it will it work or I just have to put a brand new micro on it?

Best regards,
 Mike

title: Self made ATMega32U4 board first programming

Answers: 1

body: The problem was a wrong MISO connection given by a bugged ATMega32U4 footprint.


body:
I have an SPI slave connected to Due. I send the SPI slave into sleep mode. During sleep, I need to pull all pins low, including MOSI. What's the best way to pull the SPI-4 pin low on a Due?

[Here](https://arduino.stackexchange.com/a/62492/13327)'s a similar question but it's about an AVR chip and the answer obviously doesn't apply to SAM3X8 which is an ARM.

title: Set SPI MOSI pin to idle low on a Due?

Answers: 1

body: I have managed to set MOSI to low by setting bit 26 in `PIOA->PIO_PER`, `PIOA->PIO_OER` and  `PIOA->PIO_CODR` registers. To use SPI again, bit 26 in `PIOA->PIO_PDR` has to be set (this cancels the effect of `PIOA->PIO_PER`).


body:
Is it possible to keep the 5V on, while putting the Arduino (ATMEGA328P) in sleep more, using LowPower library?

I'm trying to use this HAT:

https://spellfoundry.com/product/sleepy-pi-2-usb-c/

to control the power of my Raspberry Pi. But on top of it, I want to have a second HAT that I want to feed 5V input, event after I shut down Raspberry Pi and put the Arduino to sleep.

title: Keep 5V on while sleep with LowPower library

Answers: 1

body: If I read the schematics at https://spellfoundry.com/download/sleepy-pi-2-usb-c-schematic/ correctly, you need to draw continuous 5V power from the SUPPLY_5V pin instead of the SUPPLY_EXP_5V pin (the latter seems to be switched via some MOSFETs connected to pin 2 of the ATMEGA328p). Which means that you need to connect the 5V power of your second HAT to JP4 pin 3 on the Sleepy Pi HAT (instead of JP5 pin 3).


body:
I'm having a hard time trying to convert a float into a char array so it's stored like '7.125' just like the float looks.

I'm trying to communicate with an ATtiny85 (slave) and a program on a Raspberry Pi (master) over I2C.

The master expects 31 bytes from the slave when data is sent to it.

When I use this code on the ATtiny85 everything works as it should, the Pi gets the data correctly.

```
    char computerdata[35];
    computerdata[0] = '3';
    computerdata[1] = '.';
    computerdata[2] = '8';
    computerdata[3] = '7';
    computerdata[4] = '7';

    TinyWire.send(1);
    TinyWire.send(computerdata,30);
```

Of course I need to put a float variable in the array and not define numbers like I have for testing and this is where it breaks.

When I do something like this, it doesn't work, the Pi reports parsing error yet when I do this on the Due with Serial prints the char array looks good but something is different about it.

```
  sprintf(computerdata, "%2.32f", pH);

OR

  snprintf (computerdata, 35, "%f", pH);
```

What am I missing? Any ideas?

Thanks

title: Convert float to char array on ATtiny85

Answers: 2

body:
The reason is that the library which implements `snprintf` and `sprintf` can be dependent on the compiler used for your MCU, so in your case it's not supported.

If you always need the form `%2.32f` why not put it in directly, like:

    int i = int(3.877 * 1000.0); // Assuming f of form a.bcd, i will be 3877
    char str[6];
    str[0] = (i / 1000) % 10;
    str[1] = '.';
    str[2] = (i / 100) % 10;
    str[3] = (i /  10) % 10;
    str[4] = (i      ) % 10;
    str[5] = '0';

It will be much faster too.

body:
Just to complement Michel Keijzers’ answer: `sprintf()` or `snprintf()`
are normally the right solution. On the AVR platform, however, float
conversions are left out of their default implementation, because they
take quite a lot of flash space, even when not used. On the other hand,
the avr-libc provides the non-standard function [`dtostrf()`][dtostrf]
for doing this conversion. The program

```c++
void setup() {
    float f = 3.877;
    char str[35];
    dtostrf(f, 0, 3, str);
    Serial.begin(9600);
    Serial.println(str);
}

void loop(){}
```

outputs

```text
3.877
```

[dtostrf]: https://www.nongnu.org/avr-libc/user-manual/group__avr__stdlib.html#ga060c998e77fb5fc0d3168b3ce8771d42


body:
I am trying to use pulse sensor with Arduino Nano 33 BLE sense, but when I verify it, it shows Error compiling for board Arduino Nano 33 BLE. The code is from the pulse sensor website. The code works with all Arduino board, but it is not working with the Arduino Nano 33 BLE.

This is the code:

    /*  Getting_BPM_to_Monitor prints the BPM to the Serial Monitor, using the least lines of code and PulseSensor Library.
     *  Tutorial Webpage: https://pulsesensor.com/pages/getting-advanced
     *
    --------Use This Sketch To------------------------------------------
    1) Displays user's live and changing BPM, Beats Per Minute, in Arduino's native Serial Monitor.
    2) Print: "♥  A HeartBeat Happened !" when a beat is detected, live.
    2) Learn about using a PulseSensor Library "Object".
    4) Blinks LED on PIN 13 with user's Heartbeat.
    --------------------------------------------------------------------*/

    #define USE_ARDUINO_INTERRUPTS true    // Set-up low-level interrupts for most acurate BPM math.
    #include <PulseSensorPlayground.h>     // Includes the PulseSensorPlayground Library.

    //  Variables
    const int PulseWire = 0;       // PulseSensor PURPLE WIRE connected to ANALOG PIN 0
    const int LED13 = 13;          // The on-board Arduino LED, close to PIN 13.
    int Threshold = 550;           // Determine which Signal to "count as a beat" and which to ignore.
                                   // Use the "Gettting Started Project" to fine-tune Threshold Value beyond default setting.
                                   // Otherwise leave the default "550" value.

    PulseSensorPlayground pulseSensor;  // Creates an instance of the PulseSensorPlayground object called "pulseSensor"

    void setup() {

      Serial.begin(9600);          // For Serial Monitor

      // Configure the PulseSensor object, by assigning our variables to it.
      pulseSensor.analogInput(PulseWire);
      pulseSensor.blinkOnPulse(LED13);       //auto-magically blink Arduino's LED with heartbeat.
      pulseSensor.setThreshold(Threshold);

      // Double-check the "pulseSensor" object was created and "began" seeing a signal.
       if (pulseSensor.begin()) {
        Serial.println("We created a pulseSensor Object !");  //This prints one time at Arduino power-up,  or on Arduino reset.
      }
    }

    void loop() {

     int myBPM = pulseSensor.getBeatsPerMinute();  // Calls function on our pulseSensor object that returns BPM as an "int".
                                                   // "myBPM" hold this BPM value now.

    if (pulseSensor.sawStartOfBeat()) {            // Constantly test to see if "a beat happened".
     Serial.println("♥  A HeartBeat Happened ! "); // If test is "true", print a message "a heartbeat happened".
     Serial.print("BPM: ");                        // Print phrase "BPM: "
     Serial.println(myBPM);                        // Print the value inside of myBPM.
    }

      delay(20);                    // considered best practice in a simple sketch.

    }

The error text:

        Arduino: 1.8.7 (Mac OS X), Board: "Arduino Nano 33 BLE"

    In file included from /Users/sofyanjamal/Documents/Arduino/libraries/PulseSensor_Playground/src/PulseSensorPlayground.h:439:0,
                     from /Users/sofyanjamal/Documents/Arduino/libraries/PulseSensor_Playground/src/PulseSensorPlayground.cpp:16:
    /Users/sofyanjamal/Documents/Arduino/libraries/PulseSensor_Playground/src/PulseSensorPlayground.cpp: In member function 'boolean PulseSensorPlayground::sawNewSample()':
    /Users/sofyanjamal/Documents/Arduino/libraries/PulseSensor_Playground/src/utility/Interrupts.h:72:41: error: 'cli' was not declared in this scope
     #define DISABLE_PULSE_SENSOR_INTERRUPTS cli()
                                             ^
    /Users/sofyanjamal/Documents/Arduino/libraries/PulseSensor_Playground/src/PulseSensorPlayground.cpp:105:5: note: in expansion of macro 'DISABLE_PULSE_SENSOR_INTERRUPTS'
         DISABLE_PULSE_SENSOR_INTERRUPTS;
         ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    /Users/sofyanjamal/Documents/Arduino/libraries/PulseSensor_Playground/src/utility/Interrupts.h:73:40: error: 'sei' was not declared in this scope
     #define ENABLE_PULSE_SENSOR_INTERRUPTS sei()
                                            ^
    /Users/sofyanjamal/Documents/Arduino/libraries/PulseSensor_Playground/src/PulseSensorPlayground.cpp:108:5: note: in expansion of macro 'ENABLE_PULSE_SENSOR_INTERRUPTS'
         ENABLE_PULSE_SENSOR_INTERRUPTS;
         ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    exit status 1
    Error compiling for board Arduino Nano 33 BLE.

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

Answers: 0


body:
This is my first venture into Arduino. I am unsure which one to use even for this. As this will be a dedicated unit, and size is a small priority, the smaller the better.

Here is more info on the scheme I am looking for.

Switch 1 on turns on LED groups 1 and 2

Switch 2 on turns on LED groups 3, 4, 5, 6, 7 and 8

Switch 3 on turns on 1 for say 500 ms, then turns 1 off, turns on 3 for 500 ms, then turns off 3, then turns on 5 for 500 ms, then turns off 5, turns on 7 for 500 ms, then turns off 7, then loops back and turns on 1 repeating the cycle.

Switch 4 on turns on 2 for say 500 ms, then turns 2 off, turns on 4 for 500 ms, then turns off 4, then turns on 6 for 500 ms, then turns off 6, turns on 8 for 500 ms, then turns off 8, then loops back and turns on 2 repeating the cycle.

Will I need an Arduino uno, nano or micro?
I am hoping this will be an easy to do project in order to learn the world of Arduino

title: First time arduino attempt. 4 switch inputs controlling 8 LED outputs

Answers: 2

body:
Micheal well easy solution is to use arduino nano as its bread board friendly and easy as it comes with the arduino IDE installed, well if size is what you are looking for then digispark attiny 85 can also do the task and its size is almost equal to a coin but for that youll need to install it in the arduino IDE which is a bit difficult.
if you need any help with attiny 85 you can come here

body:
First of all, you need to have an overview over the whole project because you need to know what components you are going to use, how many digital/analog pins do you need, then check the official Arduino website to see if the board fulfills your needs.

If there is no special need, like more EEPROM or more analog inputs, almost most of the board will work for you (because most of them have the same microcontroller: ATMEGA328P), so it is up to what form factor you prefer more.

Personally, I would like to go with the Micro board because it has microusb connector, it is breadboard friendly (which is a big plus when you are prototyping) and it can be recognised as a mouse or keyboard.


body:
    #include <Wire.h>

    long aX,aY,aZ,gX,gY,gZ;
    float rtX,rtY,rtZ,gfX,gfY,gfZ;

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

    void loop()
    {
      recordAccelregisters();
      recordGyroregisters();
      printData();
      delay(100);
    }

    void setupMPU()
    {

      Wire.beginTransmission(0b1101000);
      Wire.write(0x6B);
      Wire.write(0b00000000);
      Wire.endTransmission();
      Wire.beginTransmission(0b1101000);
      Wire.write(0x1B);
      Wire.write(0b00000000);
      Wire.endTransmission();
      Wire.beginTransmission(0b1101000);
      Wire.write(0x1C);
      Wire.write(0b00000000);
      Wire.endTransmission();
    }

    void recordAccelregisters()
    {
      Wire.beginTransmission(0b1101000);
      Wire.write(0x3B);
      Wire.endTransmission();
      Wire.requestFrom(0b1101000,6);
      while(Wire.available()<6)
      {
        aX = Wire.read()<<8|Wire.read();
        aY= Wire.read()<<8|Wire.read();
        aZ = Wire.read()<<8|Wire.read();
        processAData();
      }
    }

    void processAData()
    {
      gfX= aX/16384.0;
      gfY = aY/16384.0;
      gfZ = aZ/16384.0;
    }

    void recordGyroregisters()
    {
      Wire.beginTransmission(0b1101000);
      Wire.write(0x43);
      Wire.endTransmission();
      Wire.requestFrom(0b110100,6);
      while(Wire.available()>6)
      {
        gX = Wire.read()<<8|Wire.read();
        gY = Wire.read()<<8|Wire.read();
        gZ = Wire.read()<<8|Wire.read();
        processGdata();
      }

    }

    void processGdata()
    {
      rtX= gX/131.0;
      rtY = gY/131.0;
      rtZ= gZ /131.0;
    }

    void printData()
    {
      Serial.print("Gyro degree(x)= "+ rtX + " ");// this line shows error mentioned above in the question
      Serial.print("Gyro degree(y)= "+ rtY + " ");// this line shows error mentioned above in the question
      Serial.print("Gyro degree(z)= "+ rtZ + " ");// this line shows error mentioned above in the question
      Serial.print("Accel Gforce(x)= "+ gfX + " ");// this line shows error mentioned above in the question
      Serial.print("Accel Gforce(y)= "+ gfY + " ");// this line shows error mentioned above in the question
      Serial.print("Accel Gforce(z)= "+ gfZ + " ");// this line shows error mentioned above in the question
    }

this is a code of mpu6050.  Why am I getting this error and How Can I resolve it?

title: How can I fix this error "invalid operands of types 'const char [17]' and 'float' to binary 'operator+'"?

Answers: 1

body:
These lines give you errors, because you cannot simply add character arrays (aka c-strings) and floats together with the `+` operator. C/C++ is very strict, when it comes to variable types. The compiler does not know, how it should add these types together.

In other high level languages a string literal (characters enclosed by `"` in the source code) are more complex types, than c-strings. They mostly have various different methods and also an implementation of the `+` operator for adding a float number in human readable form. This complex type in the Arduino world is the `String` type. You can convert the float variable into a `String` and then add them together. But that's not the way, that you should do it. Strings on AVR based Arduinos (like Uno, Nano, ...) can be very evil due to the limited RAM. See Majenko's blog entry about [The Evils of Arduino Strings][1] for more information.

Instead you should just use multiple print statements. As Serial data is send out serially (one byte after another), it doesn't matter, if you put all the data to send in one print statement, or in multiple onces. So each of the offending lines can be converted to something like this:

    Serial.print("Gyro degree(x)= ");
    Serial.print(rtX);
    Serial.print(" ");

It does exactly, what your code does. But it will not produce an error, since the `Serial.print()` method is also implemented for using float arguments.

  [1]: https://hackingmajenkoblog.wordpress.com/2016/02/04/the-evils-of-arduino-strings/


body: I'm trying to communicate an RS232 device with an ESP32 (Heltec Wifi/LoRa 32 v2) my problem is that I don't receive any response from the device, doing some research, I'm thinking that the trouble can be the flow control because I don't use these pins and the modules I've used neither have these pins. Do you know a way to, at least, solder the DB9 pins to have a sort of flow control to communicate the devices?

title: Flow control between ESP32 and RS323 device

Answers: 1

body:
You could use ESP-IDF calls to setup your UART correctly for hardware serial communication on pin 4 and 5 (and perhaps also other pins).

In the sample below, you just have to:
- assign `UART_CLIENT_RTS` and `UART_CLIENT_CTS` to the pins of your need
- change `uart_config_t` to whichever parameters are relevant for your RS232 device
- set `flow_ctrl` to `UART_HW_FLOWCTRL_RTS`, `UART_HW_FLOWCTRL_CTS`, `UART_HW_FLOWCTRL_CTS_RTS` or `UART_HW_FLOWCTRL_MAX`

```
    #define BUFFER_SIZE 1024

    #define UART_CLIENT_TXD  (GPIO_NUM_4)
    #define UART_CLIENT_RXD  (GPIO_NUM_5)
    #define UART_CLIENT_RTS  (GPIO_NUM_?) // Set this
    #define UART_CLIENT_CTS  (GPIO_NUM_?) // Set this

    uart_port_t uartNum = UART_NUM_1;

    uart_config_t uart_config = { // Set this
        .baud_rate = 115200,
        .data_bits = UART_DATA_8_BITS,
        .parity    = UART_PARITY_DISABLE,
        .stop_bits = UART_STOP_BITS_1,
        .flow_ctrl = UART_HW_FLOWCTRL_CTS_RTS
    };

    uart_param_config(uartNum, &uart_config);
    uart_set_pin(uartNum, UART_CLIENT_TXD, UART_CLIENT_RXD, UART_CLIENT_RTS, UART_CLIENT_CTS);
    uart_driver_install(uartNum, BUFFER_SIZE * 2, 0, 0, NULL, 0);
```

Communication can be done with the various `uart_write_*` and `uart_read_*` methods as defined in the [documentation](https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/peripherals/uart.html).


body:
I'm using the Marlin 2.0.3 for a 3D printer project. I'd like to tear apart the code, but I don't see a #include to anything in the Marlin.ino, Configuration.h, Configuration_adv.h, nor Version.h.

If I use a verbose compilation, I see the ./src/HAL/HAL_AVR/HAL.cpp is the first thing it tries to include, but I don't see that writen in the code.

How does it know what to include?

Incase you can answer without downloading it:
Marlin.ino and Version.h is just comments.
Configuration.h and Configuration_adv.h are just a bunch of #defines.

Link to Marlin: https://github.com/MarlinFirmware/Marlin/releases/tag/2.0.3

title: Can't find a #include

Answers: 0


body:
I am working on an Arduino Uno Project of a car with two motors. The motor driver board is an L9110 H-Bridge. Here is how everything is connected:

[![Schematic][1]][1]

And here is the code I am trying to run:

```lang-c

//Define all the pins for the motors
#define motorPinA1 3  //A pin right motor
#define motorPinB1 5  //B pin right motor
#define motorPinA2 6 //A pin left motor
#define motorPinB2 9 //B pin left motor

//Movement functions
void stopCar();
void frwrd(int motorSpdRight, int motorSpdLeft);
void back(int motorSpdRight, int motorSpdLeft);

//Global Variables
int motorSpeedRight = 0;  //The speed of the right motor
int motorSpeedLeft = 0;   //The speed of the left motor

void setup() {
  //Movement
  pinMode(motorPinA1, OUTPUT);
  pinMode(motorPinB1, OUTPUT);
  pinMode(motorPinA2, OUTPUT);
  pinMode(motorPinB2, OUTPUT);

  //Serial Monitor for debugging
  Serial.begin(9600);

  motorSpeedLeft = 100;
  motorSpeedRight = 100;

  frwrd(100, 100);
  delay(2000);
  stopCar();
  delay(1000);

  back(100, 100);
  delay(2000);
  stopCar();
  delay(1000);
}

void loop() {

  Serial.print("Forward");
  Serial.print("\n");

  frwrd(motorSpeedRight, motorSpeedLeft);
  delay(2000);
  stopCar();
  delay(1000);

  back(motorSpeedRight, motorSpeedLeft);
  delay(2000);
  stopCar();
  delay(1000);

}

// functions we need to make the code run
void stopCar(){
    Serial.print("Stoping Car\n");
    // Put motor 1 in halt
    analogWrite(motorPinA1, 0);
    analogWrite(motorPinB1, 0);

    // Put motor 2 in halt
    analogWrite(motorPinA2, 0);
    analogWrite(motorPinB2, 0);
}

// For the farward direction A pins will be high
void frwrd(int motorSpdRight, int motorSpdLeft){
    // Put motor 1 (Right) in forward motion with speed = motor_spd
    analogWrite(motorPinA1, motorSpdRight);
    analogWrite(motorPinB1, 0);

    // Put motor 2 (Left) in forward motion with speed = motor_spd
    analogWrite(motorPinA2, motorSpdLeft);
    analogWrite(motorPinB2, 0);

    /*
    // Put motor 1 (Right) in forward motion
    digitalWrite(motorPinA1, HIGH);
    digitalWrite(motorPinB1, LOW);

    // Put motor 2 (Left) in forward motion
    digitalWrite(motorPinA2, HIGH);
    analogWrite(motorPinB2, LOW);
    */
}

// For the backward direction B pins will be high
void back(int motorSpdRight, int motorSpdLeft){
    // Put motor 1 (Right) in backward motion with speed = motor_spd
    analogWrite(motorPinA1, 0);
    analogWrite(motorPinB1, motorSpdRight);

    // Put motor 2 (Left) in backward motion with speed = motor_spd
    analogWrite(motorPinA2, 0);
    analogWrite(motorPinB2, motorSpdLeft);

    /*
    // Put motor 1 (Right) in backward motion
    digitalWrite(motorPinA1, LOW);
    digitalWrite(motorPinB1, HIGH);

    // Put motor 2 (Left) in backward motion
    digitalWrite(motorPinA2, LOW);
    digitalWrite(motorPinB2, HIGH);
    */
}
```
Pins 3, 5, 6 and 9 are PWM so I can `alalogWrite()` to them and control the speed of the motors. Code uploads fine but although both motors move forward normally motor 1 (on pins 3, 5) doesn't move backward. The strange thing is that if I use `digitalWrite` (the commented code in the two functions) instead everything works normally but the motors move in full speed so it's not usable for my project. I have tested all the pins in other projects and everything worked fine so I know my board is not faulty.

I have also taken some measurements with a multimeter while the code was running. In the forward motion, both pairs of pins measured 1.95V. In the backward motion, the problematic pins measured 0V.

Any help would be appreciated!!

  [1]: https://i.stack.imgur.com/XawMx.png

title: Problem with PWM pins on Arduino uno

Answers: 1

body:
Try different pins than 5 and 6, because those PWM generators share the timer with `delay()`, which I'd interpret as: You use `analogWrite()` to set the timer to fire every n microseconds to toggle your PWM signal  -- and then you call `delay(1000)`, which sets that same timer to fire in one second to continue the program.

Pins 10 and 11 do use a different timer, so try these.

Reference: https://www.arduino.cc/reference/en/language/functions/analog-io/analogwrite/

> "The PWM outputs generated on pins 5 and 6 will have
> higher-than-expected duty cycles. This is because of interactions with
> the millis() and delay() functions, which share the same internal
> timer used to generate those PWM outputs."


body:
This is my very first day in the community, please bear me until I make myself comfortable here.
Coming to my question,
I'm making a self Driving car.
My car instead of moving forward it moves on the left rigorously which makes the car go round and round.
Along with my arduino, I'm using the L298 bridge to control my motors.
The motors seem to work fine until put on the ground.
Can you guys help me with what could be the possible solution to this and make my car go forward.

    Here's my code :

        const int EnableL= 5;
    const int HighL = 6;  //Left side motors
    const int LowL = 7;

    const int EnableR= 10;
    const int HighR = 8;  //Right side motors
    const int LowR = 9;

    void setup() {
     pinMode(EnableL, OUTPUT);
     pinMode(HighL, OUTPUT);
     pinMode(LowL, OUTPUT);

     pinMode(EnableR,OUTPUT);
     pinMode(HighR, OUTPUT);
     pinMode(LowR, OUTPUT);

    }

    void Forward()
    {
      digitalWrite(HighL,HIGH);
      digitalWrite(LowL,LOW);
      analogWrite(EnableL, 255);

      digitalWrite(HighR,LOW);
      digitalWrite(LowR,HIGH);
      analogWrite(EnableR, 255);
    }

    void Backward()
    {
      digitalWrite(HighL,LOW);
      digitalWrite(LowL,HIGH);
      analogWrite(EnableL, 255);

      digitalWrite(HighR,HIGH);
      digitalWrite(LowR,LOW);
      analogWrite(EnableR, 255);
    }

    void loop() {
      Forward();

    }

Components used :

3 pack lithium ion cells at 12V to power L298 bridge

A 9v cell to power Arduino Uno

title: Motors would make the car go extreme left instead of forward (Self Driving car)

Answers: 0


body:
I've just started using Arduino and I'm having trouble getting my code right.

Here is the task I need to do.

 "Create a button read function
  Hint: the function header should be `int checkbutton ( void )`
in the loop function, add code such that if the button has been pressed (i.e. the checkbutton function
returns 1), a message is sent to the serial monitor with your username."

There are no errors in the code but nothing happens in the serial monitor when I press the LED button and it does not return 0 when i don't press the LED button.
Any sort of help would be appreciated!

Thanks!

    int Button = 15; //LED and output are on the same pin

    int last = 0;

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

    int button() {
      pinMode(Button, INPUT);

      int current = digitalRead(Button);

      if (current and not last) {
        delay(5);

        pinMode(Button, OUTPUT);

        Serial.print("Hey");
        return 1;
      }

      else {
        pinMode(Button, OUTPUT);

        current == last;

        return 0;
      }
    }

    void loop() {
      if (button >=0)
      {
        button();
      }

      else
      {
        ;
      }
    }

title: Displaying when Button has been pressed for LED and returning 1

Answers: 2

body: Your problem may only be that you are not calling the button function. Try changing `if (button >=0)` to `if (button() >=0)`.

body:
In your button() function, the line

    if (current and not last) {

is less common syntax. The more common equivalent is:

    if (current && !last) {

(see https://stackoverflow.com/questions/2376448/the-written-versions-of-the-logical-operators)

This line:

    current == last;

Has no effect and is incorrect. This ( “==“ ) is not an assignment but a comparison and does not do what you want it to do.

I also think you have this the wrong way around. You want to save the “last” button state to compare it with the current button state when you call `button()` the next time. So you would need to set “last” to the current button state, like this:

    last = current;

The next time you call `button()`, “last” contains the previous button state, so your comparison to the current button state will work.

And I think your button detection code would work better if you set `last = current` each time you call button(), whether a button has been pressed or not. Otherwise your code would repeatedly keep printing “Hey” until you stop pushing the button (unless that’s what you want). Like so:

    int button() {
      pinMode(Button, INPUT);

      int current = digitalRead(Button);

      if (current &&  !last) {
        ...
        ...

        Serial.print("Hey");
        last = current; // Insert here
        return 1;
      }

      else {
        pinMode(Button, OUTPUT);
        ...

(This has not been tested but should give you a general idea).


body:
This is my first time working with an arduino and I'm having some issues when trying to copy a program I found online on my Nano.

Basically, my project consists in a pulse sensor that sends the pulse information to the arduino and then to the hc-05 Bluetooth module so my phone can receive this information in real-time.

On my nano: D2 receives the output of the sensor, D8 and D9 are connected to pins RX/RT on HC05 and D13 has a LED connected to it.

Now here's the thing, I really don't know much about this and the code I found uses different pins from the ones I'm using.

The LED keeps blinking and isn't synchronized with the sensor output, when the led blinks I receive a response in the Bluetooth serial app but I would like to synchronize the heart sensor with the led so than I can receive the pulses on my phone. I've been trying to solve this but I still can't find a solution.

Full code can be found at
<https://www.instructables.com/id/Pulse-Sensor-With-Bluetooth-and-Arduino/>

Here's part of my code

```
//bluetooth
#include <SoftwareSerial.h>// import the serial library

SoftwareSerial Genotronex(8, 9); // RX, TX
int ledpin=13; // led on D13 will show blink on / off
int BluetoothData; // the data given from Computer

//  Variables
int pulsePin = 2;                 // Pulse Sensor purple wire connected to analog pin 0
int blinkPin = 13;                // pin to blink led at each beat
int fadePin = 5;                  // pin to do fancy classy fading blink at each beat
int fadeRate = 0;                 // used to fade LED on with PWM on fadePin

// Volatile Variables, used in the interrupt service routine!
volatile int BPM;                   // int that holds raw Analog in 0. updated every 2mS
volatile int Signal;                // holds the incoming raw data
volatile int IBI = 600;             // int that holds the time interval between beats! Must be seeded!
volatile boolean Pulse = false;     // "True" when User's live heartbeat is detected. "False" when not a "live beat".
volatile boolean QS = false;        // becomes true when Arduoino finds a beat.

// Regards Serial OutPut  -- Set This Up to your needs
static boolean serialVisual = true;   // Set to 'false' by Default.  Re-set to 'true' to see Arduino Serial Monitor ASCII Visual Pulse

void setup(){
  pinMode(blinkPin,OUTPUT);         // pin that will blink to your heartbeat!
  pinMode(fadePin,OUTPUT);          // pin that will fade to your heartbeat!
  Serial.begin(115200);             // we agree to talk fast!
  interruptSetup();                 // sets up to read Pulse Sensor signal every 2mS
   // UN-COMMENT THE NEXT LINE IF YOU ARE POWERING The Pulse Sensor AT LOW VOLTAGE,
   // AND APPLY THAT VOLTAGE TO THE A-REF PIN
//   analogReference(EXTERNAL);
Genotronex.begin(9600);
  Genotronex.println("Bluetooth On please press 1 or 0 blink LED ..");
  pinMode(ledpin,OUTPUT);
}

//  Where the Magic Happens
void loop(){

    serialOutput() ;

  if (QS == true){     //  A Heartbeat Was Found
                       // BPM and IBI have been Determined
                       // Quantified Self "QS" true when arduino finds a heartbeat
        digitalWrite(blinkPin,HIGH);     // Blink LED, we got a beat.
        fadeRate = 255;         // Makes the LED Fade Effect Happen
                                // Set 'fadeRate' Variable to 255 to fade LED with pulse
        serialOutputWhenBeatHappens();   // A Beat Happened, Output that to serial.
        QS = false;                      // reset the Quantified Self flag for next time
       }
      else {

      digitalWrite(blinkPin,LOW);            // There is not beat, turn off pin 13 LED
      }

   ledFadeToBeat();                      // Makes the LED Fade Effect Happen
  if (Genotronex.available()){
BluetoothData=Genotronex.read();
   if(BluetoothData=='1'){   // if number 1 pressed ....
   digitalWrite(ledpin,1);
   Genotronex.println("LED  On D12 ON ! ");
   }
  if (BluetoothData=='0'){// if number 0 pressed ....
  digitalWrite(ledpin,0);
   Genotronex.println("LED  On D12 Off ! ");
  }
}
  delay(20);                             //  take a break
}```

title: First time working with arduino, need help adapting project from UNO to NANO

Answers: 1

body:
First: There is no need to change pin assingments, when changing from Uno to Nano. They use the same microcontroller and have the same pins.

You have set `pulsePin` to 2, which corresponds to pin D2. But the pulse sensor gives you an analog signal. D2 is not capable of measuring analog voltages, it can only measure digital voltages. Meaning you need to use one of the analog pins, A0 to A7, so use one of these pins in the declaration of `pulsePin`.

The reason for this is, that the microcontroller uses an extra peripheral device included in it for measuring analog voltages: the ADC (Analog to Digital Converter). It can only be connected to a limited number of pins (internally via a multiplexer). That also means, that you can only measure the analog voltage at one pin at a time.


body:
I am trying to create a program when the camera capture the servo will rotate in 90 degrees continously, but my code will stop in `print output 2` any idea to run the servo continously?

Here's the Code

    import numpy as np
    import cv2
    import serial
    import struct
    import time

    ser = serial.Serial('COM11',9600)

    x=0

    while(True):

     # Capture frame-by-frame
        cap = cv2.VideoCapture(0)
        #framerate = cap.get(5)
        ret, frame = cap.read()
        cap.release()
        # Our operations on the frame come here

        filename = 'C:/Users/DELVO/Desktop/tryTest/bruises/main/images' +  str(int(x)) + ".png"
        x=x+1
        cv2.imwrite(filename, frame)
        print(ser.write(x))
        time.sleep(5)
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break

    # When everything done, release the capture
    cap.release()
    cv2.destroyAllWindows()

Arduino Code

    #include <Servo.h>
    int data_x = 0;
    int data_y = 0;
    int data[1];
    Servo myservo_x;
    Servo myservo_y;// create servo object to control a servo
    // twelve servo objects can be created on most boards

    int pos = 0;    // variable to store the servo position

    void setup() {
      Serial.begin(9600);
      myservo_x.attach(7);  // attaches the servo on pin 9 to the servo object
      myservo_y.attach(10);
      myservo_x.write(90);
      myservo_y.write(90);
    }

    void loop() {
      while (Serial.available() >= 2) {
        //    data_x=Serial.read();
        //    data_y=Serial.read();
        for (int i = 0; i < 2; i++) {
          data[i] = Serial.read();
        }

        myservo_x.write(data[0]);
        myservo_y.write(data[1]);

        Serial.println(data[0]);
        Serial.println(data[1]);
      }

    }

title: Run servo when image is capture

Answers: 1

body:
is the arduino code giving error because you have initialized the array data with length of 1 (```int data[1];```) and in the for loop the length is exceeding the allocated length of the string: ```for (int i = 0; i < 2; i++) {
  data[i] = Serial.read();
                       }```


body:
Here's the code:

    void loop() {
      while (1 == 1) {
        ObsLeft();
        while (SeeLeft < 50 || SeeLeft == 50) {
          Urong();
          ObsLeft();
          if (SeeLeft > 50) {
            Hinto;
            break;
          }
        }
      }
    }

`ObsLeft()` analogReads the Infrared sensor input and Serial.prints it

`Urong()` makes the sumobot go backward

`Hinto()` stops the robot

`SeeLeft` is the analog value given by the Line Sensor (in my experience, white is 42, black is 800+)

The Problem:

When I run the program with the sensor seeing White, it makes the robot go backward, but when I move the bot so that the sensor sees Black, it still keeps going.

When I run the program with the sensor seeing Black, it does nothing.

title: While Loop does not stop when condition is false

Answers: 0


body:
I have a project with an [Arduino Nano 33 BLE Sense](https://store.arduino.cc/arduino-nano-33-ble-sense-with-headers). My project is working great, but I need to transition it to battery power, and I'm having a bit of confusion about exactly what's required.

I have a small 3.7V Li-ion battery I'd like to use (similar to [this one](https://www.sparkfun.com/products/13853) {0}) if possible.

I have read what seems to be some conflicting information, so I'd like to see which of the following are true:

* I can power the Arduino directly from the 3.3v pin? I'm suspicious of this advice since on the datasheet the 3.3v pin is marked output only. There's a note on the product page that says:

> Note: for ultra low-power functionality, you should cut the 3V3 jumper on the back of the board, and use an external battery at 3V3.

Is this something I should do? It seems difficult to reverse, I'm worried I might break my project.

* I can power the Arduino directly from the VIN pin? This again seems to contradict the datasheet, which says the VIN pin can only handle 4.5 - 21V. 3.7V is less than this.

* I could use a Step-up DC-DC transformer - like [this](https://www.ebay.co.uk/itm/Mini-3V-3-3V-3-7V-5V-9V-to-12V-Step-Up-Boost-Converter-Module-Voltage-Regulator/274297023384?hash=item3fdd606b98:g:pe4AAOSwD39eYUDV) {1}? I'd rather not wait for shipping from China.

Furthermore, I'd like to be able to charge the battery, so if I use a charging board like [this one](https://www.ebay.co.uk/itm/4-2V-5V-1A-Micro-USB-Li-ion-Battery-Charger-TP4056-Protection-Chip-Lithium-ion/192956632451?hash=item2ced1c8d83:m:m6FPVNrEa1Qnj21RHGsyZ7g) {2}, would that just work?

I don't want to connect the battery anywhere it might not be welcome for the risk of frying anything. Any help would be appreciated.

<hr>

Link references (in case ebay listings go away):

0: Lithium Ion Battery - 110mAh

[![enter image description here][1]][1]

1: Mini 3V 3.3V 3.7V 5V 9V to 12V Step Up Boost Converter Module Voltage Regulator

[![enter image description here][2]][2]

2: 4.2V 5V 1A Micro USB Li-ion Battery Charger TP4056 Protection Chip Lithium-ion

[![enter image description here][3]][3]

  [1]: https://i.stack.imgur.com/wpYl7.jpg
  [2]: https://i.stack.imgur.com/P6wLz.jpg
  [3]: https://i.stack.imgur.com/ASvKx.jpg

title: Arduino Nano 33 battery power/charging

Answers: 1

body:
The VIN (and the USB) goes into a 3.3V switching regulator. This has a minimum input voltage of 4.5V.

You isolate the output of that regulator from the rest of the circuit by cutting that one link (which is easy to re-solder). You are then free to feed 3.3V from your own power source directly into the board.

Yes, if you provide more than 3.3V you are liable to damage the board (note that a Li-Poly can be around 4.2V when fully charged).

You need to take your battery power and feed it through a nice efficient switching voltage regulator that has a low enough "dropout" voltage to allow good use from the battery. Note that many devices "rated" at 3.3V will also work much lower. For example:

* Nina-B3 series module will run at down to 1.7V.
* The APDS-9960 will operate down to 2.4V.
* The HTS221 will run at down to 1.7V.
* MP34DT06J can go as low as 1.6V.
* LSM9DS1 can run from 1.9V.
* LPS22 is 1.7V minimum

So it could be good to reduce your power to 2.5V instead of 3.3V to give more life from the battery. You should check each of the components in the both the device schematic and the rest of your circuit (by reading the datasheets) to find the highest "minimum" voltage they will work on.


body: I have six BMP180 sensors for measuring temperature and pressure. The problem is that I can get the value from one sensor but I need values from all six sensors using a single Arduino Mega board. How can I do that? I have already tried powering each sensor with digitalWrite but that didn't work. If you have a solution, can you also provide the code for that?

title: How to switch between multiple BMP180 sensors?

Answers: 2

body:
The BMP180 uses the I2C bus and you cannot simply turn off the device, since that can block the I2C bus. Also it has only one, not changeable address. Thus you would need one I2C bus for every BMP180.

So know you have 2 ways to go:

- You could use a Software I2C library and define one I2C port for each BMP. That would use 12 digital pins and you need to find a fitting library, that supports multiple instances. Due to the timed nature of the I2C bus, you most likely will only be able to service one bus at a time.

- You could buy a multiplexer chip for both signal lines. Then you could switch the SCL and SDA lines to each BMP. For that you need the multiplexer chips, 2 pins for I2C and 3 digital pins for input of the multiplexer chips (assumes an 8-channel multiplexer)

body: If you have n-MOSFETs available, a simple multiplex solution would be: SCL directly from master to all slaves. SDA from master to Source of MOSFET (for each slave one MOSFET), Drain of MOSFET with pull-up resistor (e.g. 4.7k) will be the SDA signal. Gate of MOSFET to select slaves (active <-> Gate=high level). Make sure your MOSFET turns on based on your used voltage levels.


body:
#include <Arduino.h>
    #endif
    #include <ESP8266WiFi.h>
    #define watersensor D2
    const char* ssid = "pooja";
    const char* password = "ranip2780@";
    WiFiServer server(301);
    IPAddress ip(192, 168, 43, 67);
    IPAddress gateway(192, 168, 43, 1);
    IPAddress subnet(255, 255, 255, 0);
    IPAddress dns(192, 168, 43, 1);
    void setup() {
      Serial.begin(115200);
      delay(10);

      Serial.println();
      Serial.println();
      Serial.print("Connecting to ");
      Serial.println(ssid);

      WiFi.config(ip, dns, gateway, subnet);
      WiFi.begin(ssid, password);
      while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.print(".");
      }
      Serial.println("");
      Serial.println("WiFi connected");

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

      Serial.print("Use this URL to connect: ");
      Serial.print("http://");
      Serial.print(WiFi.localIP());
      Serial.println("/");
    }

    void loop()
    {
      // Check if a client has connected
      < WiFiClient client = server.available();
      if (!client) {
        return;
      }

      // Wait until the client sends some data
      Serial.println("new client");
      while (!client.available()) {
        //    delay(1);
        client.setNoDelay(1);
      }

      String request = client.readStringUntil('\r');
      Serial.println(request);
      client.flush();

      client.println("HTTP/1.1 200 OK");
      client.println("Content-Type: text/html");
      client.println("");
      client.println("");
      client.println("");
      client.println("<meta http-equiv='refresh' content='20'>");
      client.println("<title>WATER OVERFLOW ALARM WITH ONLINE UPDATES</title>");
      client.println("");
      client.println("");
      client.println("

");
      client.println("
");
      client.println("
");
      client.println("WATER OVERFLOW ALARM WITH ONLINE UPDATES
");
      client.println("USING NODEMCU 1.0 BOARD");
      client.println("
	");
      client.println("
");

      if (digitalRead(watersensor) == LOW)
      {
        client.println("<button style='background-color:red;width:200px;height:100px'>FULL LEVEL ALERT</button>
");
      }
      else
      {
        client.println("<button style='background-color:gray;width:200px;height:100px'NOT FULL</button>
");
      }

      client.println("
	");
      client.println("
");
      client.println("

");
      client.println("");
      client.println("
");
      client.println("

");
      client.println("LEGENDS:  <button style='background-color:gray;width:100px;height:50px'><font color='white'NOT FULL</button>");
      client.println("WATER LEVEL IS BELOW SENSOR.
");
      client.println("
<button style='background-color:red;width:100px;height:50px'>FULL LEVEL ALERT</button> WATER LEVEL IS ALREADY FULL.");
      client.println("

");
      client.println("");
      client.println("");
      delay(1);
      Serial.println("Client disconnected");
      Serial.println("");
      delay(500);
    }

title: On compiling I get #endif without #if error. Here is the code. Please help!

Answers: 1

body:
The Arduino IDE gives you a massive clue

    Arduino: 1.8.12 (Windows 10), Board: "Arduino Uno"

    sketchX:2:2: error: #endif without #if

     #endif

      ^~~~~

    sketchX:3:10: fatal error: ESP8266WiFi.h: No such file or directory

     #include <ESP8266WiFi.h>

              ^~~~~~~~~~~~~~~

    compilation terminated.

    exit status 1
    #endif without #if

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

That's pointing at lines #2 & #3 in the sketch as having the error. So we fix those and try again

    //#endif

I'll also install the ESP8266 stuff since that's missing on my new laptop.

    Arduino: 1.8.12 (Windows 10), Board: "Generic ESP8266 Module, 80 MHz, Flash, Legacy (new
    can return nullptr), All SSL ciphers (most compatible), dtr (aka nodemcu), 26 MHz, 40MHz,
    DOUT (compatible), 1MB (FS:64KB OTA:~470KB), 2, nonos-sdk 2.2.1+100 (190703), v2 Lower
    Memory, Disabled, None, Only Sketch, 115200"

    C:\Users\winuser\Arduino\sketchX\sketchX.ino: In function 'void loop()':

    sketchX:42:3: error: expected primary-expression before '<' token

       < WiFiClient client = server.available();

       ^

    sketchX:42:16: error: expected primary-expression before 'client'

       < WiFiClient client = server.available();

                    ^

    sketchX:42:16: error: expected ';' before 'client'

    sketchX:43:8: error: 'client' was not declared in this scope

       if (!client) {

            ^

    sketchX:49:11: error: 'client' was not declared in this scope

       while (!client.available()) {

               ^

    sketchX:54:20: error: 'client' was not declared in this scope

       String request = client.readStringUntil('\r');

                        ^

    sketchX:4:21: error: 'D2' was not declared in this scope

     #define watersensor D2

                         ^

    C:\Users\winuser\Arduino\sketchX\sketchX.ino:79:19: note: in expansion of
    macro 'watersensor'

       if (digitalRead(watersensor) == LOW)

                       ^

    exit status 1
    expected primary-expression before '<' token

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

So all in all it's simple to use the messages that the IDE gives you to find your error and correct them, working from top to bottom in your sketch. It's not something that needs to be posted on StackExchange until you've corrected the basics.


body:
hi everybody im working in a software for a pcb based in the chip ATmega2560
im use this with Xbee in API MODE, so im driving short string data and long string data.
with the short data i dont have any problem but my long data is of 78bytes.

so the serial event only show me 63 bytes and i dont find reason for it.

this is the complete block:

    void serialEvent2(){
    while (Serial2.available()){
        frameReceived[n] = Serial2.read();
        Serial.print("  ");
        Serial.print(frameReceived[n], HEX);
        n++;
        //Serial.print("\t" + String(n));
       /* if (n == (frameReceived[1]+frameReceived[2]) + 4){
            Serial.println();
            Serial.println((frameReceived[1]+frameReceived[2])+4);
            Serial.println("IF");
        }*/
        if ( n == 3 ){
            lfr = frameReceived[2] + 4;
        }

        if (n == lfr){
            receivedDone = true;
            Serial.println();
            Serial.print("[INFO] N: ");
            Serial.println(n);
            Serial.print("[INFO] LFR: ");
            Serial.println(lfr);
        }

        if (receivedDone){
            clearValuesToReceiveFrame();
            processFrame();
            receivedDone = false;
        }
    }

    Serial.println();
    Serial.println("[While]n:");
    Serial.println(n);
    Serial.println("[While]LFR: ");
    Serial.println(lfr);
    n=0;
    lfr=0;

}

in this block i learn to the programe that the posion 2 in my array is the lenght of the frame in API MODE:

            if ( n == 3 ){
            lfr = frameReceived[2] + 4;
        }

here i learn to the programe that the n number of bytes have to equal lfr (lengh of the data). if this is true my flags gonna work.

            if (n == lfr){
            receivedDone = true;
            Serial.println();
            Serial.print("[INFO] N: ");
            Serial.println(n);
            Serial.print("[INFO] LFR: ");
            Serial.println(lfr);
        }

        if (receivedDone){
            clearValuesToReceiveFrame();
            processFrame();
            receivedDone = false;
        }
    }

the problem is that the program only rad 63 n number and my LFR is diferent so the flags never going true, n numbers ever is 63 from 78 real bytes :(
please help me.

title: serialEvent only read 63Bytes and this is not the complete data incoming

Answers: 0


body:
I have a project where we have to read the weight from an Ohaus Defender 3000 by using an Arudino Mega 2560 and a RS-232 shield. Right now we have the RX of the Arduino to the TX of the shield, and the TX of the Arduino to the RX of the shield. In our code, we get both the RX and the TX lights of the shield to light up but we can't receive data from the scale into the Arduino. Could someone help me understand what is going on or am I doing something wrong. This is the following code that I used for the Arduino. I found this code at: https://arduino.stackexchange.com/questions/48969/reading-arduino-serial-input. Thank you for the help in advance.

    #define HWSERIAL Serial1

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

    void loop() {
      int incomingByte;

      if (Serial.available() > 0) {
        incomingByte = Serial.read();
        Serial.print("USB received: ");
        Serial.println(incomingByte, DEC);
        //HWSERIAL.print("USB received:");
        //HWSERIAL.println(incomingByte, DEC);
      }
      if (HWSERIAL.available() > 0) {
        incomingByte = HWSERIAL.read();
        Serial.print("UART received: ");
        Serial.println(incomingByte);
        //HWSERIAL.print("UART received:");
        //HWSERIAL.println(incomingByte);
      }
    }

title: Reading data from an Ohaus Defender 3000 with a RS-232 shield

Answers: 1

body:
Can you provide a photo of your hardware setup, and the full code for your project?  Please use the "code sample" formatting widget (the "{}" icon) to surround the code section, and look at the preview to make sure the code is formatted correctly.

Just a guess, but you may have the TX/RX lines to the scale connected to 'Serial' on the Mega instead of 'Serial1'. That would definitely cause problems


body:
Attempting to make gps unit with screen. GPS unit communicates over serial (Adafruit Ultimate GPS Breakout) and I can get GPS data through USB to my pc with Adafruit GPS library softwareserial examples. The screen communicates over I2C (Sunfounder OLED-SSD1306 Module) and I can get display with Adafruit SSD1306 examples. However I cannot get both to happen simultaneously. Board is Adafruit Metro Mini 5v 16MHZ. GPS is using pin 8 for TX and pin 9 for RX. Display is using A4 for SDA and A5 for SCL.

If "Adafruit_GPS GPS(&mySerial);" is not commented the screen will not display anything. If it is commented the screen displays just fine. How do I get both to function simultaneously?

    #include <Wire.h>
    #include <Adafruit_GFX.h>
    #include <Adafruit_SSD1306.h>
    #define OLED_RESET     -1
    #define SCREEN_WIDTH 128
    #define SCREEN_HEIGHT 64
    Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
    #include <Adafruit_GPS.h>
    #include <SoftwareSerial.h>
    SoftwareSerial mySerial(8, 9);
    Adafruit_GPS GPS(&mySerial);

    void setup() {
      if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
        for(;;);
      }
      display.display();
      delay(2000);
      display.clearDisplay();
      display.drawPixel(10, 10, SSD1306_WHITE);
      display.display();
      delay(2000);
      testdrawchar();
    }

    void loop() {
    }

    void testdrawchar(void) {
      display.clearDisplay();

      display.setTextSize(1);
      display.setTextColor(SSD1306_WHITE);
      display.setCursor(0, 0);
      display.cp437(true);

      for(int16_t i=0; i<256; i++) {
        if(i == '\n') display.write(' ');
        else          display.write(i);
      }

      display.display();
      delay(2000);
    }

title: I2C and softwareserial

Answers: 1

body: The problem was indeed running out of memory (as suggested by Juraj). After finding smaller libraries I was able to get it to work together just fine.


body:
I have a system where an RFID tag can be checked and Its individual 4byte UID will be printed. My task is to check if subsequent tags have the same UID and if not, print “access denied”. I'm assuming i need to use `const char` but I'm not sure. I get an error at `if (myrfid.serNum[i] == ID)` saying comparison between pointers and integers are forbidden.
Any sort of clarity would be appreciated, thanks!

(Code is only a section from the for loop)

```c++
void loop()
{
    int i;
    const char ID[] = "111 11 11 11";

    cardpresent = myrfid.isCard();

    if (cardpresent && ! lastcardpresent)
    {
        if (myrfid.readCardSerial())
        {
            for (i = 0; i < 4; i++)
            {
                if (myrfid.serNum[i] == ID)
                {
                    Serial.print("Acess granted ");
                }
                else
                {
                    Serial.print("Acess not granted ");
                }
            }
        }
        Serial.printf("= ", myrfid.serNum[i]);
    }
    Serial.print("\n");

    // ...
}
```

title: Matching incoming data with a variable

Answers: 1

body:
The accepted way to initialize an array in C follows this example:

    const char ID [] = {111, 11, 11, 11};

You can read more about it [here][1].

You later use an array name ("ID") with no index ("ID[0]").  The C compiler assumes the programmer who uses an array name with no index is interested in the memory address of the first element of the array.  But you wanted the value in that memory location.  So you should use the array name with the appropriate index.  Guessing, it would appear you intended to use "ID[i]" in the above code fragment.

  [1]: https://www.programiz.com/c-programming/c-arrays