text:
Two sensors on same ESP-32 board
Need some help on the project I'm currently developing.
I have 3 YF-B2 sensors that I need to connect to the same ESP-32 board and read the data from the sensors and send it via MQTT.
I had it working for 1 sensor but now I want to add the other two and keep sending the messages via MQTT but now with 3 sensors and each with its different value.
Below is the code I have where I added the flow_frequency2/3 and flowsensor2/3 but now the code does not work and I do not get the messages via MQTT.
Can anybody help me out on this?
#include <PubSubClient.h>
#include <EEPROM.h>

/****** Replace the next variables with your SSID/Password combination ********/
const char* ssid = "xxx";
const char* password = "xxx";

/****** Add your MQTT Broker IP address, example: ********/
const char* mqtt_server = "xxx.com";
const char* mqtt_user = "aaa";
const char* mqtt_pass = "aaa";
const char* input_topic = "teste/xxxx/in";
const char* output_topic = "teste/xxxx/out";

/****** FLUXO DE ÁGUA-YF-B2 ********/
volatile int flow_frequency1; // Measures flow sensor pulses
volatile int flow_frequency2; // Measures flow sensor pulses
volatile int flow_frequency3; // Measures flow sensor pulses
unsigned int l_hour; // Calculated litres/hour
unsigned char flowsensor1 = 34; // Sensor Input
unsigned char flowsensor2 = 35; // Sensor Input
unsigned char flowsensor3 = 32; // Sensor Input
unsigned long currentTime;
unsigned long cloopTime;

WiFiClient espClient;
PubSubClient client(espClient);
long lastMsg = 0;
char msg[50];
int value = 0;

void flow () { // Interrupt function
  flow_frequency1++;
  flow_frequency2++;
  flow_frequency3++;
}

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

  setup_wifi();
  client.setServer(mqtt_server, 1883);
  client.setCallback(callback);

  pinMode(flowsensor1, INPUT);
  pinMode(flowsensor2, INPUT);
  pinMode(flowsensor3, INPUT);
  digitalWrite(flowsensor1, HIGH); // Optional Internal Pull-Up
  digitalWrite(flowsensor2, HIGH); // Optional Internal Pull-Up
  digitalWrite(flowsensor3, HIGH); // Optional Internal Pull-Up
  attachInterrupt(34, flow, RISING);
  attachInterrupt(35, flow, RISING);
  attachInterrupt(32, flow, RISING);// Setup Interrupt
  sei(); // Enable interrupts
  currentTime = millis();
  cloopTime = currentTime;
}

void loop() {
  if (!client.connected()) {
    reconnect();
  }
  client.loop();

  long now = millis();
  if (now - lastMsg > 5000) {
    lastMsg = now;

    if (digitalRead(flowsensor1) == HIGH) {
      // Pulse frequency (Hz) = 7.5Q, Q is flow rate in L/min.
      l_hour = (flow_frequency1 * 60 / 7.5); // (Pulse frequency x 60 min) / 7.5Q = flowrate in L/hour
      flow_frequency1 = 0; // Reset Counter

      String water = String(l_hour);

      Serial.print("Water flow of sensor 1 is: " + water + " L/hour");
      water = water + " , waterflow1";
      client.publish(output_topic, water.c_str());
    }

    if (digitalRead(flowsensor2) == HIGH) {
      // Pulse frequency (Hz) = 7.5Q, Q is flow rate in L/min.
      l_hour = (flow_frequency2 * 60 / 7.5); // (Pulse frequency x 60 min) / 7.5Q = flowrate in L/hour
      flow_frequency2 = 0; // Reset Counter

      String water = String(l_hour);

      Serial.print("Water flow of sensor 2 is: " + water + " L/hour");
      water = water + " , waterflow2";
      client.publish(output_topic, water.c_str());
    }

    if (digitalRead(flowsensor3) == HIGH) {
      // Pulse frequency (Hz) = 7.5Q, Q is flow rate in L/min.
      l_hour = (flow_frequency3 * 60 / 7.5); // (Pulse frequency x 60 min) / 7.5Q = flowrate in L/hour
      flow_frequency3 = 0; // Reset Counter

      String water = String(l_hour);

      Serial.print("Water flow of sensor 3 is: " + water + " L/hour");
      water = water + " , waterflow3";
      client.publish(output_topic, water.c_str());
    }

  }
}

void setup_wifi() {
  delay(10);
  // We start by connecting to a WiFi network
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);

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

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

void callback(char* topic, byte* message, unsigned int length) {
  Serial.print("Message arrived on topic: ");
  Serial.print(topic);
  Serial.print(". Message: ");
  String messageTemp;

  for (int i = 0; i < length; i++) {
    Serial.print((char)message[i]);
    messageTemp += (char)message[i];
  }
  Serial.println();

  // Feel free to add more if statements to control more GPIOs with MQTT

  // If a message is received on the topic esp32/output, you check if the message is either "on" or "off".
  // Changes the output state according to the message
  if (String(topic) == input_topic) {
    Serial.print("Changing output to ");
    if (messageTemp == "on") {
      Serial.println("on");
      //digitalWrite(ledPin, HIGH);
    }
    else if (messageTemp == "off") {
      Serial.println("off");
      //digitalWrite(ledPin, LOW);
    }
  }
}

void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Attempt to connect
    if (client.connect("ESP8266Client", mqtt_user, mqtt_pass)) {
      Serial.println("connected");
      // Subscribe
      client.subscribe(input_topic);
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}
 ´´´

use an array for the flow sensor pins ... use flowsensor[1] instead of flowsensor1 ... then you can use a for loop to iterate through the sensor setup and sensor read


text:
working with ultrasonic sensors
I have a little problem dealing with ultrasonic sensor
I want a simple thing , when the sensor read High pulse then after it low pulse , turns on the led
so I try to make it with a 5cm distance and a flag , but it's dose not work
help me please!
    #define echoPin 5
    #define trigPin 7
    int GREEN = 2;
    int YELLOW = 3;
    int RED = 4;
    int pos = 0;
    int flag = 0 ;
    long duration;
    int distance;
    void setup() {

  // put your setup code here, to run once:
    pinMode(GREEN, OUTPUT);
    pinMode(YELLOW, OUTPUT);
    pinMode(RED, OUTPUT);
    pinMode(trigPin, OUTPUT); // Sets the trigPin as an OUTPUT
    pinMode(echoPin, INPUT); // Sets the echoPin as an INPUT
     }

    void loop() {

    ultra();

    if ( distance <= 5 && flag == 0)
    {//H
      flag = 1 ;}
    } //high pulse (When the distance <=5)

    if ( distance >5 && flag == 1)
    {//L
      red_light(); }

    }//the led should turned on when low pulse appears (When the distance >5)

    void red_light()
    { digitalWrite(GREEN, LOW);
    digitalWrite(YELLOW, LOW);
    digitalWrite(RED, HIGH); }

    void ultra()
    { digitalWrite(trigPin, LOW);
    delayMicroseconds(2);
    digitalWrite(trigPin, HIGH);
    delayMicroseconds(10);
    digitalWrite(trigPin, LOW);
    duration = pulseIn(echoPin, HIGH);
    distance = duration*0.034/2; }

//this is my code

I don't quite understand, what you are trying to do here. So the red LED should light up, when the distance gets lower than 5cm. But what should then happen? Should it stay on forever? Should it go off, when the distance gets higher than 5cm?

no , the red led should light up when( distance gets lower than 5cm and then after that gets greater than 5cm ) , I try to turned in the led after I get ( a HIGH signal then LOW)

and yes I want it turned on forever . can u understand me now ?

why do you have two closing braces for the first if loop in the  void() function?

Yes, now that is clear. Can you please give a detailed description, what actually happens (instead of the "it doesn't work) with your code? Or do you get an error during compilation? If yes, please provide the full error message. PS: You use the terms HIGH signal and LOW signal in a wrong way, which is a bit confusing. HIGH and LOW are about the digital signal on the pin, not about the measured pulse length. So you want to trigger your code, when the pulse length walks around the mark for 5cm. You don't want to trigger it after a LOW signal.

what actually happens with this code  is  when I put something near the sensor <= 5 , the led is on without i removed the thing , but i want the led on ehen i put then removr the thing , how i should do this ?

@goodarduinocode it's a syntax error, but it's not the problem hear

what actually happens with this code is when I put something near the sensor <= 5 , the led is on without i removed the thing , but I want the led on when I put then remove the thing

Here is my theory on what happens here. You can confirm it by using one of the solutions, that I will explain below.
Currently your code is measuring the distance as fast as it can. The measurement is what takes the longest time in one iteration of the loop() function. Thus you get many many measurements per second. But such distance measurements are always noisy, meaning that the values change randomly in a specific range. When you put the object in front of the sensor, you expect the values to just go down, but actually they are sometimes rising again for 1 or 2 values because of the noise. So the measured values might look something like this (only imagined for making the point; not real values):
5.4 --> 5.2 --> 4.99 --> 5.001 --> 4.89 --> 4.90 --> 4.5

Overall the values go down, but you are comparing always the current value with the fixed threshold of 5cm. When the noise just raises the value again, while you pass 5cm, you will get a false "put and removed again" outcome. At the probability  of the noise doing that is really high, since you measure that often and ultrasonic sensors are not accurate down to millimeters. You could even have the distance pass 5cm multiple times due to the noise.
There are some possibilities to reduce noise or to handle it.

Hysteresis: The first, that I would implement here is hysteresis. That means, that you set the "put" distance different than the "remove" distance. For example you could use 5cm as the distance to register, that the object is put in front of the sensor, but then you wait for the distance to go above 7cm to actually treat the object as "removed". You need to choose the difference between the distances larger than the noise (you can find that out via experimenting). This principle is also used directly with noisy digital signals on the Arduinos input pins. An Arduino Uno will treat voltages above about 2.6V as digital 1 (HIGH signal), and a value below 2.1V as digital 0 (LOW signal) (taken from the datasheet of the Atmega328P, which is the microcontroller on an Arduino Uno, while assuming the controller running on 5V like in an Arduino Uno). In electrical terms this is called a Schmitt-Trigger.
For implementing this, you can just change the threshold values in your if statements.

You can reduce the noise by always measuring multiple times in a row and then calculating the mean value from it. Since a part of the noise is random, you can smoothe out this part a bit through taking the mean. That also reduces your time resolution, but in such a simple use case that mostly doesn't matter that much.

If the reaction time doesn't matter that much, you could reduce the frequency of measurements, so that subsequent distance measurements are already to far away from each other for the noise to create false triggers. This is worse than the other solutions, since it also depends on how fast you put the object in front of the sensor, but it is really easy to implement (just a simple delay() call, or better using millis() like in the BlinkWithoutDelay example for non-blocking code)

I would first implement the hysteresis. Then, if the difference in distances, that you need for it to work good, is too big for you, you can take the mean of multiple value to reduce the noise.

And just for protocol, as it already was said in the comments: Your first if statement has an extra closing bracket } which should not be there.

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

sort: votes


text:
Problem with a class? SHT21 library
I am using ESP32 and SHT21 temp+humidity sensor but while compiling the code I get the following error:
variable "SHT21" is not a type name

I see an SHT21 class defined in the SHT21.cpp file in the library folder. I don't know much about classes so could you please tell what is wrong with the SHT21 class in this case?
Here is the link to the library:
https://github.com/markbeee/SHT21
Sketch:
#include <Arduino.h>

#include <Wire.h>
#include "SHT21.h"

SHT21 SHT21;

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

