body: I am using ublox zed F9P multi GNSS module. I have to program it for its configuration messages. Like I have to run a specific configuration of my receiver with the help of Arduino. I know arduino parse the GNSS sentences but can anyone tell me how to write code for ublox configuration commands such that that command can change setting of the receiver upon burning it in Arduino. Also, that code should retain in the receiver even if arduino is disconnected (closing arduino IDE console). Please help

title: send configuration commands with arduino

Answers: 1

body:
Here you find a **standard** library from arduino.

https://www.arduino.cc/reference/en/libraries/sparkfun-ublox-arduino-library/

You can find the documentation here:

https://github.com/sparkfun/SparkFun_Ublox_Arduino_Library


body:
I'm using arduino pro micro Atmega32u4 5v 16Mhz

I want to use it to make a HID Keyboard and Mouse but I ran out of pins so I was wondering if I can use the RX and TX pins as digital input pins. Will it work? Will it affect the communication of the arduino  to the computer?

title: Can I use arduino pro micro rx tx as digital pins

Answers: 2

body:
Using TX and RX on a 32U4 does not affect PC communication. It uses a competent different communication channel.

You can use those pins for digital operation with no problems, you just won't be able to use `Serial1` for communication with serial peripherals.

body:
Welcome to ASE.

1. Communication between the PC and the Arduino Pro Micro happens through the USB, unlike the Arduino Uno and Mega, which use the RX and TX lines.
2. In your case, the USB pins of the Micro are used to communicate with the PC. Hence, the RX and TX pins are available for digital input and output operations.

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

  [1]: https://i.stack.imgur.com/OVjSD.jpg


body:
I would like to be able to set the wifi SSID in the setup(), so I can customize it based on the MAC address or something similar. (avoiding to ESP's with the same code having the same SSID). However since it requires a const it does not seem to be possible, or am I missing something?

I'm using platformIO if that matters...

title: ESP32 softAP SSID not const

Answers: 2

body:
A `const` parameter to a function doesn't define what can be passed. It is, instead, a "promise" by the function that it will not modify the data you pass it.

In C when you pass a "string" (which is actually an array of characters) to a function you don't actually pass the string (as in the content). You really just pass a pointer to the location in memory where the string is stored.

It is perfectly possible for a function to then make modifications to that passed "string", which will be modifying the original data in memory. That is not really desirable in many situations.

So by flagging the parameter as `const` you tell the compiler "From this moment onwards the data pointed to by this variable must not be changed". All attempts to write to the memory using that variable will be blocked by the compiler.

There's no actual difference between, say, a `char *` and a `const char *` other than how the compiler treats attempts to write to them.

When you pass a `char *` to a function that is expecting a `const char *` the pointer is "upgraded" to a constant so that no attempts to change the data will be allowed.

The converse is not allowed though - you can't (or shouldn't) try and convert a `const char *` to a `char *` as on some systems ("Princeton" architecture systems with a single monolithic memory address space) the pointer could be pointing to data stored in flash, and an attempt to write to that will obviously fail.

The function you are calling to set the SSID is merely promising that it won't attempt to change the data you pass it. It doesn't matter if it's a constant or not - both will be treated as a constant and not be changed.

body:
The library [WifiManager][1] might work for you, it’s got a captive portal to configure your wifi connection on the fly. It’s got quite some configuration options to shape it to your will if I am not mistaken, I hope it serves you well.

  [1]: https://github.com/zhouhan0126/WIFIMANAGER-ESP32


body:
I need to read a potentiometer value from an ATTINY85.
I have big fat 10K POT but for this use case I need it to be very small so I used a salvaged 2.4K one, the kind that is soldered directly onto a PCB.

I am using tinkercad to prototype my project and I am facing a very weird problem. Everytime I read from the POT Pin, I get the value of 512 (using the debugger)

Here is a screenshot of my prototype:
[![enter image description here][1]][1]

The goal is to power the circuit and the lamp (does not matter what is there, consider it just a load) with a 9V battery, use a 5V regulator to power the ATTINY85 and use an NPN transistor to turn the lamp/load on or off.

For information, the whole regulator and transistor setup is tested and works like a charm.

Here is the code I wrote for the this case:

    void setup()
    {
      pinMode(PB0, INPUT);
    }

    int potValue = 0;

    void loop()
    {
      potValue = analogRead(PB0);
      delay(100);
    }