void loop()
{
  Serial.print("Humidity(%RH): ");
  Serial.print(SHT21.getHumidity());
  Serial.print("     Temperature(C): ");
  Serial.println(SHT21.getTemperature());

  delay(1000);
}

Don't name your instance the same as the class. It confuses the compiler as it never knows what you're talking about.

Ah Ok! I see it. Thanks for the tip. It compiles without error now.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
iterate through 8 thermocouple sensors (MAX31856)
I have 8xMAX31856 and I am trying to use the Adafruit library. Instead of writing all 8 thermocouple channels each time in code (and wasting memory), I want to store the objects in an array and loop through them periodically.
Here is my code:
Adafruit_MAX31856 TCouple1 = Adafruit_MAX31856(2,11,12,13);
Adafruit_MAX31856 TCouple2 = Adafruit_MAX31856(3,11,12,13);
Adafruit_MAX31856 TCouple3 = Adafruit_MAX31856(4,11,12,13);
Adafruit_MAX31856 TCouple4 = Adafruit_MAX31856(5,11,12,13);
Adafruit_MAX31856 TCouple5 = Adafruit_MAX31856(6,11,12,13);
Adafruit_MAX31856 TCouple6 = Adafruit_MAX31856(7,11,12,13);
Adafruit_MAX31856 TCouple7 = Adafruit_MAX31856(8,11,12,13);
Adafruit_MAX31856 TCouple8 = Adafruit_MAX31856(9,11,12,13);

char* thermocouples[] = {TCouple1, TCouple2, TCouple3, TCouple4, TCouple5, TCouple6, TCouple7, TCouple8};

however, I am met with this error on compile:
cannot convert 'Adafruit_MAX31856' to 'char*' in initialization

Why can I not store these variables in an array and call on them later? Is there another way to do this? They work on SPI logic...

You CAN store them in an array, but NOT in an array of pointers to characters. That is just the wrong type. Try
Adafruit_MAX31856 thermocouples[] = {TCouple1, ...}

or even ditch the first declarations and use
Adafruit_MAX31856 thermocouples[] = {
    Adafruit_MAX31856(2,11,12,13),
    Adafruit_MAX31856(3,11,12,13),
    Adafruit_MAX31856(4,11,12,13),
    ...
};

I don't have that library installed, but I tried compiling this pattern with the Bounce2 library and it works. That looks like this:
Bounce buttons[] = {
    Bounce(),
    Bounce(),
    Bounce()
};

Alright! I have tried that and it compiles past it... but how do I loop through this array? I tried for(int i = 0; i<8; i++){thermocouples[i].setThermocoupleType(MAX31856_TCTYPE_T);} and it says it is void

nevermind... sorted out issue. Thanks for the guidance!


text:
arduino robot wont move
I wanted to build an object avoider robot and I am a beginner so I copied a video from youtube and did exactly the same thing and used the same code but when I upload the code the robot won't move at all and it makes a weird sound. i cant I identify if this is a coding problem or hardware problem please tell me what is wrong and what I should do. previously I had made the same robot it moved but the coding was wrong and while adjusting it the minus and plus met at the positive terminal and smoke came I quickly turned it off and this resulted in my batteries getting wasted. do you think that this might be the reason might have added some things extra but they are not connected to the motor driver or Arduino here is the pics of my robot
https://drive.google.com/drive/folders/1t9eYnCt_v4w-IAjYex5wKEFwKv91hnAr?usp=sharing
.here is my code
//ARDUINO OBSTACLE AVOIDING CAR Video - https://youtu.be/h-B42_HXL00//
// Before uploading the code you have to install the necessary library//
//AFMotor Library https://learn.adafruit.com/adafruit-motor-shield/library-install //
//NewPing Library https://github.com/eliteio/Arduino_New_Ping.git //
//Servo Library https://github.com/arduino-libraries/Servo.git //

#include <AFMotor.h>
#include <NewPing.h>
#include <Servo.h>

#define TRIG_PIN A0
#define ECHO_PIN A1
#define MAX_DISTANCE 100
#define MAX_SPEED 150 // sets speed of DC  motors
#define MAX_SPEED_OFFSET 20

NewPing sonar(TRIG_PIN, ECHO_PIN, MAX_DISTANCE);

AF_DCMotor motor1(1, MOTOR12_64KHZ);
AF_DCMotor motor2(2, MOTOR12_64KHZ);
AF_DCMotor motor3(3, MOTOR34_64KHZ);
AF_DCMotor motor4(4, MOTOR34_64KHZ);
Servo myservo;

boolean goesForward=false;
int distance = 100;
int speedSet = 0;

void setup() {

  myservo.attach(10);
  myservo.write(115);
  delay(2000);
  distance = readPing();
  delay(100);
  distance = readPing();
  delay(100);
  distance = readPing();
  delay(100);
  distance = readPing();
  delay(100);
}

void loop() {
 int distanceR = 0;
 int distanceL = 0;
 delay(40);

 if(distance<=25)
 {
  moveStop();
  delay(100);
  moveBackward();
  delay(200);
  moveStop();
  delay(200);
  distanceR = lookRight();
  delay(200);
  distanceL = lookLeft();
  delay(200);

  if(distanceR>=distanceL)
  {
    turnRight();
    moveStop();
  }

  else

  {
    turnLeft();
    moveStop();
  }
 }

 else
 {
  moveForward();
 }
 distance = readPing();
}

int lookRight()
{
    myservo.write(50);
    delay(500);
    int distance = readPing();
    delay(100);
    myservo.write(115);
    return distance;
}

int lookLeft()
{
    myservo.write(170);
    delay(500);
    int distance = readPing();
    delay(100);
    myservo.write(115);
    return distance;
    delay(100);
}

int readPing() {
  delay(100);
  int cm = sonar.ping_cm();
  if(cm==0)
  {
    cm = 250;
  }
  return cm;
}

void moveStop() {
  motor1.run(RELEASE);
  motor2.run(RELEASE);
  motor3.run(RELEASE);
  motor4.run(RELEASE);
  }

void moveForward() {

 if(!goesForward)
  {
    goesForward=true;
    motor1.run(FORWARD);
    motor2.run(FORWARD);
    motor3.run(FORWARD);
    motor4.run(FORWARD);
   for (speedSet = 0; speedSet < MAX_SPEED; speedSet +=2) // slowly bring the speed up to avoid loading down the batteries too quickly
   {
    motor1.setSpeed(speedSet);
    motor2.setSpeed(speedSet);
    motor3.setSpeed(speedSet);
    motor4.setSpeed(speedSet);
    delay(5);
   }
  }
}

void moveBackward() {
    goesForward=false;
    motor1.run(BACKWARD);
    motor2.run(BACKWARD);
    motor3.run(BACKWARD);
    motor4.run(BACKWARD);
  for (speedSet = 0; speedSet < MAX_SPEED; speedSet +=2) // slowly bring the speed up to avoid loading down the batteries too quickly
  {
    motor1.setSpeed(speedSet);
    motor2.setSpeed(speedSet);
    motor3.setSpeed(speedSet);
    motor4.setSpeed(speedSet);
    delay(5);
  }
}

void turnRight() {
  motor1.run(FORWARD);
  motor2.run(FORWARD);
  motor3.run(BACKWARD);
  motor4.run(BACKWARD);
  delay(500);
  motor1.run(FORWARD);
  motor2.run(FORWARD);
  motor3.run(FORWARD);
  motor4.run(FORWARD);
}

void turnLeft() {
  motor1.run(BACKWARD);
  motor2.run(BACKWARD);
  motor3.run(FORWARD);
  motor4.run(FORWARD);
  delay(500);
  motor1.run(FORWARD);
  motor2.run(FORWARD);
  motor3.run(FORWARD);
  motor4.run(FORWARD);
  }```

forget about obstacle avoidance ... write a simple sketch to move motors forward for 1 second, stop for 1 second, then repeat

I recognize that robot chassis - its the one I started with as well!  I second the commenter's recommendation.  Don't worry about anything beyond getting the motors to move.  In fact, I would recommend you disconnect all but one motor, and replace the wheel from that motor with a piece of tape (so you can see if it is rotating).  That way the robot will be supported by the three non-moving wheels and you can see motor rotation without having the robot run away.

You might also want to consider a different power source, other than the 9V batteries you show in your pics.  These batteries are very poor motor sources as they have relatively low capacity.  If you have a DC power supply, use it instead.  If not, be prepared to change out batteries often.  See my blog site (fpaynter.com) for some additional information on 2 and 4-wheel robots.

Please don't link to Google Drive. Those pictures will disappear, and then people won't understand your question (and perhaps the answer) in the future. You can edit your post and upload the relevant pictures through the editor. Keep the amount of pics minimal though.


text:
Having a bunch of global variables or calculate them on the go on an Arduino, as far as memory is concerned
So I'm new in the arduino world but I have a grasp of object oriented programming, and decided to write a little library for running games on an arduino mega using a display. My question is, I'm creating an "Entity" class (to spawn multiple enemies, players, etc) outside the setup() and the loop() functions, so they dont overwrite themselfs when the program is running (don't know if there's a better way), and I want to store position information, like xPos and yPos, but I need to calculate a lot of other stuff based on those two variables, and creating more variables makes the code more easy to read/write.
But I don't know how this would affect the memory usage or speed, because I ran into some problems earlier when I tried to create a big array, it end up using like 300% of the dynamic memory, so I guess that when I declare a global byte, for example, the arduino allocates the whole memory as if you would use the biggest byte possible.
Sorry for bad english :s

Maybe try to change some constant variables to #define values, because they need nearly no storage. Also a ESP32 has 4MB of flash, with that much more place (the Mega has 256KB) place shouldn't be a problem anymore.

Well, I want to know if should I avoid creating more variables that I know they can be calculated easily, but makes the code more readable, or if I just stick to the most basic variables.

Thanks @PythonSchlange, I'll keep that in mind, I never understood the use of #define till now.

On an Arduino Mega, the “biggest byte possible” is 8-bits wide.

@EdgarBonet, yeah, but I was trying to calculate collisiones just using a 2d array, like simulating every pixel in an array, but a 128 x 64 byte array is too big for the dynamic memory.

Yes, 128 × 64 = 8 K, which is the whole RAM of the Mega. Seems you found yourself the answer to your question.

@EdgarBonet, mmm, looks like it, then I'll try to stick to the most basic variables (in a global scope) when memory usage is critical. But the readability's gonna suck :(

The question is one of time vs. space.  If time is more important then use up memory to hold the values.  If memory is more important then you use some time to recalculate things each time.  Only you really know what your project does and what its needs are.  There simply is not one right answer to this question.

On your collision issue: You might have to think of another algorithm, that works with less RAM but caches results. -- That is what I find satisfactory in embedded control: The need to think instead of mindlessly using a lot of resources.


text:
Object composition (class uses class)
I would like to write a class which utilises another class and it´s member functions. I found out that this is object composition and read some examples of how to do it but it ither doesn´t work for me or I just don´t understand it completely. Here are parts of my code.
#include <SPFD5408_Adafruit_GFX.h>    // Core graphics library
#include <SPFD5408_Adafruit_TFTLCD.h> // Hardware-specific library
#include <SPFD5408_TouchScreen.h>     // Touch library
#include <TriangleButton.h>        // TriangleButton library

I want to use an Adafruit_TFTLCD object and its member functions inside my own class TriangleButton. The object tft is initialised before setup.
Adafruit_TFTLCD tft(LCD_CS, LCD_CD, LCD_WR, LCD_RD, LCD_RESET); //Class is part of SPFD5408_Adafruit_TFTLCD.h

I built the TriangleButton.h similar to this thread (Use object of other class within class) and used a reference to the tft object.
/*
  TriangleButton.h - Library for for constructing and reading triangle Buttons.
*/
#ifndef TriangleButton_h
#define TriangleButton_h

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

class TriangleButton
{
  public:

    TriangleButton(Adafruit_TFTLCD &tft, int16_t coordX, int16_t coordY, int16_t orientation, uint16_t size, uint16_t color) : _tft(tft){}
    boolean IsTriggered();
    void dash();
  private:

    Adafruit_TFTLCD &_tft;
    int16_t _coordX;
    int16_t _coordY;
    int16_t _orientation;
    int16_t _size;
    int16_t _color;
    int16_t _ru;
    int16_t _hc;
};

#endif

In the ccp. i put a coresponding constructor.
TriangleButton::TriangleButton(Adafruit_TFTLCD &tft, int16_t coordX, int16_t coordY, int16_t orientation, uint16_t size, uint16_t color)
:
_tft(tft)

Now i get the following error message:
C:\Users\Erik\Documents\Arduino\libraries\AquariumController_Library\TriangleButton.cpp:19:1: error: redefinition of 'TriangleButton::TriangleButton(Adafruit_TFTLCD&, int16_t, int16_t, int16_t, uint16_t, uint16_t)'
TriangleButton::TriangleButton(Adafruit_TFTLCD &tft, int16_t coordX, int16_t coordY, int16_t orientation, uint16_t size, uint16_t color)
^~~~~~~~~~~~~~
In file included from C:\Users\Erik\Documents\Arduino\libraries\AquariumController_Library\TriangleButton.cpp:7:0:
C:\Users\Erik\Documents\Arduino\libraries\AquariumController_Library\TriangleButton.h:14:5: note: 'TriangleButton::TriangleButton(Adafruit_TFTLCD&, int16_t, int16_t, int16_t, uint16_t, uint16_t)' previously defined here
TriangleButton(Adafruit_TFTLCD &tft, int16_t coordX, int16_t coordY, int16_t orientation, uint16_t size, uint16_t color) : _tft(tft){}
^~~~~~~~~~~~~~
exit status 1
I don`t understand why ther is a redefinition. Can somebody explain it to me?

error: class 'TriangleButton' does not have any field named '_tft'

This should be self-explanatory. When you write in the constructor

_tft(tft)

It means “initialize the property _tft of this object with the
parameter tft.
It is not very clear what you mean by “object composition”. In the usual
sense, it means that object A either is or has an object B. In your
case, it seems like you want your TriangleButton to hold a reference
to an Adafruit_TFTLCD. This is not really composition, as your class
neither is nor has an LCD.
As an immediate solution, just add an appropriate data member to the
class:
Adafruit_TFTLCD &_ftf;

Assuming that holding a reference to the LCD is really what you want for
your class, this should be enough to solve your issue.

Edit: To answer the edited question.
“Redefinition” means you are defining again something that has already
been defined before. In this case, the constructor is defined inline in
the header file:
TriangleButton(Adafruit_TFTLCD &tft,
        int16_t coordX, int16_t coordY,
        int16_t orientation, uint16_t size, uint16_t color)
    : _tft(tft){}

(yes, that's a complete definition with an empty body).
And then you try to define it again in the cpp file. This is an error,
every method should be defined only once. At your choosing, it can be
either inline in the header or in the .cpp, but not both.

Thank you Edgar for your explaination. You are right this is not a composition but a reference. Your advice of adding the data member solved the error with the missing field. I updated my code in the question. Now i have a problem with a redefinition. Can you help me?

@ErikWeisbrod: See amended answer.

Thank you Edgar once again now the code compiles. I did not know about the possibility to use an inline constructor in the header file. If i define the constructor in the ccp. do i still need the TriangleButton in the header?

@ErikWeisbrod: If you define the constructor in the .cpp file, you still have to declare it in the class definition within the header file: TriangleButton(parameter list...);. Note that the declaration has no initialization list (i.e. : _tft(tft)) nor a function body ({}), and it ends with a semicolon (;).


text:
Wrong data receiving in my Arduino by bluetooth
I have programmed a client-server between an Arduino and my mobile app in Android. I´m using a buetooth HC-06. For the moment is a very basic code just to turn ON/OFF a led, regulate its voltage, and receive the charge of the battery.
This is my Arduino code for receiving the message:
#include <SoftwareSerial.h>
#include <TimerOne.h>
SoftwareSerial hc06(2,3);

char command;
String string;
boolean ledon = false;
const byte MAX_STRING_LEN = 40;
const int  BLINK_INTERVAL = 1000;

char inputString[MAX_STRING_LEN];  // a string to hold incoming data

int BatteryPin = A0;    // select the input pin for the potentiometer
int sensorValue = 0;  // variable to store the value coming from the sensor
float BatteryCar = 0;
int PercentageBatt = 0;
int intensidad = 0;
byte strLen   = 0;                 // current length of rec'd string

#define led 11
void setup()
{
  Serial.begin(9600);
  hc06.begin(9600);
  pinMode(led, OUTPUT);
  Timer1.initialize(10000); // set a timer of length 10000 microseconds (or 0.01 sec - or 1Hz => the led will blink 5 times, 5 cycles of on-and-off, per second)
  Timer1.attachInterrupt( SendVoltage );
}
void loop()
{

  sensorValue = analogRead(BatteryPin);
  BatteryCar = sensorValue * (5.0 / 1023.0);
  if (hc06.available() == 0)
  {
    analogWrite(led, 0);
    delay (10);
  }
  while(hc06.available() > 0)
  {
    command = ((byte)hc06.read());
    if((command == '\n') || (command == '\r'))
    {
      command =='\0';
      break;
    }
    else if (command == 'O')
      analogWrite(led, 255);
    else
      analogWrite(led, 0);
    delay(10);
    Serial.println(command);
  }
}

void SendVoltage ()
{

  PercentageBatt = (BatteryCar * 100)/4;
  hc06.println(PercentageBatt);
}

This is the data that I´m receiving:

It supposed that i should only receive "O" or "F". Any suggestion??
thanks in advanced,

It would appear that whatever is sending the data is sending something else.  Since we cannot see any of that code nobody can do anything but guess at why.

simply ignore unexpected data

why are you printing the value of command after you modify its value?

note:  substituting \0 for \r and for \n is kind of pointless

Does your HC-06 actually run at 9600 baud? Is your serial monitor set for 9600 baud?

Well, after a lot of research, it seems that my main problem was that I´m receiving and sending information at the same time. And with the library Softwareserial, only 1 can be active at the same time.
I found two solutions, but to be honest I'm not complete satisfy with neither of them. However, for my application will work.
The first solution: Is to used the HardwareSerial (pin 0,1) itself, instead of using the pin 2 and 3. When I used those, it didn't have any problem. Although I decided no to used because it help me debugging my code.
The second solution: Is to decrease the frecuency of what I´m sending. For me its ok I send the data every second. So my code would be like this:
#include <SoftwareSerial.h>
#include <TimerOne.h>
SoftwareSerial hc06(2,3);

char command;
String string;
boolean ledon = false;
const byte MAX_STRING_LEN = 40;
const int  BLINK_INTERVAL = 1000;

char inputString[MAX_STRING_LEN];  // a string to hold incoming data

int BatteryPin = A0;    // select the input pin for the potentiometer
int sensorValue = 0;  // variable to store the value coming from the sensor
float BatteryCar = 0;
int PercentageBatt = 0;
int intensidad = 0;
byte strLen   = 0;                 // current length of rec'd string

#define led 11
void setup()
{
  Serial.begin(9600);
  hc06.begin(9600);
  pinMode(led, OUTPUT);
  Timer1.initialize(1000000);
  Timer1.attachInterrupt( SendVoltage );
}
void loop()
{

  sensorValue = analogRead(BatteryPin);
  BatteryCar = sensorValue * (5.0 / 1023.0);
  if (hc06.available() == 0)
  {
    analogWrite(led, 0);
    delay (10);
  }
  while(hc06.available() > 0)
  {
    command = ((byte)hc06.read());
    if((command == '\n') || (command == '\r'))
    {
      command =='\0';
      break;
    }
    else if (command == 'O')
      analogWrite(led, 255);
    else
      analogWrite(led, 0);
    delay(10);
    Serial.println(command);
  }
}

void SendVoltage ()
{

  PercentageBatt = (BatteryCar * 100)/4;
  hc06.println(PercentageBatt);
}

I have read about this library (AltSoftSerial), but I couldn't get it work. I have usde the pin 8 and 9, but nothing.


text:
Using esp-wroom-32 without a development board
There are lots of examples on the internet on how to build Arduino from scratch such as IN THIS LINK. I will like to do the same but with the esp32.
I have this development board:

And I am able to program it with the Arduino framework/IDE thanks to THIS VIDEO.

Now the question
How can I flash my code and run it on a standalone ESP-WROOM-32 chip like this one:

I do not want to use voltage regulator etc as I am planning to run it from a 3.3V battery.
Before asking this question this was my research:

In this video (https://www.youtube.com/watch?v=n43rHugPbTg) Hugatry does exactly what I am looking for but he does not explain what pins he is using. Moreover what happens if I connect my 5v serial to the chip? will it burn?

I went directly to espressif website and looked for the schematics (https://www.espressif.com/sites/default/files/documentation/esp32-wroom-32d_esp32-wroom-32u_datasheet_en.pdf). It is hard to understand I just want to do something simple.

This blog (http://blogs.oregonstate.edu/copaps/resources/programming-esp32-on-custom-pcb/) explains how but the pins are different than my esp-wroom-32 chip.

Looking more on the internet/youtube everyone explains how to solder it. But I haven't found a diagram that will enable me to flash it and run my code. Also will I have to burn a bootloader like with arduino?
What I am about to try is to buy a 5V to 3.3V serial converter connecting TX with RX and RX with TX. Providing 3.3V power to the 3.3V pin and connect the last cable to ground. If I try that will it work?

It looks like you need to increase your general level of understanding of electronics. There is no "really simple" way except for buying a ready-made board. Look at the schematics of a standard ESP32 board to see what you need for support circuitry. As for your questions: 1) Yes, it will burn at 5V. 2) See my first comment. 3) See my first comment.

The development board is basically the minimum circuit plus a USB to UART interface and a 3.3V regulator. Once you remove the regulator and its capacitors, and the USB interface and the few components for that, what you are left with is the bare minimum. You can't get much simpler than those development boards.

The third link from the Oregon State University is unfortunately no longer available. It would be interesting to know what they wrote there.

This is what I was looking for. The development board is not the minimum as @Majenko and @StarCat stated on their comments. This is exactly what I need as I plan to run my project from a battery. Moreover, the development board consumes a lot more energy when in sleep mode. I will even remove the LED that shows on this diagram:

So basically use a programming board like @KenVanHoelandt stated to program the board and then wire the esp32 like in the diagram above.
I got that diagram from this link:
https://www.14core.com/wiring-and-flashing-programming-esp-32-esp32s-with-usb-ttl-uart/

you don't really need the buttons either

Is this recognized as a programmer board by Arduino software (like the IDE or some plugin)?

I am not sure what the exact minimum voltage esp32 requires, but make sure it is at least 3.6v that will be able to support it when wifi is being used . Also if you dont have a cut off circuitry for low voltage it might mess up your memory when the voltage is too low as the battery discharges.

There are programming boards available to which you can plug one of these SOCs into them. There are different boards for different types of ESP SOCs.
You can find them at popular Chinese vendors, and probably elsewhere too.
They look like this:

You could use wireless.  First, use OTA programming (eg Elegant OTA) to burn a basic OTA uploader.  Then, in principle,  you can then upload any sketch you want so long as it ALWAYS has the basic OTA sketch included within your program.

I don't think this answers the question. You still need support circuitry to auto-update, even if only updating over Wifi.


text:
Copy outbound data of Serial to Serial1 for Pro Micro
I am working on a bluetooth HID device. There are libraries which make HID devices a cake walk if you are making a wired version of your HID device.
I managed to configure my bluetooth module to appear as a HID device to the system, it however does nothing yet.
I figured if I route the serial data, that my wired version of device is sending to the system on Serial, to Serial1 my bluetooth device will function the same way the wired device worked.
If I am not wrong, code that I came across, maps RX of Serial to TX of Serial1.
Void setup(){
    Serial.begin(9600);
    Serial1.begin(9600);
}
void loop(){
     if(Serial.available()){
      char get= Serial.read();
      Serial1.Write(get);
     }
}

What I want to do is map the TX pin of Serial to TX pin of Serial1 of the pro micro.

What is your actual question?  As I understood, you want to forward the data, that you receive on Serial to the Serial1 interface. That's exactly what your code does (except for the spelling error with the big W in Serial1.Write(get)).

Re “map the TX pin of Serial to TX pin of Serial1”: you are rather forwarding from Serial’s RX to Serial1’s TX.

@chrisl I don't want to forward the data that I receive on Serial, I want to forward the data that Serial is sending to the system.

@EdgarBonet I want to forward TX of Serial to TX of Serial1. Is there a way to do that? Maybe there's a register where data is stored before writing it on the Serial?

Maybe the context is missing in your question. When you want to send the same data to Serial and Serial1, just always use Serial.write() and Serial1.write() together with the same data. Or is there any reason, why you cannot do this?

@chrisl I am using the ArduinoJoystick library by MHeironimus. Whatever communication it does over the Serial connection is done underneath. I went through it's code but couldn't find anything similar to Serial.begin(). It does however use the DynamicHID library which in turn uses the PluggableUSB library. I don't have an electronics background so I couldn't understand much there.

Thats because the ArduinoJoystick library does not use Serial. It configures the micro to act as HID-USB device. That is completely different to Serial communication. Thus you cannot just send that over a Serial interface

What bluetooth device do you use?

Let us continue this discussion in chat.


text:
Teensy 4.1 Ethernet Throughput
Using a socket server on a Teensy 4.1, I am sending and receiving data in a loop from a Windows socket client (WinForms C#.NET).
I am sending or receiving 530 bytes of data. In each direction, it takes approximately 1.6 seconds to read or write and I think I've narrowed this delay down to the Teensy end when either client.read() or client.write(buffer, 530) are called by using Wireshark and a stopwatch in my C#.NET code on the Windows side.
The read code on the Teensy looks like this:
byte buffer[530];
int idx = 0;

while (client.available() > 0)
{
   buffer[idx] = client.read();
   idx++;
}

The write code is simply a byte array of 530 elements written like so: client.write(buffer, 530);
Is this typical? If not, is there some way to reduce this bottleneck?
Update
I found the issue - it was to do with some scanning function on the I2C bus taking up processing time. Isolating the socket server code allows it to execute very fast.

1.6 seconds sounds about 1.59999 seconds too long.

Are you opening the socket fresh each time you want to send? Is there a slow DNS lookup involved with that socket opening? Do you have other things in your code that will slow down the operation?

The socket connection is opened once and left open while the read/write loop is running. I'm using a static IP address to connect to the Teensy server so there's no DNS lookup involved.

I’m voting to close this question because the problem was elsewhere.


text:
How to combine two codes in arduino?
bine
#include <LiquidCrystal.h>
LiquidCrystal lcd(12,11,5,4,3,2);

#define sensor A0
#define led 13
#define ledd 8  // d out from mq3
#define buz 9
#define motor 10
void setup()
{
  Serial.begin(9600);
  lcd.begin(16,2);
  lcd.print("ALCOHOL MONITORING");
  lcd.setCursor(0,1);
  lcd.print(" VEHICLE SYSTEM ");
  delay(2000);
  pinMode(sensor, INPUT);
  pinMode(buz, OUTPUT);
  pinMode(led, OUTPUT);
  pinMode(ledd, OUTPUT);
  pinMode(motor, OUTPUT);
  lcd.clear();
}

void loop()
{
  float adcValue=0;
  for(int i=0;i<10;i++)
  {
    float actualanalogReading =  analogRead(sensor);
    adcValue = adcValue + actualanalogReading;
    Serial.println("In loop counter >"); // logging
    Serial.print(i);
    Serial.print(" input reading : ");
    Serial.print(actualanalogReading);
    Serial.print(" cumulative input reading : ");
    Serial.print(adcValue);

    delay(10);
  }
    float v= (adcValue/10) * (3.0/1024.0);
    float mgL= 0.67 * v;
    Serial.println("");
    Serial.print("Post calculation v value >" );
    Serial.print(v);
    Serial.print(" mg/L > ");
    Serial.print(mgL);
    Serial.println("");
    Serial.print("BAC:");
    Serial.print(mgL);
    Serial.print(" mg/L");
    lcd.setCursor(0,0);
    lcd.print("BAC: ");
    lcd.print(mgL,4);
    lcd.print(" mg/L        ");
    lcd.setCursor(0,1);
    if(mgL > 0.8)
    {
      lcd.print("Drunk ENGINE OFF ");
      Serial.println("Drunk ENGINE OFF ");
      digitalWrite(buz, HIGH);
      digitalWrite(led, HIGH);
      digitalWrite(ledd, LOW);
      digitalWrite(motor, LOW);
    }
    else
    {
      lcd.print("Normal ENGINE ON ");
      Serial.println(" Normal ENGINE ON ");
      digitalWrite(buz, LOW);
      digitalWrite(led, LOW);
      digitalWrite(ledd, HIGH);
      digitalWrite(motor, HIGH);
    }

    delay(100);

}

top code^^^
combines with this>>
const int LED = A5;
const int DO = 6;
void setup() {
 Serial.begin(9600);
 pinMode(LED, OUTPUT);
 pinMode(DO, INPUT);
}
void loop() {
 int alarm = 0;
 float sensor_volt;
 float RS_gas;
 float ratio;
//-Replace the name "R0" with the value of R0 in the demo of First Test -/
 float R0 = 0.10;
 int sensorValue = analogRead(A1);
 sensor_volt = ((float)sensorValue / 1024) * 5.0;
RS_gas = (5.0 - sensor_volt) / sensor_volt; // Depend on RL on yor module
 ratio = RS_gas / R0; // ratio = RS/R0
//------------------------------------------------------------/
 Serial.print("sensor_volt = ");
 Serial.println(sensor_volt);
 Serial.print("RS_ratio = ");
 Serial.println(RS_gas);
 Serial.print("Rs/R0 = ");
 Serial.println(ratio);
 Serial.print("\n\n");
 alarm = digitalRead(DO);
 if (alarm == 1) digitalWrite(LED, LOW);
 else if (alarm == 0) digitalWrite(LED, HIGH);
 delay(1000);
}

Do you know how both "codes" work?

@majenko both works just need to know how to combine them

@chrisl still not that familiar with them terms can you help me combine them and maybe i can see what you add and remove

I didn't ask if they both worked. I asked if you knew how they both worked. If you don't know how they work then there is no way you will be able to combine them.

What exactly is your problem in combining them? With what terms aren't you familiar? I will gladly answer your questions, but honestly I don't want to write the code for you. There is no simple answer to your current questions (other than the one I linked), because it is a rather broad question unless we do all your work for you. As Majenko stated, the key in combining 2 sketches is to understand how they work. Then you can decide how the final program should work and write a new code with fitting snippets of the previous codes

And you should look into the BlinkWithoutDelay example, which comes with the Arduino IDE. It shows how you can use the millis() function to write non-blocking code without delay() calls. It is an important principle to learn and may be really helpful when combining your sketches

While I'd like to direct you to ways to set up a nice tasking system with a frame counter, your system is likely simple enough that it is unnecessary.  You can likely just replace the delay(1000); of the second program with approximately 5 calls of the first program's loop.  May you instead learn something when cleaning up the following (which is literally a copy paste with minimal changes).

#include <LiquidCrystal.h>
LiquidCrystal lcd(12,11,5,4,3,2);

#define sensor A0
#define led 13
#define ledd 8  // d out from mq3
#define buz 9
#define motor 10
void setup1()
{
  Serial.begin(9600);
  lcd.begin(16,2);
  lcd.print("ALCOHOL MONITORING");
  lcd.setCursor(0,1);
  lcd.print(" VEHICLE SYSTEM ");
  delay(2000);
  pinMode(sensor, INPUT);
  pinMode(buz, OUTPUT);
  pinMode(led, OUTPUT);
  pinMode(ledd, OUTPUT);
  pinMode(motor, OUTPUT);
  lcd.clear();
}

void loop1()
{
  float adcValue=0;
  for(int i=0;i<10;i++)
  {
    float actualanalogReading =  analogRead(sensor);
    adcValue = adcValue + actualanalogReading;
    Serial.println("In loop counter >"); // logging
    Serial.print(i);
    Serial.print(" input reading : ");
    Serial.print(actualanalogReading);
    Serial.print(" cumulative input reading : ");
    Serial.print(adcValue);

    delay(10);
  }
    float v= (adcValue/10) * (3.0/1024.0);
    float mgL= 0.67 * v;
    Serial.println("");
    Serial.print("Post calculation v value >" );
    Serial.print(v);
    Serial.print(" mg/L > ");
    Serial.print(mgL);
    Serial.println("");
    Serial.print("BAC:");
    Serial.print(mgL);
    Serial.print(" mg/L");
    lcd.setCursor(0,0);
    lcd.print("BAC: ");
    lcd.print(mgL,4);
    lcd.print(" mg/L        ");
    lcd.setCursor(0,1);
    if(mgL > 0.8)
    {
      lcd.print("Drunk ENGINE OFF ");
      Serial.println("Drunk ENGINE OFF ");
      digitalWrite(buz, HIGH);
      digitalWrite(led, HIGH);
      digitalWrite(ledd, LOW);
      digitalWrite(motor, LOW);
    }
    else
    {
      lcd.print("Normal ENGINE ON ");
      Serial.println(" Normal ENGINE ON ");
      digitalWrite(buz, LOW);
      digitalWrite(led, LOW);
      digitalWrite(ledd, HIGH);
      digitalWrite(motor, HIGH);
    }

    delay(100);

}

const int LED = A5;
const int DO = 6;
void setup() {
 setup1(); //Serial.begin(9600);
 pinMode(LED, OUTPUT);
 pinMode(DO, INPUT);
}
void loop() {
 int alarm = 0;
 float sensor_volt;
 float RS_gas;
 float ratio;
//-Replace the name "R0" with the value of R0 in the demo of First Test -/
 float R0 = 0.10;
 int sensorValue = analogRead(A1);
 sensor_volt = ((float)sensorValue / 1024) * 5.0;
RS_gas = (5.0 - sensor_volt) / sensor_volt; // Depend on RL on yor module
 ratio = RS_gas / R0; // ratio = RS/R0
//------------------------------------------------------------/
 Serial.print("sensor_volt = ");
 Serial.println(sensor_volt);
 Serial.print("RS_ratio = ");
 Serial.println(RS_gas);
 Serial.print("Rs/R0 = ");
 Serial.println(ratio);
 Serial.print("\n\n");
 alarm = digitalRead(DO);
 if (alarm == 1) digitalWrite(LED, LOW);
 else if (alarm == 0) digitalWrite(LED, HIGH);

 for(int dd = 0; dd < 5; dd++) loop1();
}


text:
Monitor two baud rates
I am using different codes which set different values of baud rate through the Serial.begin() function.
I have an Uno using Serial.begin(9600) connected to an ESP8266 ESP-01 module
SoftwareSerial WiFiBoard(2, 3);
WiFiBoard.begin(115200)

Both of them are printing and reading from Serial, but when I use Arduino IDE Serial Monitor, I'm only able to display the content of the 9600... Am I missing a setting somewhere?
Also, when I configure both of them to use the baud rate 9600, I still only see the Uno information

You can't have two different baud rates on the same serial connection. That is illogical.

My understanding is that by using the SoftwareSerial library, a new Serial connection is used

That is a completely separate serial connection. Nothing at all to do with the serial monitor.

Oh ! That makes a lot more sense now... So is there a way to actually monitor the two boards ?

Your PC only sees what the Arduino sends through Serial. If you want it to see something from somewhere else then you have to actively read that data from that "other place" and send it to your PC through Serial.

That makes so much sense now.. So I still can chose a different baud rate for the WiFiBoard, I can still write and read from it, but in order to display it in the serial monitor, I need to basically Serial.print(WiFiBoard.read()) ?

In short, yes.  Better: while (WiFiBoard.available()) { Serial.write(WiFiBoard.read()); }

Perfect, thank you!

Your computer can not see what is going over the WiFiBoard serial connection because that connection has nothing at all to do with the connection to your computer.
If you want your computer to see what is being received on that port you must read the data from that port then send it to your computer.
It doesn't (much) matter about the difference in baud rates (only that if one sends too much data too fast for the other to forward it you will lose some data).
It's common to use something like:
while (WiFiBoard.available()) {
    Serial.write(WiFiBoard.read());
}

That will forward anything received from the WiFi board over the serial port to the computer.


text:
Esp 32 keeps disconnecting from com port
I was trying to upload a blinking coding that was in Arduino IDE but the Arduino IDE can not detect my Esp32 but when i press "EN" i manage to get connection but when i letgo the esp32 disconnect again

What is wired to your ESP32?

Nothing is wired to my esp32

What ESP32 board are you using?

Esp 32 DOIT DEVKIT V1 board

I would suggest that you have a dodgy USB cable or socket on that board. Pressing the EN can not do anything to USB, since it has no connection to USB. But it is right by the USB socket, so you may be pressing down on that at the same time, or otherwise moving the connector.

I have use multiple  cable still the same result

And if you hold the board completely still with one hand and press EN with the tip of something like a pen does it still exhibit the same symptoms?

By doing that the Arduino IDE detect my board on com port 3 but when i letgo of "EN" button it disconnect


text:
AT firmware upgrade in ESP-01 using Arduino UNO R3
I need to upgrade the AT firmware in ESP-01 by using Arduino UNO R3 serial interface. Do I need to remove the Microcontroller Chip from the DIP socket before burning firmware? Does it going to affect Arduino Bootloader?

Take a look at my answer to another similar question.

Thank you it helped a lot

Do I need to remove the Microcontroller Chip from the DIP socket before burning firmware?

No, just connect RESET to GND to stop the MCU from running.

Does it going to affect Arduino Bootloader?

No.


text:
How do I use lambda functions in Arduino?
I want to pass a lambda function as an argument to a method. Example:
T reduce(const T initial, const std::function<T(T, T)> acc) {
    T value = initial;
    for (size_t i = 0; i < S; ++i) {
        value = acc(value, this->values[i]);
    }

    return value;
}

...

int sum = this->reduce(42, [](int acc, int value) { return acc + value; });

If I try to compile this code for Arduino, I get an obvious error:

error: 'function' in namespace 'std' does not name a template type

How can I use a lambda function in Arduino?

std::function is not supported by the Arduino environment.
(Edit: as mentioned by KIIV in a comment, it's supported on ARM
targets, but not on AVR.) You can, however, pass a non-capturing lambda
to a function that expects a plain function pointer. For example, given
T reduce(const T initial, T (*acc)(T, T)) {
    T value = initial;
    for (size_t i = 0; i < S; ++i) {
        value = acc(value, this->values[i]);
    }
    return value;
}

You can call it as
int sum = test.reduce(42, [](int acc, int value){ return acc + value; });

If you want your lambda to capture something, it would seem you are out
of luck...

Not completely true. It's not supported by avr-g++ compiler. However compilers for ARM based arduinos usually have full support of STL libraries including std::function

@KIIV: thanks for the heads up. I edited the answer.

You can emulate a closure by an instance of a helper class that stores the captured values and implements the function. I didn't try it, but I expect it to work even for AVRs.


text:
How to upload a sketch to an atmega328 via FTDI FT232RL UART and Arduino IDE?
I have a sparkfun AVR Pocket Programmer and have burned the bootloader and uploaded programs using "upload using programmer" via USBtinyISP. It works fantastic.
I have a sparkfun FTDI Basic (as well as another FTDI breakout) that can send and receive bytes via the Arduino IDE serial monitor.
However, I cannot upload a new sketch or modified sketch to the atmega328 via FTDI. The IDE just hangs at the upload till timeout. Here is the list of some of my troubleshooting attempts:

I have tried uploading a plain bootloader, as well as a running program via the ISP programmer before attempting the FTDI.
I have tried direct connecting the FTDI DTR/RTS reset to the Atmega328 pin1.
I have also tried connecting the FTDI DTR/RTS reset to a one side of a 0.1uF cap, and the other side of the cap to the Atmega328 pin1. I assume the cap is to send just a reset pulse instead of a reset constant.
I have tried a different brand of FTDI FT232RL chip. No difference.
I have tried adding 1k resistors on the Tx and Rx lines. No difference.

Being able to program over serial is really the secret sauce that makes Arduino so much easier for beginners than a stock AVR chip. However, I have not been able to locate any detailed information on how this Arduino programming via serial really works. Also, I am not sure how the reset pin works in relation to this process. I remember something that on old Arduino boards you had to press or hold the reset when uploading, but have not be able to find any of this information either as it has been buried by time.
This Building an Arduino on a Breadboard Article and photo from that article below is a good outline of the setup I have right now. But in this configuration it seems that a sketch can not be uploaded. What do I need to add breadboard circuit in order to upload a sketch via serial? Or what procedure do I need to do with the reset button when uploading?

Thanks!
Atmega328 Spec Sheet PDF

Instead of showing a picture of what you attempted, you should show us a picture of what you have actually done.

Your first link in fact provided all the information you need. By default, Atmega328 only support programming via ISP (which is an SPI interface), in order to serial boot loading, you need to upload the bootloader to the chip first. There are plenty of information available on the internet or even on the first link you provided on how to burn a bootloader to Atmega328. For programming via serial, you need the DTR connect RST via a cap, take a look at Pro Mini schematic.

@hcheung, Thanks! I had just figured it out when you posted your comment, but you were right on! Thanks!

@Majenko, I posted my actual breadboards in the answer. Thanks!

Answering my own question; I just got lost in the troubleshooting.

Though I tested it both ways, I evidently overlapped issues, masking the core problem. Upload using programmer works great for transferring your sketch but it does NOT allow sketches to be uploaded via serial later. (Not sure if there is an inherent or logical reason for this, but this is what I have found by experimentation).
And like hcheung mentioned in the comments, a capacitor on the FTDI reset line is required. Connecting it directly will NOT work. I used a 0.1uF and it worked well. I have attached a couple different photos of my setup for someone following this path in the future. Note that the LED I am using has an internal resistor; a normal LED will need an 1k series resistor. Also, leaving the ISP programmer attached while uploading a sketch over serial did not seem to cause any issues.


text:
L298N motor driver and battery issues
I'm trying to build an Arduino 4WD smart car. so i connected my l298N motor driver module with my v4 shield and used a 4 x 1.5v AA batteries to try and power my 4 motors up. i connected 2 of the motors in parallel so i can use 1 L298N to power it on. initially it worked but then a few minutes later it stopped moving. i thought my connections were bad so i redid all the connections but it didn't work so i changed the battery to 9v. with this the motors worked for a few seconds then stopped but was making noise so i tried powering the motor driver with my Arduino but it didn't come on. I tried powering the motor driver module with my Arduino but the driver module didn't come on.i decided to use my bread board and l293D IC to control my motors it didn't work but the motors were making noise. I changed my motor to one that i removed from a PlayStation controller but nothing still.i did research on the internet and was advised on this tutorial (https://create.arduino.cc/projecthub/maxxlife/arduino-4wd-car-cf5fd0) to not use AA batteries but no explanation why. so i checked other tutorials and saw people using AA to control 1 or 2 motors. Why shouldn't i use AA batteries? does anyone please think they know the solution to my problem? thank you
This is how my kit looks https://www.ebay.com/itm/NEW-4WD-Robot-Smart-Car-Chassis-Kits-car-with-Speed-Encoder-for-Arduino-M26/201561877173?_trksid=p2047675.c100009.m1982&_trkparms=aid%3D777000%26algo%3DABA.MBE%26ao%3D1%26asc%3D36860%26meid%3Dc76077722d4348e88152fa6c7f32c005%26pid%3D100009%26rk%3D1%26rkt%3D1%26sd%3D181329341315
Also should i change my use Li-ion battery 18650 x2 instead of the 6LR61 9v battery i used

go back to the begining ... one motor, 4 AA cells, simple sketch that runs the motor in one direction for 1 second, stops motor for one second and repeats

I tried that but it didn't work so i checked the voltage reading of the AA and i got around 5v. i tried my 9v battery but i checked the voltage reading first and it was 7v. the motors worked for a while but now have stopped working i checked the voltage readings and i'm getting 4v

I have the same problem. I made car from this link: https://www.electronicshub.org/bluetooth-controlled-robot-using-arduino/ currently, I used 4 AA batteries for this project but 4 dc motors not working. After that, I trying with a 3.7 V lion battery (2200mAH) with MT3608 step-up convertor to set 10V output which given to Arduino and L298N module to drive the motors but suddenly discharge the battery. So how to solve this issue?? Thanks in advance. Chirag

Rule #1 9V batteries a power supply they are NOT. In your case you are looking at small voltages for the motor power. Your choice of a driver is not the best as you will have from 1.2 to 2.4 volts across the L298 depending on the loading. This is directly from the ST data sheet. Try the TB6612FNG instead, taking advantage of the device’s use of MOSFETs. The TB6612 may be a little more expensive, but it will be clearly worth it.

Thank you for your answer but i don't really get what you're saying. i know the L298N is not really a good choice but i don't really have an option on what motor driver to use because of where i live. I did some research on the web and i think my problem is the batteries I'm using. i think the 9v and AA batteries cannot supply enough current for the 4 motors but I'm not sure. what do you think?

I agree. Batteries have a discharge curve which shows how much you can get out of them with a given load. Overloading them causes them to lose capacity.

I changed my batteries to 2 18650 li ion batteries and now the driver works well. But can you please explain  how i can calculate what battery is best to use. thank you for your help so far

You are welcome. That I cannot do, I do not know your resources, what the final design is like, how many you are going to make, what the actual load is, what the efficiency of your system etc.. That decision you have to make and rest assured there will always be a better one but there are also a whole bunch that are not as good. You are the design engineer you get to make the choice you will be happy with.

I give you credit for trying. In your spare time read some materials on basic
electronics. I will see if I can help but no guarantee. he motor driver you are using
has transistors as the driving element. That indicates the motor power is going
through them. Since they are transistors they have a PN junction. When voltage goes
through a silicone junction it will drop 0.7volts for each junction. If lightly
loaded sometimes less. Note: this loss is expelled as heat. You have two configured as a darlington configuration on each output. This places two junctions in series with each motor lead.  That is a total of 4 junctions yielding a drop of 4 * 0.7 = 2.8 Volts.  Subtract that from your supply before you start, that is a big hit in low voltage systems. The MOSFET will have a drop of about 0.05Volts on each side leaving you 2.7 more volts to work with. Batteries have power ratings, these are conservative:
Type Cap (mAh))  Drain(mA) -
D    13000      200 -
C     6000      100 -
AA    2400       50 -
AAA   1000       10 -
N     650        10 -
9     500        15 -
The battery capacity will be better with lower drain currents and shorter with higher drain current. To determine your battery life, divide the capacity by the actual load current to get the hours of life. For example: A circuit that draws 10 ma powered by a 9 volt rectangular battery will operate about 50 hours: 500 mAh /10 mA = 50 hours The cell voltage of alkaline cells steadily drops with usage from 1.54 volts to about 1 volt when discharged. The voltage is near 1.25 volts at the 50% discharge point. Alkaline cells exhibit a slightly increased capacity when warmed and the capacity drops significantly at temperatures below freezing. Mercury and silver oxide batteries have nearly twice the capacity as alkaline batteries of the same size but the current ratings are significantly lower. Alkaline batteries also have good shelf life making them ideal for home-made electronic projects. Rechargeable batteries have less capacity than primary cells Look at it like the batteries are your piggy bank. The more your take out the less you will have. The faster you take it out the quicker you are out of money.

ok thank you. but i still don't really get this.is drain how much current it can produce? if no then. According to the info i found on the internet the dc motors take 100mA at 5v. since 9v batteries have a type cap of 500mAh then shouldn't my motors last at least 5hrs or this is wrong because the drain is 15mA so i should use a type D or C battery. Also if i connect 4 AA in series does this increase the drain. i also connected the 9v battery and 4 AA in series and the motor came on and rotated faster and longer than using 9v alone i know this is part due to the increased voltage

But does the drain of the batteries also increase to 215mA? Li-ion have a capacity of 2200mAh so if i use 2 for my 4 motors then it should last more than 5hrs (2200/400) so doesn't that mean Li-ion or Lipo is my best bet?

The tork of your motor is dependent on watts. Since it is a fixed resistance the higher the voltage the more tork you will get. Also since Ohm's law entered into this the higher the voltage the higher the current the more watts you get hence more tork. More current decreases battery life at the expense of more tork. Drain as referred to is the load on the battery or the amount of energy it is draining from the battery.


text:
Read from Blynk terminal number to arduino
I have a problem in sending numbers from blynk terminal to arduino serial monitor. When I send any number from blynk terminal the arduino always getting 1. How can I get any number please help me. Thank you.
Here's my code
BLYNK_WRITE(V0){
  int pinValue = param.asInt(); // Int Value
  String i = param.asStr(); //String Value
  Serial.println(pinValue);

 if(i == "A"){
      Serial.println("Ready to enroll a fingerprint!");
      Serial.println("Please type in the ID # (from 1 to 127) you want to delete...");

      Blynk.virtualWrite(V0, "Ready to enroll a fingerprint!");
      Blynk.virtualWrite(V0, "Please type in the ID # (from 1 to 127) you want to save this finger
      as...");

      uint8_t num = 0;

        while (num == 0) {
          while (! Serial.available());
          num = Serial.parseInt();
        }
      Serial.print("Enrolling ID #");
      Serial.print(num);
 }
}

The value output of num is always 1 even I sent a different number.

the number is sent as string. so use param.asStr(), then convert it to number

I already know that, but the actual problem was any value that was sent to arduino serial monitor becomes 1

how do you know?. you don't print it. you print the int value

I tried it earlier, the value always get 1. please help


text:
Can I run more than 2 servo motors smoothly, connecting their power to regulated limit voltage and signal wires to the digital pins of the arduino?
Now my next project is going to be about Servo Motors and for that, I don't want to buy any shield or motor driver for Servos. So I have designed a circuit, to drive 12 servos at a time without any interruptions. I haven't got any Servos yet, well my order is shipped already...Keeping that aside lets head down to the connection..

The Screenshot was taken from a circuit designed by me at tinkercad.com.
Parts:

HiWatt Battery (Standard 9 volts battery blue and white coloured)

SG90 Servo Motor
(6v 400mah max)
(Resistance of each of them is 1.4kohm, when connected power and ground of multimeter)

Arduino
(Required amp is 40*12)

The circuit Explanation:

The Orange wires of servos are signal wires connected to the pins of Arduino.

A 750 ohm resistor is connected to the positive terminals of each motor, from which, voltage is regulated for the motor.

The motor grounds have been connected to the ground of the battery.

Ground of Arduino has been connected to the ground terminal of the battery. So now, ground of the battery and the Arduino is same.

All the motors are connected in parallel connections with 750 ohm resistors at the positive terminal of each motors

So now my question is, How many servos will I be able to run when I power them parallel-ly using a standard 9 volts battery (HI-WATT, Blue and white one), if no, Which will be the best battery for doing it?
I need to run 12 Servos uninteruptedly.
Thanks for your precious time....

So now my question is, How many servos will I be able to run when I power them parallel-ly using a standard 9 volts battery (HI-WATT, Blue and white one), if no, Which will be the best battery for doing it?

Unfortunately: Zero motors with your current circuit. Maybe one motor with a better circuit and the same battery. Here is the explanation.

You should ditch the standard 9V block battery. These batteries are made for low power applications (like IR remotes or smoke sensors) and cannot provide enough current for driving all those motors. They might be able to drive one servo, but still will be drained very fast. You should use a battery, that can provide much more current. Which battery you choose also depends on your other requirements. A series of AA alkaline batteries can give you enough current. Or you can directly buy a LiIon or LiPo rechargeable battery (including a fitting charger board). They can provide way enough current.

You cannot just use simple resistors as voltage regulators. That just doesn't work for loads, that can draw a changing amount of current (like a motor).

The voltage, that the motor gets, depends on the current, that the motor draws. When the motors stands still, it will draw very little current. Thus the motor is getting the full 9V in that case. As the drawn current rises, the voltage will go down, until the motor gets not enough voltage to operate correctly.
The resistor of 750 Ohm restricts the current draw of the motor. Even when we (for the sake of calculation) treat the motor as a short circuit, the maximum current through the resistor with 9V will be only 12mA, so way way lower than the 400mA, that you stated in your question. You won't be able to move the motor much with that little current.
Even if you used a smaller value, you need to be careful with the current. I guess you are using standard resistors there, which typically have a power limit of about 0.25W. These are meant for rather low current circuits. With the 400mA @ 6V, that your motors need, you are in the region of 2.4W (that is not necessary the power for the resistor, just a value for you to see the relation). You can easily burn away a little resistor that way. When you need a resistor with a higher power limit, you need to buy one, which can handle it (and these are typically multiple times the size of a standard "signal" resistor and still can get very hot, when used in the realm of their power limit).

Instead you should buy a proper voltage regulator. At that current, buy a switching buck regulator, as they are way more efficient than linear regulators. Which regulator you need to buy also depends on the voltage of the battery, that you choose. Be sure to buy a regulator, that can provide significantly more current, than we need in total for your circuit. This is important, because regulators are typically described with a maximum current, at which they already need extra measures for cooling. When you stay well below that, you can avoid thinking about fitting cooling for it.

So , will it control the motors as good as 16 channel servo drivers?

Yes, it can. Though you need to think about how you are controlling the servos on the Arduino. The standard Servo library supports up to 12 servos with one timer. When you can change the library to use 2 Timers for supporting more servos, then you have it. You could also try to search for other libraries, which support more servos, or write your own library. I would say, using the driver would be simpler. The driver does not switch the power for the servos. It has a chip, which can output 16 servo control signals and is controllable over an interface like I2C or SPI.
If you want to use such a driver is up to you. You might find it more important to have as few electronic parts as possible.

So, I just need to divide the current using a Voltage Regulator? So volt will remain constant, then, I guess the 750 ohm resistors won't be useful. Am I right?

Yes, a fitting voltage regulator will give you the correct voltage and will hold it constant (as long as you don't overload it). Voltage regulators are way more complex internally as a simple resistor. And yes, when using a proper voltage regulator, you should ditch the resistor.

The parallel connection of motor terminals should be connected to the voltage regulator output without any 750 resistor , and the battery should input the 9 volt in the regulator. Right? So , will it control the motors as good as 16 channel servo drivers?

I added a short explanation about the controls signals. Your question is mainly about the power supply. It is independent of the decision, if you want to use a driver. The power supply only gives the power to the servos, while the driver has a chip to generate the control signals.

Thanks for your precious time

Only 1 Voltage regulator would be enough right, I shouldn't require voltage regulator for each of the motors right?

Yes, one is enough, as long as it can provide enpugh current for all motors

Thanks again bro


text:
Arduino wait for incomming data from blynk terminal
I need to add wait command in code where it waits the next input value from blynk terminal to arduino? How can I do that? please help, I will appreciate your help, Thank you.
Here is my code
BLYNK_WRITE(V0)
{

     String i = param.asStr(); //String Value from blynk

      if(i == "A"){
          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...");

          Blynk.virtualWrite(V0, "Ready to enroll a fingerprint!");
          Blynk.virtualWrite(V0, "Please type in the ID # (from 1 to 127) you want to save this finger");

int numb = i.parseInt; //I need to add a command here to wait for the next blynk terminal value

  Serial.print("Enrolling ID #");
  Serial.print(numb);
}}

Possible duplicate of Read from Blynk terminal number to arduino

No, It was a different problem

you can't wait in blynk handler function. let it end. it will be called with the next input. use some variable to remember in which step of user input the code is


text:
Is it possible to send 2 or more o/p signal at the same time?
I wanted run two motors using Cytron MDD10A Dual Channel motor driver. So my concern is based on execution of code that is done line by line, in that case when I'm driving two motors will this delay in output signal at the PWM pins make a difference in nature of performance i.e. for example a car wheel, in case there is such delay it'll cause one wheel to rotate prior to another which is not desired. If yes, how do I rectify the same.
I also wanted to know when I use the delay function does it cause the delay in execution of the previous line or reads the upcoming line upon some 'x' seconds of delay?
Thank you for your help.
edit: code sample:
void FWD() {       // to move forward
    digitalWrite(m1, HIGH);  // motor 1 ON
    digitalWrite(m2, HIGH);  // motor 2 ON
    analogWrite(tm1, 225);   // tm1 assigned to a PWM pin
    analogWrite(tm2, 225);   // tm2 assigned to another PWM pin
}

in the above function I wish to run both analogWrite at the same time as I'm not sure how will it affect the output? I wish for the motors to start at the same time.

What is an O/P signal?

sorry, output signal. I wish to send two PWM signal at the same time to two different PWM pins.

you would have to post your code so we can fully understand what your talking about. But in general PWM signal are generated via timers and underlying hardware, so you can have multiple running at the same time.  A delay call will pause on its line. It will have already completed the previous line.

code sample:
void FWD(){
//to move forward
digitalWrite(m1, HIGH);//motor 1 ON
digitalWrite(m2,HIGH);//motor 2 ON
analogWrite(tm1,225);// tm1 assigned to a PWM pin
analogWrite(tm2,225;)//tm2 assigned to another PWM pin
}
in the above function I wish to run both analogWrite at the same time as I'm not sure how will it affect the output? I wish for the motors to start at the same time.

Arduino's(and any other device with a  single core processor) can only do one thing at a time. But you will not be able to tell which motor starts. The analog write function does not wait for the motor to do anything, it simply sets timers and interrupts to handle this. You should study the "Blink without Delay" example to understand how to do multiple things "at the same time".  Both motors will start at the same time.

Thank you @ChadG :)

@ChadG: No interrupts are involved in analogWrite().

@EdgarBonet not directly, but timers used by PWM are interrupt driven.

@ChadG: No, they are not. TIMER0_OVF is used for internal timekeeping, but this is unrelated to the PWM. The Arduino core does not enable any other timer interrupt, unless you use Tone, Servo, or another timer-dependent library.

how much delay do you think there is between the motor startups with the code you posted? ... also, do you think that two motors actually start up at the same time if connected together?

Technically, it is possible to start two PWM outputs at the exact same
time on an Uno or Nano. If they are both controlled by the same timer,
you just have to update the corresponding control register once with
the relevant bits set to enable both channels. For example, you could
start outputs 5 and 6 simultaneously, as both are on Timer 0:
OCR0A   = value;  // set the duty cycle on OC0A = digital 6
OCR0B   = value;  // set the duty cycle on OC0B = digital 5
TCCR0A |= _BV(COM0A1) | _BV(COM0B1);  // enable both outputs

If the outputs are on different timers, it is a bit more tricky. Timers
0 and 1 can be synchronized by clearing their shared prescaler with the
Timer/Counter Synchronization mode active. I do not think there is a
simple way to synchronize Timer 2 with any of the others.
All this is highly hardware-dependent, and not supported at all by the
Arduino core library. Thus, if you want to apply any of this, you will
have to study the datasheet, and poke directly into the I/O
registers of the microcontroller.
But then, as Delta_G clearly points out in his answer, all this is
irrelevant to motor control. Motors are mechanical devices that have
significant inertia. They take time to speed up and slow down. Just to
give you a sense of scale, PWM outputs 3, 9, 10 and 11 deliver a square
wave with a period of 2.04 ms. Yes, those are milliseconds, and
this is too short for the motors to significantly change their speed
within one period. Contrast this with the handful of microseconds,
that the call to analogWrite() will take.

I don’t think your fear is founded.  Yes technically one motor starts after the other but the amount of time would be a few microseconds at most.   For perspective it takes you about 200,000 microseconds to blink your eye.  You will not be able to tell.  They will appear to start at exactly the same time.  You would need some very sophisticated high speed cameras to see the difference in timing.  It wouldn’t affect how your car moves.


text:
Failed to boot VL53L0X: VL53L0X Error: -6
I am using a VL53L0X sensor in my project.
It was working fine when suddenly it started to show failed to boot error.
I tried debugging but of no use. I ran I2C scanner sketch and it detected the sensor at 0x29.
I get the following error -
23:38:27.797 -> Adafruit VL53L0X test
23:38:27.830 -> VL53L0X Info:
23:38:27.830 -> Device Name: VL53L0X ES1 or later, Type: VL53L0X, ID: VL53L0CBV0DH/1$1
23:38:27.830 -> Rev Major: 1, Minor: 1
23:38:27.864 -> VL53L0X: StaticInit
23:38:27.932 -> VL53L0X: PerformRefSpadManagement
23:38:27.932 -> refSpadCount = 2226323456, isApertureSpads = 92
23:38:27.932 -> VL53L0X Error: -6
23:38:27.932 -> Failed to boot VL53L0X

This is the code I used (its the example code with just 0x29 and true passed in begin function for verbose output):
#include "Adafruit_VL53L0X.h"

Adafruit_VL53L0X lox = Adafruit_VL53L0X();

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

  // wait until serial port opens for native USB devices
  while (! Serial) {
    delay(1);
  }

  Serial.println("Adafruit VL53L0X test");
  if (!lox.begin(0x29,true)) {
    Serial.println(F("Failed to boot VL53L0X"));
    while(1);
  }
  // power
  Serial.println(F("VL53L0X API Simple Ranging example\n\n"));
}

void loop() {
  VL53L0X_RangingMeasurementData_t measure;

  Serial.print("Reading a measurement... ");
  lox.rangingTest(&measure, false); // pass in 'true' to get debug data printout!

  if (measure.RangeStatus != 4) {  // phase failures have incorrect data
    Serial.print("Distance (mm): "); Serial.println(measure.RangeMilliMeter);
  } else {
    Serial.println(" out of range ");
  }

  delay(100);
}

I am using an Arduino nano -
following are the connections
ARDUINO->VL53L0X
3v3->Vin
GND->GND
A4->SDA
A5->SCL
I have rechecked the connection and voltages the sensor does receive 3v3 and gnd.
I need help with this asap.
Thanks in advance :)