Not real fancy right?
Now no matter what use for the POT, and I tried 2.4K, 10K and up to 100K, the value read by the ATTINY is always 512.

Do you see something wrong in this setup?
Could it be a bug in tinkercad? (I'd be surprised though)

I could try and share this circuit within tinkercad if someone would be willing to have a look...

EDIT: I just tried with PB2 as suggested but not the value is always 58:
[![enter image description here][2]][2]

  [1]: https://i.stack.imgur.com/Xyzc5.png
  [2]: https://i.stack.imgur.com/5DHK8.png

title: ATTINY85 and POT

Answers: 1

body:
[Port PB0 is not an ADC (analog input) pin on the ATTiny85](https://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-2586-AVR-8-bit-Microcontroller-ATtiny25-ATtiny45-ATtiny85_Datasheet.pdf).

Available pins of the ATTiny85 (from the Atmel ATtiny 25, 45, 85 datasheet):

[![ATtinyx5 pinout][1]][1]Choose PB2, PB3, PB4 or PB5 if you need an analog input.

Additional information: When built in TinkerCAD, using PB2 as an analog input does not seem to work correctly and produces a fixed value. Using PB3 did work correctly however. This might be a bug in TinkerCAD.

  [1]: https://i.stack.imgur.com/ksObn.jpg


body:
So, I am new with arduino and am to build a robot using motors, for that I have bought l298n H bridge motor driver. I have watched various site and videos ,to make sure not to make a mistake but, in every video and sites

I have found their connecting the motor direction controller to

  [![Diagram][1]][1]

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

IN1 -> Arduino Pin 8 (digital) and IN2 -> Arduino Pin 7 (digital)

Till then it was fine ... Now the fishy thing for me is

IN3 -> Arduino Pin 5 (PWM) and IN4 -> Arduino Pin 4 (Digital)

Why connect to a Digital and a PWM?

For E1 and E2 I am sure that the wires should be connected to the PWM (~) pins for arduino, to control speed of the motor..

But, Should not I be able to connect IN3 and IN4 both to rest of the digital pins 12, 13 or 2,4 Just Like IN1 and IN2 is connected to 7 and 8.

But the IN3 and IN4 is connected to a PWM and a Digital pin.

Conclusion,

So can I use all the unused non PWM digital pins to connect the motor direction control?

Thanks for your precious time..!

title: Why should I connect the l289n motor driver wires to specific arduino pins only?

Answers: 1

body:
Pwm is just a digital out with extra fancy on off controls.  You can use any digital out if you do not need those extra features.

To just signal a single H bridge (1 motor of your l289n) for forward, reverse, stop, one only needs two digital outs.

I recommend you get the hang of your h bridge first - signaling it on a bread board with vcc (usually 5v but can be 3.3) and ground rather than the arduino.  Then once you understand the motor directions that result from your wiring, write the code accordingly.  This tends to result in:
1) fewer fried arduinos
2) code with functions and signals named after their intent (rather than having to mix forward and reverse)


body:
I am trying to get a nice sounding varying PWM to DAC, and intend to use a [Sallen Key][1] as part of an active low pass filter.

I set the Fast PWM at a max of 255 ([WGM1\[0-3\] = 5][2]) and set/clear OC1A upon comparing with OCR1A `(1<< COM1A1)`

I also update the value of OCR1A in 64 distinct steps, changing those steps around 15'000 times a second to create a specific sinusoidal shape.

As the chip works at 16 Mega Hertz, does this mean that one cycle of PWM is `16'000'000/256=` 62.5 Kilo Hertz? If not, what is its resolution

Thank you!

  [1]: http://sim.okawa-denshi.jp/en/OPstool.php
  [2]: http://sculland.com/ATmega168/Interrupts-And-Timers/16-Bit-Timer-Setup/

title: Fast PWM: Resolution in hertz

Answers: 1

body:
With the help of the comments, I decided to use variable PWM max values to match absolutely with the frequency. This resulted in a crispier sound that *actually doesn't need the Sallen Key anymore*.

For example, a low C natural, or `261.6Hz`, updated `32` times for `8` full cycles of PWM give us, for a 16MHz chip, an period and amplitude of `238`.

This means that having a prescaler of `8` (`CS01`), a period (`OCR0A`) AND a max potential duty cycle (`ICR1`) of `238`, and going through 32 iterations of the sound sought for, I got the sound that I wanted and none of the wave groove that comes with a pulse duty cycle cut short.