what is the actual error description? ... the Serial.println(F("Failed to boot VL53L0X")); could just as easily be Serial.println(F("the sky is blue"));

This is the entire error message, could you let me know what you are looking for?

I was facing same issue, now my problem is solved here.
This problem mostly occurs when we apply a power supply to the MCU that has capacitors at its output. This type of power supply's rising voltage is like you can see the image:

If you look at the data sheets of MCUs, you see that most MCUs can work at 1.8V to 5.5V. Here the rising voltage is slow; the MCU starts working at 1.8V and send signals to VL53L0x, but the sensor doesn't work at 1.8V.
So, what you need to do is add some delay (first power supply gets stable then start communication with sensor) in your code to avoid this issue. Do not add delay in the loop; it will affect the working of the MCU, where exactly you need to add delay. Code modifications are in the video below:
https://youtu.be/QEiNbTB8nNE
or you just can search on Youtube: How to fix VL53L0X error

From the VL53L0X API documentation The error shows up as
#define VL53L0X_ERROR_RANGE_ERROR   ((VL53L0X_Error) -6)

Not very helpful, but maybe you still have the factory protective cover installed?
Also, IMHO the Adafruit library is a bit buggy.  I now use the Pololu library (among other things, the Pololu library allows usage of the WIRE1, WIRE2, & WIRE3 hardware I2C busses.
27 September 2020 Update: On the Adafruit technical support forum, I did a search for 'VL53L0X ERROR'.  There were several thread mentioning ERROR -6 issues, but most of them were due to poor or missing solder on the VL53L0X header pins.  Could that be your problem?

I have removed the factory protective cover.
I understand that the error message is not very helpful, I do not know what else I can deduce from it.
I will try to use the Pololu library as suggested.

Since it sort of worked before I am assuming it is connected correctly. However you failed to mention pull up resistors on the I2C bus. If they are not there or to weak that could cause what you are seeing.

I tried the same code with another sensor, without any pull ups, it works fine with it.
However, it is this particular sensor which throws an error which i am unable to resolve.

IIRC, the VL53L0X modules have 10K pullups on SDA/SCL already - no need to add

I found a new possible solution to this problem, as I spent 2 days to solve it, I feel that I need to share it with you guys. I also could find the sensor through i2C scanner, but could not initialize it.
Here is the summary of solutions:

Powering problem 1: add a 50ms delay in the setup function (before the sensor init, obviously). This way, the Vin will have time enough to reach the level needed by the sensor, as explained in a previous message (ocrdu)
Powering problem 2: This sensor demands more than others, normally the 5V pin of your board will do it better than the 3v3. If there are many sensors connected at the same time, disconnect all of them to check whether they are using the power our vl53l0x needs.
Powering problem 3: If you feed it with an external source, unify grounds with the board, don't forget it
SCL - SDA weak signals: add a pullup (2k2 - 4k7 from each channel to vin), this way the signals will perform better, that could be the problem
Soldering problem: Make sure that each header pin is well soldered. I've found many cases of poor soldering. The tiny pads don't help. It is advisable to check continuity with a multimeter between the headers and the pads where they should be connected
XSHUT not pulled up: My problem, this was that AZDelivery board says that it has a pull up in XSHUT (which works like an enable). But it could either be false, or badly implemented. Xshut needs to be high, 3v3/5v, otherwise, the sensor won't work. Bridge the XSHUT to Vin or implement a pull up and the problem will be solved.

I am using adafruit's library 1.1.2, and it works, with pullups, without pullups, connected to 5V and also connected to 3V3, with the
50ms delay, and connecting XSHUT to high (3V3 / Vin)
My board is vl53l0x from AZDelivery (5€ amazon)
I have tested the sensor with arduino nano and with ESP32, both work fine

Hope you guys find this useful <3
[esp32] [sensor] [i2c] [boot] [error]


text:
ESP8266 NodeMCU running out of heap
I'm trying to create SMS alarm using Twilio, Firebase and Arduino IDE. Using sensors I am measuring the temperature. If the temperature is higher than a specified value (ESP reads that value from Firebase Realtime Database), a SMS should be sent using twilio. I am also storing the measures in Firebase Realtime Database. The code worked well, until I tried to retrieve data from Firebase one more time and set data two more times. I believe that I'm running out of heap. I have only 10k heap left and cannot send SMS via Twilio. It only prints: connecting to api.twilio.com, but I don't receive the message.
Here's my code:
#include <ESP8266WiFi.h>
#include <FirebaseESP8266.h>
#include "OneWire.h"
#include "DallasTemperature.h"
#include "twilio.hpp"
#include <ESP8266WebServer.h>
#include <WiFiManager.h>

#define FIREBASE_HOST "***.firebaseio.com"
#define FIREBASE_AUTH "****"
#define WIFI_SSID "*****"
#define WIFI_PASSWORD "****"

const char fingerprint[] = "BC B0 1A 32 80 5D E6 E4 A2 29 66 2B 08 C8 E0 4C 45 29 3F D0";
const char* account_sid = "******";
const char* auth_token = "*******";

String to_number    = "+*****";
String from_number = "+*****";
String message_body    = "Hello from Twilio and the ESP8266!";

// The 'authorized number' to text the ESP8266 for our example
String master_number    = "+******";

// Optional - a url to an image.  See 'MediaUrl' here:
// https://www.twilio.com/docs/api/rest/sending-messages
String media_url = "";

// Global twilio objects
Twilio *twilio;
ESP8266WebServer twilio_server(8000);

//  Optional software serial debugging
#if USE_SOFTWARE_SERIAL == 1
#include <SoftwareSerial.h>
// You'll need to set pin numbers to match your setup if you
// do use Software Serial
extern SoftwareSerial swSer(14, 4, false, 256);
#else
#define swSer Serial
#endif

#define ONE_WIRE_BUS 4
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);
float temp1 = 0;