Sure, it means less granularity when it comes to a Bb with a max duty cycle of 133, however it worked for me.


body:
I'm really new to Arduino and wanted to know if I can make Arduino a permanent controller?
and could you help me with a cheaper alternative?
I also wanted to know about "fuse", i read it somewhere that i can protect the code from someone else who wishes to use, using a FUSE.

Thanks a lot for helping me out:)

title: Can Arduino UNO permanently store a code?

Answers: 1

body:
> idk if the arduino stores the code for ever

The code is saved in the flash memory, which is non-volatile. It does not lose its content during power cycles. Also, when looking at the time dimension, it holds the code over a very long time, though not for ever. The [datasheet of the Atmega328p][1] (the microcontroller in the Arduino Uno or Nano) states:

> Reliability Qualification results show that the projected data retention failure rate is much less than 1 PPM over 20 years at 85°C or 100 years at 25°C.

So over 20 years at a temperature of 85°C you can get 0.0001% of data loss in the flash memory. At normal room temperature you can get that loss in 100 years. So significantly longer than the lifetime of most electronic products.

> I also wanted to know about "fuse", i read it somewhere that i can protect the code from someone else who wishes to use, using a FUSE.

There are different ways and levels of protection. Though that is a more advanced topic, that you should tackle, when your product is finished otherwise. There are multiple resources on the web about this. The first place to look is always the datasheet of the used microcontroller. First part might be to not use the standard Arduino bootloader, but your own. And then you can set 2 fuses for getting different levels of protection (write protection, read protection), that will lock out 99% of the people. [This question][2] on Electrical SE might also be interresting for you. You can find many resources on the web by searching for something like "Arduino code protection" or "AVR code protection" (if you are using an AVR based microcontroller like with the Arduino Uno/Nano/Mega)

---

Apart from that I also would open the question to you, if your code is really that new and ingenious, that you need to protect it from being read that way? It might totally be, that this is the case for you. But from my perspective the probability is very low. I cannot say of my own codes, that they are worth the hassle of protection. And it also depends on what you really want to prevent that way.

For context: When you program the Arduino (or any microcontroller) with your C/C++ program, the text of the program is not saved on the Arduino. Instead the code is first converted to Assembler code and then compiled into binary machine code. On that level all the nice concepts of the higher level languages are not present, so they are done by multiple lower level functions (for example loops are jumps with conditions). An attacker might read the machine code back from the microcontroller. The biggest threat here is, that he would just copy it to a new microcontroller.

If he wants to get "code" from it, he would invoke a disassembler, which converts the machine code back to the assembler language. But at this point all symbols (names of variables, functions, ...) are lost, because they are not saved in the original machine code from the start. Reading and understanding such a code is very difficult, especially, if your code is rather big and complex. Most times it would be easier for an attacker to just reverse engineer your code based on the behavior of the original microcontroller.

So in the end, you cannot really prevent people from building counterfeit products. That's what a patent is for.

This does not mean, that you should not use the code protection. Just do a realistic security assessment and then decide, if it is worth the hassle.

  [1]: http://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-7810-Automotive-Microcontrollers-ATmega328P_Datasheet.pdf
  [2]: https://electronics.stackexchange.com/questions/53282/protecting-avr-flash-from-reading-through-isp


body:
I would eventually like to use a Due as a custom USB device PC-side (through programming port) while using it as a USB Host on the native port.
Adding the programming port endpoints (perhaps willingly removing the CDC endpoints) means I may break USB descriptors, or USB to PC communication generally speaking during development.

On the Micro that's not a problem because a double reset input lets me access the bootloader for 8s and reprogram the board even though I've removed CDC endpoints altogether. But on the Due, which I am not familiar with, I can see that a double reset input does not seem to have the same effect as my script starts right away. So I am quite scared to begin messing with the USB communications if I might just break my Due permanently (or rather, until I can recover it directly accessing the MCU).

Hence the question: is there some equivalent to the bootloader recovery of the Micro (& other older boards) on the Due ?

title: How to access bootloader recovery mode (like the Micro) or equivalent on the Due?

Answers: 0


body:
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 <WiFi.h>
#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);
    }
  }
}
 ´´´

title: Two sensors on same ESP-32 board

Answers: 0


body:
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

title: working with ultrasonic sensors

Answers: 1

body:
> 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][1], 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.

  [1]: http://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-7810-Automotive-Microcontrollers-ATmega328P_Datasheet.pdf


body:
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);
    }

title: Problem with a class? SHT21 library

Answers: 0


body:
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...

title: iterate through 8 thermocouple sensors (MAX31856)

Answers: 1

body:
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()
    };


body:
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);
  }```

title: arduino robot wont move

Answers: 0


body:
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

title: Having a bunch of global variables or calculate them on the go on an Arduino, as far as memory is concerned

Answers: 0


body:
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 (https://arduino.stackexchange.com/questions/9296/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?

title: Object composition (class uses class)

Answers: 1

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

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

> ```cpp
> _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:

```cpp
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:

```cpp
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.


body:
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:

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

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

It supposed that i should only receive "O" or "F". Any suggestion??

thanks in advanced,

title: Wrong data receiving in my Arduino by bluetooth

Answers: 1

body:
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][1] library (AltSoftSerial), but I couldn't get it work. I have usde the pin 8 and 9, but nothing.

  [1]: https://www.pjrc.com/teensy/td_libs_AltSoftSerial.html


body:
There are lots of examples on the internet on how to build Arduino from scratch such as [IN THIS LINK][1]. I will like to do the same but with the esp32.

I have this development board:

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

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

-------

Now the question
-

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

[![enter image description here][4]][4]

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:

1. 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?

2. 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.

3. 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?

  [1]: https://www.arduino.cc/en/main/standalone
  [2]: https://i.stack.imgur.com/mJwJp.png
  [3]: https://www.youtube.com/watch?v=mBaS3YnqDaU
  [4]: https://i.stack.imgur.com/l2YjS.png

title: Using esp-wroom-32 without a development board

Answers: 3

body:
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:

[![ESP32 flash burner tool][1]][1]

  [1]: https://i.stack.imgur.com/nXXQ1.jpg

body:
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:

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

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/

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

body: 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.


body:
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.

title: Copy outbound data of Serial to Serial1 for Pro Micro

Answers: 0


body:
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.

title: Teensy 4.1 Ethernet Throughput

Answers: 0


body:
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);
    }

title: How to combine two codes in arduino?

Answers: 1

body:
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();
}

~~~


body:
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

title: Monitor two baud rates

Answers: 1

body:
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.


body: 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

title: Esp 32 keeps disconnecting from com port

Answers: 0


body: 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?

title: AT firmware upgrade in ESP-01 using Arduino UNO R3

Answers: 1

body:
> 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.


body:
I want to pass a lambda function as an argument to a method. Example:

```cpp
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?

title: How do I use lambda functions in Arduino?

Answers: 1

body:
`std::function` is <s>not supported by the Arduino environment</s>.
(**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

```cpp
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

```cpp
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...


body:
I have a [sparkfun AVR Pocket Programmer][1] 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:

 1. I have tried uploading a plain bootloader, as well as a running program via the ISP programmer before attempting the FTDI.
 2. I have tried direct connecting the FTDI DTR/RTS reset to the Atmega328 pin1.
 3. 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.
 4. I have tried a different brand of FTDI FT232RL chip. No difference.
 5. 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][2] 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?

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

Thanks!

[Atmega328 Spec Sheet PDF][4]

  [1]: https://www.sparkfun.com/products/9825
  [2]: https://www.arduino.cc/en/Main/Standalone
  [3]: https://i.stack.imgur.com/ZcQl7m.jpg
  [4]: http://ww1.microchip.com/downloads/en/DeviceDoc/ATmega48A-PA-88A-PA-168A-PA-328-P-DS-DS40002061B.pdf

title: How to upload a sketch to an atmega328 via FTDI FT232RL UART and Arduino IDE?

Answers: 1

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

[![Upload Using Programmer != Burn Bootloader][1]][1]

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.

[![atmega328 ftdi top view][2]][2]
[![ftdi setup left][3]][3]
[![ftdi setup right][4]][4]

  [1]: https://i.stack.imgur.com/mgbie.png
  [2]: https://i.stack.imgur.com/zqQdE.jpg
  [3]: https://i.stack.imgur.com/u64u0.jpg
  [4]: https://i.stack.imgur.com/bSlzP.jpg


body:
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=777000&algo=ABA.MBE&ao=1&asc=36860&meid=c76077722d4348e88152fa6c7f32c005&pid=100009&rk=1&rkt=1&sd=181329341315

Also should i change my use Li-ion battery 18650 x2 instead of the 6LR61 9v battery i used

title: L298N motor driver and battery issues

Answers: 2

body: 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.

body:
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.


body:
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.

title: Read from Blynk terminal number to arduino

Answers: 0


body:
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..

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

  [1]: https://i.stack.imgur.com/cvEy7.jpg

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

Parts:

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

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

3. Arduino
(Required amp is 40*12)

The circuit Explanation:

1. The Orange wires of servos are signal wires connected to the pins of Arduino.
2. A 750 ohm resistor is connected to the positive terminals of each motor, from which, voltage is regulated for the motor.
3. The motor grounds have been connected to the ground of the battery.
4. Ground of Arduino has been connected to the ground terminal of the battery. So now, ground of the battery and the Arduino is same.

5. 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....

title: 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?

Answers: 1

body:
> 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.


body:
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);
    }}

title: Arduino wait for incomming data from blynk terminal

Answers: 0


body:
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:

```cpp
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.