FirebaseData *firebaseData1 = new FirebaseData();
FirebaseData *firebaseData2 = new FirebaseData();
FirebaseData *firebaseData3 = new FirebaseData();
FirebaseData firebaseData;
FirebaseData firebaseData4;
FirebaseJson tms;
FirebaseJsonArray arr;

unsigned long sendDataPrevMillis = 0;

String path = "/Test/Stream";

int count = 0;
int sms = 0;
String c;
int b;

bool deallocated = false;

void printResult(FirebaseData &data);
void printResult(StreamData &data);

void streamCallback(StreamData data)
{

  Serial.println("Stream Data1 available...");
  Serial.println("STREAM PATH: " + data.streamPath());
  Serial.println("EVENT PATH: " + data.dataPath());
  Serial.println("DATA TYPE: " + data.dataType());
  Serial.println("EVENT TYPE: " + data.eventType());
  Serial.print("VALUE: ");
  printResult(data);
  Serial.println();
}

void streamTimeoutCallback(bool timeout)
{
  if (timeout)
  {
    Serial.println();
    Serial.println("Stream timeout, resume streaming...");
    Serial.println();
  }
}

void setup()
{

  Serial.begin(115200);

    WiFiManager wm;
    bool res;
    res = wm.autoConnect("AutoConnectAP","password"); // password protected ap

    if(!res) {
        Serial.println("Failed to connect");
        // ESP.restart();
    }
    else {
        Serial.println("connected...yeey :)");
    }

twilio = new Twilio(account_sid, auth_token, fingerprint);
  sensors.begin();
twilio_server.begin();

  Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH);
  Firebase.reconnectWiFi(true);

  //Set the size of WiFi rx/tx buffers in the case where we want to work with large data.
  firebaseData1->setBSSLBufferSize(1024, 1024);

  //Set the size of HTTP response buffers in the case where we want to work with large data.
  firebaseData1->setResponseSize(1024);

  //Set the size of WiFi rx/tx buffers in the case where we want to work with large data.
  firebaseData2->setBSSLBufferSize(1024, 1024);

  //Set the size of HTTP response buffers in the case where we want to work with large data.
  firebaseData2->setResponseSize(1024);

  if (!Firebase.beginStream(*firebaseData1, path))
  {
    Serial.println("------------------------------------");
    Serial.println("Can't begin stream connection...");
    Serial.println("REASON: " + firebaseData1->errorReason());
    Serial.println("------------------------------------");
    Serial.println();
  }

  Firebase.setStreamCallback(*firebaseData1, streamCallback, streamTimeoutCallback);
}

void loop()
{
  if (millis() - sendDataPrevMillis > 5000)
  {
    sendDataPrevMillis = millis();

sensors.requestTemperatures();
  temp1 = sensors.getTempCByIndex(0);
  Serial.print("");

tms.set(".sv", "timestamp");

 if (Firebase.getString(firebaseData, "002/alarm")) {

    if (firebaseData.dataType() == "string") {
      Serial.println(firebaseData.stringData());
    }

  } else {
    Serial.println(firebaseData.errorReason());
  }
int myInt = firebaseData.stringData().toInt();

if (temp1 < myInt) {
  if(Firebase.setInt(*firebaseData3, "/serial/sms", sms))
  {
      Serial.println("PASSED");
      Serial.println("PATH: " + firebaseData3->dataPath());
      Serial.println("TYPE: " + firebaseData3->dataType());
      Serial.print("VALUE: ");
      printResult(*firebaseData3);
      Serial.println("------------------------------------");
      Serial.println();
    }
    else
    {
      Serial.println("FAILED");
      Serial.println("REASON: " + firebaseData3->errorReason());
      Serial.println("------------------------------------");
      Serial.println();
    }
}

   if (Firebase.getInt(firebaseData4, "/serial/sms")) {

    if (firebaseData4.dataType() == "int") {
      Serial.println(firebaseData4.intData());
    }

  } else {
    Serial.println(firebaseData4.errorReason());
  }

if (temp1 > myInt) {
  if(firebaseData4.intData() < 1){
    sms++;
  String response;
      bool success = twilio->send_message(
                       to_number,
                       from_number,
                       message_body,
                       response,
                       media_url
                     );
    if(Firebase.setInt(*firebaseData3, "/serial/sms", sms))
  {
      Serial.println("PASSED");
      Serial.println("PATH: " + firebaseData3->dataPath());
      Serial.println("TYPE: " + firebaseData3->dataType());
      Serial.print("VALUE: ");
      printResult(*firebaseData3);
      Serial.println("------------------------------------");
      Serial.println();
    }
    else
    {
      Serial.println("FAILED");
      Serial.println("REASON: " + firebaseData3->errorReason());
      Serial.println("------------------------------------");
      Serial.println();
    }
}
}

    Serial.println(ESP.getFreeHeap());

    delay(0);

    count++;

    Serial.println("------------------------------------");
    Serial.println("Set Int...");

        arr.clear();
        arr.set("/[0]", temp1);
        arr.set("/[1]", tms);

    if (Firebase.push(*firebaseData2, path + "/Int", arr))
    {
      Serial.println("PASSED");
      Serial.println("PATH: " + firebaseData2->dataPath());
      Serial.println("TYPE: " + firebaseData2->dataType());
      Serial.print("VALUE: ");
      printResult(*firebaseData2);
      Serial.println("------------------------------------");
      Serial.println();
    }
    else
    {
      Serial.println("FAILED");
      Serial.println("REASON: " + firebaseData2->errorReason());
      Serial.println("------------------------------------");
      Serial.println();
    }

    if (count == 1)
    {
      Serial.println("Deallocate the Firebase Data objects after 3 times Firebasse call");

      //Need to stop the stream to prevent the readStream and callback to be called after objects deallocation
      Firebase.endStream(*firebaseData1);
      Firebase.removeStreamCallback(*firebaseData1);

      //Deallocate
      delete firebaseData1;
      delete firebaseData2;

      firebaseData1 = nullptr;
      firebaseData2 = nullptr;
      count = 0;
    }
  }

}