title: Is it possible to send 2 or more o/p signal at the same time?

Answers: 2

body: 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.

body:
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:

```c++
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][328p], 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.

[328p]: http://ww1.microchip.com/downloads/en/DeviceDoc/ATmega48A-PA-88A-PA-168A-PA-328-P-DS-DS40002061B.pdf


body:
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 :)

title: Failed to boot VL53L0X: VL53L0X Error: -6

Answers: 4

body:
From the [VL53L0X API documentation][1] 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?

  [1]: https://documentation.help/VL53L0X-API/group__VL53L0X__define__Error__group.html#gab1bcfe4c791fa91012ccf489a260430a

body: 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.

body:
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:

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

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

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

body:
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:

 1. *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)
 2. *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**.
 3. *Powering problem 3*: If you feed it with an external source, **unify grounds with the board**, don't forget it
 4. *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
 5. *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
 6. *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]


body:
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!

title: ESP8266 NodeMCU running out of heap

Answers: 0


body:
I'm working on water level detector using lolin nodemcu v3 and AJ-SR04M Sensor, a water proof ultrasonic sensor. It is working fine at close distance less than one meter or so. However for long distance > 1 meter, I get varying results.
[![enter image description here][1]][1]

Using the following code:
<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->
    void setup() {

      Serial.begin (115200);
      pinMode(TRIGGER, OUTPUT);
      pinMode(ECHO, INPUT);
      pinMode(BUILTIN_LED, OUTPUT);
    }

    void loop() {

      long duration, distance;
      digitalWrite(TRIGGER, LOW);
      delayMicroseconds(2);

      digitalWrite(TRIGGER, HIGH);
      delayMicroseconds(10);

      digitalWrite(TRIGGER, LOW);
      duration = pulseIn(ECHO, HIGH);
      distance= duration*0.034/2;

      Serial.print("Distance: ");
      Serial.print(distance);
      Serial.println(" cm");
      delay(1000);
    }
<!-- end snippet -->
This is what I get in the monitor for the same distance 2-3 meters:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
    Distance: 141 cm
    Distance: 135 cm
    Distance: 225 cm
    Distance: 195 cm
    Distance: 226 cm
    Distance: 226 cm
    Distance: 129 cm
    Distance: 135 cm
    Distance: 134 cm
    Distance: 146 cm
    Distance: 136 cm
    Distance: 129 cm
    Distance: 154 cm
    Distance: 123 cm
    Distance: 147 cm
    Distance: 226 cm
    Distance: 181 cm
    Distance: 137 cm
    Distance: 134 cm
    Distance: 136 cm
    Distance: 137 cm
    Distance: 145 cm
    Distance: 227 cm
    Distance: 179 cm
    Distance: 226 cm
    Distance: 226 cm
    Distance: 101 cm
    Distance: 134 cm
    Distance: 270 cm
    Distance: 294 cm
    Distance: 266 cm
    Distance: 281 cm
    Distance: 146 cm
    Distance: 279 cm
    Distance: 128 cm
    Distance: 579 cm
    Distance: 138 cm
<!-- end snippet -->
**So, is there a way to make it right or that means my sensor is faulty.**

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

title: Data Fluctuation with AJ-SR04M Sensor

Answers: 0