//Helper function for printing the response/received data
void printResult(FirebaseData &data)
{

  if (data.dataType() == "int")
    Serial.println(data.intData());
  else if (data.dataType() == "float")
    Serial.println(data.floatData(), 5);
  else if (data.dataType() == "double")
    printf("%.9lf\n", data.doubleData());
  else if (data.dataType() == "boolean")
    Serial.println(data.boolData() == 1 ? "true" : "false");
  else if (data.dataType() == "string")
    Serial.println(data.stringData());
  else if (data.dataType() == "json")
  {
    Serial.println();
    FirebaseJson &json = data.jsonObject();
    //Print all object data
    Serial.println("Pretty printed JSON data:");
    String jsonStr;
    json.toString(jsonStr, true);
    Serial.println(jsonStr);
    Serial.println();
    Serial.println("Iterate JSON data:");
    Serial.println();
    size_t len = json.iteratorBegin();
    String key, value = "";
    int type = 0;
    for (size_t i = 0; i < len; i++)
    {
      json.iteratorGet(i, type, key, value);
      Serial.print(i);
      Serial.print(", ");
      Serial.print("Type: ");
      Serial.print(type == FirebaseJson::JSON_OBJECT ? "object" : "array");
      if (type == FirebaseJson::JSON_OBJECT)
      {
        Serial.print(", Key: ");
        Serial.print(key);
      }
      Serial.print(", Value: ");
      Serial.println(value);
    }
    json.iteratorEnd();
  }
  else if (data.dataType() == "array")
  {
    Serial.println();
    //get array data from FirebaseData using FirebaseJsonArray object
    FirebaseJsonArray &arr = data.jsonArray();
    //Print all array values
    Serial.println("Pretty printed Array:");
    String arrStr;
    arr.toString(arrStr, true);
    Serial.println(arrStr);
    Serial.println();
    Serial.println("Iterate array values:");
    Serial.println();
    for (size_t i = 0; i < arr.size(); i++)
    {
      Serial.print(i);
      Serial.print(", Value: ");

      FirebaseJsonData &jsonData = data.jsonData();
      //Get the result data from FirebaseJsonArray object
      arr.get(jsonData, i);
      if (jsonData.typeNum == FirebaseJson::JSON_BOOL)
        Serial.println(jsonData.boolValue ? "true" : "false");
      else if (jsonData.typeNum == FirebaseJson::JSON_INT)
        Serial.println(jsonData.intValue);
      else if (jsonData.typeNum == FirebaseJson::JSON_FLOAT)
        Serial.println(jsonData.floatValue);
      else if (jsonData.typeNum == FirebaseJson::JSON_DOUBLE)
        printf("%.9lf\n", jsonData.doubleValue);
      else if (jsonData.typeNum == FirebaseJson::JSON_STRING ||
               jsonData.typeNum == FirebaseJson::JSON_NULL ||
               jsonData.typeNum == FirebaseJson::JSON_OBJECT ||
               jsonData.typeNum == FirebaseJson::JSON_ARRAY)
        Serial.println(jsonData.stringValue);
    }
  }
  else
  {
    Serial.println(data.payload());
  }
}

//Helper function for printing the response/received stream data
void printResult(StreamData &data)
{

  if (data.dataType() == "int")
    Serial.println(data.intData());
  else if (data.dataType() == "float")
    Serial.println(data.floatData(), 5);
  else if (data.dataType() == "double")
    printf("%.9lf\n", data.doubleData());
  else if (data.dataType() == "boolean")
    Serial.println(data.boolData() == 1 ? "true" : "false");
  else if (data.dataType() == "string" || data.dataType() == "null")
    Serial.println(data.stringData());
  else if (data.dataType() == "json")
  {
    Serial.println();
    FirebaseJson *json = data.jsonObjectPtr();
    //Print all object data
    Serial.println("Pretty printed JSON data:");
    String jsonStr;
    json->toString(jsonStr, true);
    Serial.println(jsonStr);
    Serial.println();
    Serial.println("Iterate JSON data:");
    Serial.println();
    size_t len = json->iteratorBegin();
    String key, value = "";
    int type = 0;
    for (size_t i = 0; i < len; i++)
    {
      json->iteratorGet(i, type, key, value);
      Serial.print(i);
      Serial.print(", ");
      Serial.print("Type: ");
      Serial.print(type == FirebaseJson::JSON_OBJECT ? "object" : "array");
      if (type == FirebaseJson::JSON_OBJECT)
      {
        Serial.print(", Key: ");
        Serial.print(key);
      }
      Serial.print(", Value: ");
      Serial.println(value);
    }
    json->iteratorEnd();
  }
  else if (data.dataType() == "array")
  {
    Serial.println();
    //get array data from FirebaseData using FirebaseJsonArray object
    FirebaseJsonArray *arr = data.jsonArrayPtr();
    //Print all array values
    Serial.println("Pretty printed Array:");
    String arrStr;
    arr->toString(arrStr, true);
    Serial.println(arrStr);
    Serial.println();
    Serial.println("Iterate array values:");
    Serial.println();

    for (size_t i = 0; i < arr->size(); i++)
    {
      Serial.print(i);
      Serial.print(", Value: ");

      FirebaseJsonData *jsonData = data.jsonDataPtr();
      //Get the result data from FirebaseJsonArray object
      arr->get(*jsonData, i);
      if (jsonData->typeNum == FirebaseJson::JSON_BOOL)
        Serial.println(jsonData->boolValue ? "true" : "false");
      else if (jsonData->typeNum == FirebaseJson::JSON_INT)
        Serial.println(jsonData->intValue);
      else if (jsonData->typeNum == FirebaseJson::JSON_FLOAT)
        Serial.println(jsonData->floatValue);
      else if (jsonData->typeNum == FirebaseJson::JSON_DOUBLE)
        printf("%.9lf\n", jsonData->doubleValue);
      else if (jsonData->typeNum == FirebaseJson::JSON_STRING ||
               jsonData->typeNum == FirebaseJson::JSON_NULL ||
               jsonData->typeNum == FirebaseJson::JSON_OBJECT ||
               jsonData->typeNum == FirebaseJson::JSON_ARRAY)
        Serial.println(jsonData->stringValue);
    }
  }
}

I deallocate the Firebase Data objects after every loop, however, I believe, I still don't have enough heap. Do you have any suggestions how to optimize the code and gain more memory?
Any help would be appreciated!

why do you use dynamic allocation? it fragments the heap and there is nothing to defragment it

Hi Juraj, thanks for your reply. I'm doing this for my school project and I'm new to Arduino, so I don't know much about dynamic allocation. Do you mean that there is something wrong with the way I create new Firebase variables (this part of the code: FirebaseData *firebaseData1 = new FirebaseData();)?

FirebaseData firebaseData1; should be good as global variable, but I don't know the Firebase library. how do they do this in the examples of the library?