text:
How to prevent flickering relay upon waking from deep sleep using ESP01 board?
I have a cheap ESP01 relay module and am using it with ESPEasy. I soldered the GPIO pin 16 to RST to allow deep sleep and that all works great.
However when the unit wakes up the relay flickers quite a bit. The application I had in mind was for a 12v fridge which draws quite a bit of current on start up. I think this flickering would damage the fridge compressor or controller pretty quickly, not to mention wearing out the relay itself.
I need the unit to wake up from deep sleep, and keep the relay in the off position, unless triggered by some external criteria.
Perhaps a capacitor would absorb the pin high voltage for a short period until it's booted? Trouble is that I don't really want to hack the module, I'll probably break something.

perhaps the starting point is to ask which IO pin does not change state when ESP01 wakes up ... that relay module may not be suitable for controlling a 12 V fridge (dependent on the current drawn by the fridge at startup)

"Trouble is that I don't really want to hack the module", you already hacking the ESP-01 by connecting IO16 to RST, so what's the difficulty of adding a capacitor compare to the ESP-01 hack?

well yes, that was already pretty difficult, and I succeeded in two out of three I've tried. But these relay boards are hard to come by where I am, so I'd want to be pretty confident to try that. I've already had to remove one smd resistor to get the thing to boot. each time I'm adding more risk of destroying the board

The only two pins that don't glitch or change state during reset and boot are GPIO4 and GPIO5, and neither of them are brought out to the 2x4 header on an ESP-01.
https://rabbithole.wwwdotorg.org/2017/03/28/esp8266-gpio.html
All of the other pins will make your relay click or chatter.  Pick a different module, or try soldering a wire onto GPIO4 or 5. The boot time is ~ 150ms long, so it'd take a long time constant R-C circuit to filter it out, on the order of 1/2 second or more.

Apparently it's a pretty common issue for people using this board. There are a  couple of solutions here that I will try: https://github.com/IOT-MCU/ESP-01S-Relay-v4.0/issues/1
The most non invasive one with Tasmoto firmware didn't work in my case. So I will try another pin and if that fails, bite the bullet and introduce a capacitor.


text:
WeMos D1 ESP-Wroom-02 Mother Board ESP8266 - where is reset pin for deep-sleep
This item was bought for battery use with deep sleep purposes. For doing so in ESP8266 reset pin must be connected to Gnd pin in order to wake up. This board lacks a reset on- board pin.
Since spec states it has a such capabilities - I wonder if someone has succeeded with putting it to sleep ( and wake it back on ).
PS - I know that on-chip gpio16 can be soldered to on-chip gnd - I'm hoping there is a more elegant, not soldering invloved, solution.
Guy

So the board does not break out the reset pin. You can try to solder a wire to the reset button. But what is your actual question? Asking for a specific, cheap, bad documented one from aliexpress most likely will not lead to good results. The possibility, that someone else here used the exact same module, is very low. Also: Where does it state, that it has a broken out reset pin? I don't see anything like that on the site.

Both GPIO16 and RST are available on ESP-WROOM-02 module, see https://www.espressif.com/sites/default/files/documentation/0c-esp-wroom-02_datasheet_en.pdf.

@jsotola question is rephrased now.

@chrisl I hope question  is clearer now. I tried to create such "soldering" as you suggested - but a awke up did not occur

This support page has the instructions for enabling deep sleep:
Support for WeMos D1 ESP-Wroom-02 Nodemcu
edit by Guy: in short, solder/connect pins as shown circled in red:

source: Stack Exchange

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

sort: votes


text:
ARDUINO expected ';' before 'delay'
I want to shine LED in 64 of 255 duty cycles = level of brightness but it pops up this error (see picture). Can anybody tell me why and help me ? Thank you.
void setup() {
  // put your setup code here, to run once:

}

void loop() {

  analogWrite(11, 64)
  delay{1000};
  analogWrite(11, 0)
  delay(1000);

  // put your main code here, to run repeatedly:

}

The error message (and the title of your post) tells you everything you need to fix your code, really.

You should write ";" end of each lines.
analogWrite(11, 64);
delay(1000);
analogWrite(11, 0);
delay(1000);

This advice helped a lot :) Great, it works already.
Thank you very much Furkan

Did you check connects? You should check that long leg of led is connected with arduino.

It works already, thank you very much. I had also broken LED and with new one it works perfectly :)

Good job. See you...

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


text:
How to Adjust MQ131 Sensor?
The problem
Hey. I'm trying to use the sensor Mq131 to measure some ozone data in a closed environment, but I'm having some bad time to adjust the trim in the sensor and get results in ppb. By searching on the internet I could not find any elucidative manual/instruction.

My Hardware set
As my first attempt, I've made the following wiring with the Arduino UNO and the sensor module.

Notice that my potentiometer does not have any indication of the resistance reached when spinning the potentiometer screw.

My software script
To get the value of tension in the output from the sensor I'm using the following approach.
int sensor_AOUT = A1; //connected from AOUT to the sensor to A1 on the Arduino
int sensor_DOUT = 2; //connect DOUT from sensor to Arduino pin 2
int wartosc_AOUT; //variable for the value of AOUT
int wartosc_DOUT; //variable for the value of DOUT

void setup() {
 Serial.begin(9600); //start the monitor serial port
 pinMode(2, INPUT); //set pin 2 as input

}

void loop() {

 wartosc_AOUT = analogRead(sensor_AOUT); //load values from AOUT
 wartosc_DOUT = digitalRead(sensor_DOUT); //load values DOUT

 Serial.print("D0: "); //display on serial monitor
 Serial.print(wartosc_DOUT);
 Serial.print(" -- A0: ");
 Serial.println(wartosc_AOUT);
 delay(200); //delay between consecutive readings
 }

which gives me values 30 < A0 <50. How can I get a value in ppb (parts per billion) and how can I calibrate the potentiometer screw?

Sensor Datasheet
The datasheet of this sensor can be found in this link.

what do you expect the potentiometer to do? ... you will need to have the datasheet to determine the ppb conversion ... another way to calibrate is to compare the output against an already calibrated sensor

@jsotola I've edited the question including the datasheet of the sensor. I would expect that the potentiometer enhances the sensibility of the sensor. I don't have any other calibrated sensor here, so I can not consider this option.


text:
How to post image using Arduino HTTPClient
I am using arduino HTTPClient to do the post request in ESP32. Can anyone help me with the part where I will be able to post an image file along with some data.
The below code works perfectly fine with only sending user_name and image_type-
#include <HTTPClient.h>

http.begin("https://www.somelink.com/post-image");

http.addHeader("Content-Type", "application/x-www-form-urlencoded");

String httpRequestData = "user_name=Shidhartha&image_type=Outdoor";

int httpResponseCode = http.POST(httpRequestData);
if(httpResponseCode > 0){
  String response = http.getString();
  Serial.println(response);
}else{
  Serial.print("Error on sending POST: ");
  Serial.println(httpResponseCode);
}

this is not Arduino code. this is C code using esp8266 SDK

Thank you for your comment @Juraj . Can you share any code or link for esp32? It would really help me.

You could use the HttpClient library. but there are only download examples

ESP-IDF specific code is off-topic for this site. You should be asking about ESP-IDF code on the ESP-IDF forums. We deal with the Arduino API abstraction and libraries only.

@Majenko I have edited my post based on your comment. Any more suggestions will be very helpful..

Are you missing void main(void)?

Tutorial from randomnerd is absolutely correct. You can upload multiple types of files like JPEG, TXT, LOG, XML and all others.

Below is the perfectly working code I got from here.
#include <Arduino.h>
#include <WiFi.h>
#include "soc/soc.h"
#include "soc/rtc_cntl_reg.h"
#include "esp_camera.h"

const char* ssid = "REPLACE_WITH_YOUR_SSID";
const char* password = "REPLACE_WITH_YOUR_PASSWORD";

String serverName = "192.168.1.XXX";   // REPLACE WITH YOUR Raspberry Pi IP ADDRESS
//String serverName = "example.com";   // OR REPLACE WITH YOUR DOMAIN NAME

String serverPath = "/upload.php";     // The default serverPath should be upload.php

const int serverPort = 80;

WiFiClient client;

// CAMERA_MODEL_AI_THINKER
#define PWDN_GPIO_NUM     32
#define RESET_GPIO_NUM    -1
#define XCLK_GPIO_NUM      0
#define SIOD_GPIO_NUM     26
#define SIOC_GPIO_NUM     27

#define Y9_GPIO_NUM       35
#define Y8_GPIO_NUM       34
#define Y7_GPIO_NUM       39
#define Y6_GPIO_NUM       36
#define Y5_GPIO_NUM       21
#define Y4_GPIO_NUM       19
#define Y3_GPIO_NUM       18
#define Y2_GPIO_NUM        5
#define VSYNC_GPIO_NUM    25
#define HREF_GPIO_NUM     23
#define PCLK_GPIO_NUM     22

const int timerInterval = 30000;    // time between each HTTP POST image
unsigned long previousMillis = 0;   // last time image was sent

void setup() {
  WRITE_PERI_REG(RTC_CNTL_BROWN_OUT_REG, 0);
  Serial.begin(115200);

  WiFi.mode(WIFI_STA);
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    Serial.print(".");
    delay(500);
  }
  Serial.println();
  Serial.print("ESP32-CAM IP Address: ");
  Serial.println(WiFi.localIP());

  camera_config_t config;
  config.ledc_channel = LEDC_CHANNEL_0;
  config.ledc_timer = LEDC_TIMER_0;
  config.pin_d0 = Y2_GPIO_NUM;
  config.pin_d1 = Y3_GPIO_NUM;
  config.pin_d2 = Y4_GPIO_NUM;
  config.pin_d3 = Y5_GPIO_NUM;
  config.pin_d4 = Y6_GPIO_NUM;
  config.pin_d5 = Y7_GPIO_NUM;
  config.pin_d6 = Y8_GPIO_NUM;
  config.pin_d7 = Y9_GPIO_NUM;
  config.pin_xclk = XCLK_GPIO_NUM;
  config.pin_pclk = PCLK_GPIO_NUM;
  config.pin_vsync = VSYNC_GPIO_NUM;
  config.pin_href = HREF_GPIO_NUM;
  config.pin_sscb_sda = SIOD_GPIO_NUM;
  config.pin_sscb_scl = SIOC_GPIO_NUM;
  config.pin_pwdn = PWDN_GPIO_NUM;
  config.pin_reset = RESET_GPIO_NUM;
  config.xclk_freq_hz = 20000000;
  config.pixel_format = PIXFORMAT_JPEG;

  // init with high specs to pre-allocate larger buffers
  if(psramFound()){
    config.frame_size = FRAMESIZE_SVGA;
    config.jpeg_quality = 10;  //0-63 lower number means higher quality
    config.fb_count = 2;
  } else {
    config.frame_size = FRAMESIZE_CIF;
    config.jpeg_quality = 12;  //0-63 lower number means higher quality
    config.fb_count = 1;
  }

  // camera init
  esp_err_t err = esp_camera_init(&config);
  if (err != ESP_OK) {
    Serial.printf("Camera init failed with error 0x%x", err);
    delay(1000);
    ESP.restart();
  }

  sendPhoto();
}

void loop() {
  unsigned long currentMillis = millis();
  if (currentMillis - previousMillis >= timerInterval) {
    sendPhoto();
    previousMillis = currentMillis;
  }
}

String sendPhoto() {
  String getAll;
  String getBody;

  camera_fb_t * fb = NULL;
  fb = esp_camera_fb_get();
  if(!fb) {
    Serial.println("Camera capture failed");
    delay(1000);
    ESP.restart();
  }

  Serial.println("Connecting to server: " + serverName);

  if (client.connect(serverName.c_str(), serverPort)) {
    Serial.println("Connection successful!");
    String head = "--RandomNerdTutorials\r\nContent-Disposition: form-data; name=\"imageFile\"; filename=\"esp32-cam.jpg\"\r\nContent-Type: image/jpeg\r\n\r\n";
    String tail = "\r\n--RandomNerdTutorials--\r\n";

    uint16_t imageLen = fb->len;
    uint16_t extraLen = head.length() + tail.length();
    uint16_t totalLen = imageLen + extraLen;

    client.println("POST " + serverPath + " HTTP/1.1");
    client.println("Host: " + serverName);
    client.println("Content-Length: " + String(totalLen));
    client.println("Content-Type: multipart/form-data; boundary=RandomNerdTutorials");
    client.println();
    client.print(head);

    uint8_t *fbBuf = fb->buf;
    size_t fbLen = fb->len;
    for (size_t n=0; n<fbLen; n=n+1024) {
      if (n+1024 < fbLen) {
        client.write(fbBuf, 1024);
        fbBuf += 1024;
      }
      else if (fbLen%1024>0) {
        size_t remainder = fbLen%1024;
        client.write(fbBuf, remainder);
      }
    }
    client.print(tail);

    esp_camera_fb_return(fb);

    int timoutTimer = 10000;
    long startTimer = millis();
    boolean state = false;

    while ((startTimer + timoutTimer) > millis()) {
      Serial.print(".");
      delay(100);
      while (client.available()) {
        char c = client.read();
        if (c == '\n') {
          if (getAll.length()==0) { state=true; }
          getAll = "";
        }
        else if (c != '\r') { getAll += String(c); }
        if (state==true) { getBody += String(c); }
        startTimer = millis();
      }
      if (getBody.length()>0) { break; }
    }
    Serial.println();
    client.stop();
    Serial.println(getBody);
  }
  else {
    getBody = "Connection to " + serverName +  " failed.";
    Serial.println(getBody);
  }
  return getBody;
}

I follow this too but I wish we could use the http client for this. Would make life wayy easier


text:
Relay with NodeMCU is not working
I'm using a Relay Channel and NodeMCU(8266-WIFI). When i trigger the connection, LED Turns ON in Node MCU But the Relay connection is not working. I'm not sure what is the issue, Please help to fix it..
My Pin connection as follows.

NodeMCU (VIN) -> Relay (VCC)
NodeMCU (G) -> Relay (G)
NodeMCU (D1) -> Relay (IN4)

My code as follows,
#include <ArduinoJson.h>
#include <ESP8266WiFi.h>
#include <FirebaseCloudMessaging.h>
#include <Firebase.h>
#include <FirebaseHttpClient.h>
#include <FirebaseArduino.h>
#include <FirebaseError.h>
#include <FirebaseObject.h>

// Set these to run example.
#define FIREBASE_HOST "xxx-xxxx.firebaseio.com"
#define FIREBASE_AUTH "xxxxxx"
#define WIFI_SSID "xxxx"
#define WIFI_PASSWORD "xxxxx"

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

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

  pinMode(D1, OUTPUT);
  pinMode(LED_BUILTIN, OUTPUT);

  Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH);
  Firebase.set("LED_STATUS",0);
}

int n = 0;

void loop() {
  // Get value
  n=Firebase.getInt("LED_STATUS");

  if (n==1) {
     digitalWrite(D1, LOW);
     digitalWrite(LED_BUILTIN, LOW);
     Serial.print("LED is ON ");
     Serial.println(Firebase.getInt("LED_STATUS"));
     delay(1000);
  }
 else{
   //LED_BUILTIN
   digitalWrite(D1, HIGH);
   digitalWrite(LED_BUILTIN, HIGH);
   Serial.print("LED is OFF ");
   Serial.println(Firebase.getInt("LED_STATUS"));
   delay(1000);
 }

}

the red wire is not connected to anything

you mean the Main power Red wire right ?I removed the connection to take photo..

What version of the NodeMCU is that?

On back of board it mentioned, "Node MCU V3"
and in front top right corner , ver 0.1

Does the relay work when you connect IN4 to Vcc ?

No. That is the problem, When i trigger the power, the relay port is not closing and light bulb is not getting power

Can the relay module work with 3.3V logic signal?

If you attach and detach IN4 to VCC on the NodeMCU, does the relay click when you attach it? If it doesn't, and you still have VCC on the relay board connected to VIN(5V) on the NodeMCU, and GND on the relay board connected to GND on the NodeMCU, something is wrong with either your wiring or the board. Try another IN on the board and see if one is faulty. Those modules will work fine with 3v3 control signal coming from the NodeMCU due to the opto-isolator on the inputs of the relay board. If it does click, something is wrong with your code.

@chris could you explain a bit more please. I'm a very beginner. i bought a 5v relay board, but i'm not sure what output nodeMCU provides, I hope it is same 5v ?

@peter-feerick : Click ? U mean a click sound will come when i connect IN4 to vcc on NodeMCU ?

But VCC is connected to VIN right ?

@GaneshKumar Yes, a click sound from the relay, as it is a electro-mechanical switch, hence you should hear when it activates/deactivates. The yellow jumper to the side connects the VCC used to power the relays to the VCC used for the rest of the electronics on the module. The jumper is there because sometimes you don't have enough power, so you pull that jumper off, and use a second power source. If you put a GND or a VCC signal to one of the IN pins, that relay should either turn on or off.

I found that the 3V isn't enough to power the relay.
https://www.instructables.com/Getting-Started-With-ESP8266LiLon-NodeMCU-V3Flashi/ shows the board supplies USB power (pin VU).
You can remove the jumper that connects signal voltage to relay power and connect the relay board to the USB power.
After that change I could turn the relays on and off, but I could not reliably power 4 relays, 2 relays as shown below seems fine.


text:
inconsistent digital output on simple code
so im new on arduino coding, and i made this code, where i input from serial monitor and then use it as a command for digital write. the problem is, sometimes the code work perfectly but then when i input 4, both D3 ad D4 is high and that also happens in D5 and D6. but its inconsistent, and i also print the 'out' value and also which digital pin is high to make it easier.
byte b;
int out;
int D3 = 3;int D4 = 4;int D5 = 5;int D6 = 6;int D7 = 7;int D8 = 8;
void setup() {
  Serial.begin(9600);
  pinMode(out, OUTPUT);
  digitalWrite(D3, LOW);digitalWrite(D4, LOW);digitalWrite(D5, LOW);digitalWrite(D6, LOW);digitalWrite(D7, LOW);digitalWrite(D8, LOW);

}

void loop() {
  while (Serial.available() == 0) {}
  b = Serial.read() - 48;
  out = b;
  Serial.print("\n Out is ");
  Serial.println(out);
  digitalWrite(out, HIGH);
  delay(600);
 if (digitalRead(D3) == HIGH)
{
   Serial.print("D3 HIGH");
}
 if (digitalRead(D4) == HIGH)
{
   Serial.print("D4 HIGH");}
 if (digitalRead(D5) == HIGH)
{
   Serial.print("D5 HIGH");
}
 if (digitalRead(D6) == HIGH)
{
   Serial.print("D6 HIGH");
   }
 if (digitalRead(D7) == HIGH)
{
   Serial.print("D7 HIGH");
}
 if (digitalRead(D8) == HIGH)
{
   Serial.print("D8 HIGH");
   }
  digitalWrite(out, LOW);
  delay(1000);

}

does anyone know why this happens? or can anyone recommend another method to do what im tryinng to do? thank you guys!!!

If I look at the first 5 lines:
byte b;
int out;
int D3 = 3;int D4 = 4;int D5 = 5;int D6 = 6;int D7 = 7;int D8 = 8;
void setup() {
  Serial.begin(9600);
  pinMode(out, OUTPUT);

You see that pinModeout, OUTPUT)uses a variableoutwhich is not initialized (it's only declared inint out`'.
I assume D3 to D8 are all output pins, so you have to replace the last line with:
pinMode(D3, OUTPUT);
pinMode(D4, OUTPUT);
pinMode(D5, OUTPUT);
pinMode(D6, OUTPUT);
pinMode(D7, OUTPUT);
pinMode(D8, OUTPUT);

Also, since you are using all pins in the same way, I suggest you use two variables: startPin and endPin. Then you can use a for loop to iterate through all pins. Also

always initialize variables.
use '0' instead of 48 when you convert from a byte value to a character (since you don't need to know the ASCII value of '0').

I don't have an Arduino compiler at hand, but it should look something like:
byte b = 0;
int out = 0;
const byte startPin = 3;
const byte endPin = 8;

void setup() {
  Serial.begin(9600);
  for (byte pin = startPin; pin <= endPin; pin++)
  {
      pinMode(pin, OUTPUT);
      digitalWrite(pin, LOW);
  }
}

void loop() {
  while (Serial.available() == 0) {}
  b = Serial.read() - '0';
  out = b;
  Serial.print("\n Out is ");
  Serial.println(out);
  digitalWrite(out, HIGH);
  delay(600);

  ...

However, from here you are using the pins as INPUT pins. You cannot change those on the fly, you might change them manually (by using pinMode(pin, INPUT)), but it does not seem normal to switch input and output pins, so maybe you should explain what you are intending with your application.

Hey, thank you so much, your recommendation actually solve the problem so far lol, and the intention of the program is fairly simple, i just need to input number to serial monitor and made the digital pins give out the output according to the numbers, (3456 in serial monitor means pind D3 til pin D6 gives out high value one by one.

but I still don't understand why you need to read the pins; if you write a HIGH you can assume the pin will be HIGH, no need (or you should) not read them, as they are configured to be output pins, not input pins.

yeah i dont need to, but i just need to check whether my code is working as intended, and i have limited resources where im at right now due to corona so i stuck in a place where nobody even sell resistor or LED

I doubt it will work this way, because if you change the pin mode, it will not output the signal anymore. Better use a multimeter to check the pin voltages.

yeah, its just temporary, thanks for the advice!!! i really appreciate it! :)

Ok, good luck. If the answer helped, upvote it (up arrow next to my answer), if a problem is solved, also accept the answer (check box next to the answer). Welcome to Arduino stackexchange.

At least on AVR, digitalRead() on an pin configured as OUTPUT is perfectly fine. pinMode() controls the output buffer, the input buffer is always active.

@EdgarBonet Thanks for the comment, good to know.


text:
What Minimum Value Can I Measure With ACS712 30A Current Sensor?
I am making an Arduino multimeter for current measurement. I first thought about using a shunt but that fails to work since I need to measure current in the mA range.

That model has a sensitivity of 66mV/A which means for every 1A of current passing through it outputs 66mV.
The Arduino's ADC when running at 5V has a resolution of (5/1024) 4.88mV per LSB.
That means that 4.88/66 gives you 0.074 - or 74mA per LSB.
Since 1LSB is considered to be in the noise area of the signal you can expect the minimum usable value to be double that - 148mA
Which is pretty useless for measuring currents in the mA range.
You would get better results with the 5A variant, but still not great.

The datasheet for the ACS712 shows the following:

This means the 30A variant has a sensitivity of 66mV/A. This means a reading of 1A will show 66mV plus some bias voltage. The Arduino ADC is 10-bit, meaning it has 2^10 = 1024 increments across a default 5V voltage reference for the Uno, Nano, etc. This gives it a measuring resolution of 5V/1024 increments = 4.88mV voltage resolution. 4.88mV / 66mV/A = 0.074A, or 74mA.
So, the default resolution of an Arduino Uno, Nano, etc, is 74mA. Realistically it will bounce around this value, so your precision might be about 3~4x this, or around 300mA, and your accuracy is as good as you calibrate it, which could easily be around this value too if you calibrate it well.
74mA resolution isn't bad, but there are several tricks to improve this. Here are a few:
1. External hardware solutions:

Use the 20A or 5A version instead of the 30A version of the ACS712. The 5A version has a sensitivity of 185mV/A, which automatically improves your resolution to 4.88mV / 185mV/A = 0.026A, or 26mA, which is 74mA/26mA = 2.8x better.
Buy an external ADC with high-resolution. This Adafruit ADS1115 16-Bit ADC (datasheet) will improve your resolution on the 30A version of the ACS712 as follows. Minimum resolution of the ADC is now 5V/2^16 = 5V/65535 = 0.0763mV instead of 4.88mV, and 0.0763mV / 66mV/A = 0.001156A, or 1.156mA.

2. Software solutions (freebies!):

Change your voltage reference to use the internal 1.1V internal reference. This is easy: call analogReference(INTERNAL) in your setup() function. Done! See: https://www.arduino.cc/reference/en/language/functions/analog-io/analogreference/. If I recall correctly, this is a diode-based internal voltage reference (see the ATmega328 datasheet), and can be off by as much as 10% from part to part, so calibrate it for each individual Arduino you have and you will get good results! Now, your ADC resolution is 1.1V/1024 = 1.07mV instead of the Arduino's default 4.88mV, so your current resolution is 1.07mV / 66mV/A = 16.2mA, which is 74mA/16.2mA = 4.6x better.
Use oversampling to increase the Arduino's 10-bit ADC to up to ~16 bits or so. Atmel Application Note AVR121: Enhancing ADC resolution by oversampling explains this very well, albeit it requires some serious study. There are libraries which exist to do this for you which you can Google for. I wrote one of them. Here is a link to my website where I present one such library I wrote. The gist is this: to get an 11-bit reading (which is 1-bit better than your hardware ADC resolution of 10-bits) you need to take 4^1 = 4 10-bit readings, sum them, then divide by 2^1 = 2. Your max value will be 1023 x 2 = 2046. To get a 16-bit reading (which is 6-bits better than your hardware ADC resolution of 10-bits) you need to take 4^6 = 4096 10-bit readings, sum them, and divide by 2^6 = 64. Your max value will be 1023 x 64 = 65472. Your voltage resolution will be improved from 4.88mV to ~0.0764mV at best. It won't be as good as a true 16-bit ADC, like the Adafruit one above, but it's good enough for many uses. Keep in mind that 4096 10-bit readings takes some time, so I also recommend you speed up the ADC clock to improve reading rate at 10-bits from ~10kHz to ~50kHz. This is also where a library comes in handy to make this easy to do. Free and open source solutions already exist. Here's a table I made back when I first read the  AVR121 application note and practiced oversampling. Consider the resolution values beyond ~16-bits to be purely theoretical. Oversampling has its limits.

What would I do? I'd use the 1.1V internal voltage reference and oversampling with increased ADC clock speed on the ACS712 part which provides the minimum acceptable max current (ie: choose the 5A version not the 20A or 30A version if 5A is enough, or the 20A version not the 30A version if 20A is enough). Just be sure that your max voltage now at the analog pins will not exceed the 1.1V Vref value. If it will, use the standard 5V reference for the ADC, and just do oversampling alone. My current resolution would end up being a few mA in the end. If I can't sample at the desired frequency using oversampling (I don't know what dynamic effects you may be trying to measure), then I'd use an external high-resolution ADC which can sample faster than oversampling at high resolutions would allow.

And if that's not good enough, what would I do? I'd use a precision shunt, ie: "current resistor" with the right value such that I can measure values at the right range. If I need amplification I'd buy an external ADC and/or op-amp from Adafruit until I have everything sized just right. Remember, if your shunt (current resistor) is too small to measure the low currents you need, do the following:

Use a higher resistance value. V = IR (Voltage = Current x Resistance), so increase R to increase the V across it for a given current, I.
Use an op-amp to amplify the voltage drop across the resistor (go for an Adafruit one since Adafruit makes it easy and has the world's best examples).
Use a high-resolution ADC, and/or oversampling to increase your sensitivity to measure small voltage changes.

Thanks sir....  Thats actually helps

Glad to help! Don't forget to click the up-arrow at the top-left of answers to upvote answers that you find helpful, and click the check-mark if you'd like to mark an answer as the "best" or "correct" answer. It helps bring the best answers to the top to help others after you who have the same question.


text:
How to separate in columns the data contained in a barcode
I have the following code, which allows me by scanning a typical 128 barcode to write this code in SD card under the Header "FA" as well as the time and date of scanner under the Header "Zeit".
I use for that an Arduino Uno, Waveshare scanner module connected in Serial to the arduino and SD/RTC mounted on top of the Arduino.
#include <SoftwareSerial.h>
#include <SPI.h>
#include <SD.h>
#include <string.h>
#include <Wire.h>
#include "RTClib.h"
#define rxPin 2
#define txPin 3
RTC_DS1307 RTC;
SoftwareSerial mySerial = SoftwareSerial (rxPin, txPin);
File main_folder; // initialize folder for saving
File dataFile; // initialize sd file
const int chipSelect = 10; // CS pin on sd card module
int prev_file_indx = 0; // used for file naming
String fileName = "000";
char timestamp[30];

const unsigned int MAX_INPUT = 50; // how much serial data we expect before a newline

void dateTime(uint16_t* date, uint16_t* time) {
  DateTime now = RTC.now();
  sprintf(timestamp, "%02d:%02d:%02d %2d/%2d/%2d \n", now.hour(), now.minute(), now.second(), now.month(), now.day(), now.year() - 2000);
  // return date using FAT_DATE macro to format fields
  *date = FAT_DATE(now.year(), now.month(), now.day());

  // return time using FAT_TIME macro to format fields
  *time = FAT_TIME(now.hour(), now.minute(), now.second());
}

void setup ()
{
  Serial.begin (115200);
  mySerial.begin (115200);
  Wire.begin();
  if (!RTC.begin()) {
    return;
  }

  pinMode(10, OUTPUT);
  if (!SD.begin(chipSelect)) {
      return;
    }

    main_folder = SD.open("/");
    fileName = sd_saver(main_folder);

 // end of setup

    delay(1500);
    dataFile = SD.open("DATA"+fileName+".csv",FILE_WRITE);
  if (dataFile) {
    Serial.println(dataFile);
    Serial.println("Writing Headers...");
    dataFile.println("FA,  Zeit");
    dataFile.close(); // close the file
    Serial.println("File closed, Headers written");
  }
 }//Open-Create file , populatrd with headers (2 collumns)

void process_data (const char * data)//to process the incomingserial data (from Scanner + timestamp when scanned) after a terminator received

{ delay(500);
    SdFile::dateTimeCallback(dateTime);
  DateTime now = RTC.now();
  sprintf(timestamp, "%02d:%02d:%02d %2d/%2d/%2d \n", now.hour(), now.minute(), now.second(), now.month(), now.day(), now.year() - 2000);
     dataFile = SD.open("DATA"+fileName+".csv",FILE_WRITE);
  if (dataFile) {
    Serial.println("Writing to file...");
    dataFile.print (data);
    dataFile.print(",");
    dataFile.println (timestamp);
    Serial.println (data);
    Serial.println (timestamp);
    Serial.println("Done.");
    dataFile.close();
  } else {
    Serial.println("error opening test.txt");
    delay(1000);
  }

}

void processIncomingByte (const byte inByte) //Processsing of the incoming scanned data
{
  static char input_line [MAX_INPUT];
  static unsigned int input_pos = 0;

  switch (inByte)
  {

    case '\n':   // end of text
      input_line [input_pos] = 0;  // terminating null byte

      // terminator reached! process input_line here ...
      process_data (input_line);

      // i here reset the buffer for the next time
      input_pos = 0;
      break;

    case '\r':   // discard the carriage return
      break;

    default:
      // keep adding if not full and permit for a terminating null byte
      if (input_pos < (MAX_INPUT - 1))
        input_line [input_pos++] = inByte;
      break;

  }  // end of the switch

} // end of processIncomingByte

void loop() {
  delay(2000);

  // if serial data available, process it
  while (mySerial.available () > 0)
  processIncomingByte (mySerial.read ());
  mySerial.write(processIncomingByte);
  delay(1000);

  //possibility to do other stuff while testing digital?? ...

}  // end of loop

String sd_saver(File dir){
  while(true){
    // iterate all files to ensure no overwrites
    File entry = dir.openNextFile();
    if (!entry){
      break;
    }
    // naming routine
    String entry_name = entry.name();
    if ((entry_name.substring(4,7)).toInt()>=prev_file_indx){
      prev_file_indx = (entry_name.substring(4,7)).toInt()+1;
      if (prev_file_indx>=100){
        fileName = String(prev_file_indx);
      } else if (prev_file_indx>=10){
        fileName = "0"+String(prev_file_indx);
      } else{
        fileName = "00"+String(prev_file_indx);
      }
    }
    entry.close();
  }
  return fileName;
}

My question is, can you come up with a way or guidance on how I should redo the code so that allows me to split the information of the barcode in different headers? that is columns. So for example the number "10000" as shown in the image after "@" to be in logged in another column called "Machine Number" ? I tried to insert control characters in the barcode to be scanned , but they are not interpreted as such but as characters .
Any help or thoughts are most than welcome
Thanks

google c++ parsing text data

take a look at strtok.

@hcheung before I delve into this function, assuming that "pch stands for recompiled header, would you tell me if this "precompiled header" is acknowledge by Arduino Library , do I need a new one?

It's possible that the code's author decided to abbreviate the variable name, which could mean is stands for "pointer to a char". If you search our site for char * pch;, there are a few example of the code adapted to work in the Arduino IDE.

@VE7JROthanks for your answer. You mean by your site: http://www.cplusplus.com/?

@Maximilian1988 - I'm not sure what you mean when you say "your site". I am not affiliated with cplusplus.com, or any other Arduino website, except for this one. You are free to use any code at cplusplus.com as long as you can get it to compile in the IDE you are using. Once you have mastered the language reference here https://www.arduino.cc/reference/en/, and want to do advanced "things", generic C++ websites will be your friend.


text:
Extremely unstable analogRead() on Arduino Nano when powered from an external source
I'm doing a really simple project with an Arduino Nano and found a problem.
The circuit is a simple temperature sensor and a tension read from an analog pin everything showed on a Nokia 5110 LCD.
When the Nano is connected to the USB everything works and the reads are perfect.
When I install the circuit on my car taking the 12V to the Vin and the GND from the centraline everything goes bad: I certainly know that the 12V is obviously not stable and oscillates a lot (between 12V and 14V).
What can be the solution? Should I add some ref or should I regulate the input tension to maintain it stable to a certain quantity?

Car power is incredibly noisy. You need lots of filtering to get it to work right. Either that or get a proper automotive grade power supply. The simplest is a "cigarette lighter" USB charger...

Thanks. Unfortunately I'm taking the readings from the cables that go to the lpg commuter. If the problem is the stability of the input does exist some (cheap) circuit that I can use to stabilize it to 12V?

Why is that "unfortunate"? What does where you're taking readings from have to do with how you're powering the board?

To keep everything compact I take power and readings from the same part. To use the cigarette lighter usb charger I should keep it plugged in and pass a cable along all the front part of the car

You're thinking too literal. A "cigarette lighter" style power supply doesn't have to be plugged into a cigarette lighter socket. Take a screwdriver to it. Pull it apart. Solder wires to it. Think outside the plastic shell it comes in.

Thanks, I will give it a try. Can I ask you if this cheap product
https://a.aliexpress.com/_BPIybF (A DC-DC regulator)  can do the work? Thanks

Since the Arduino uses the power input as the reference for the ADC, taking power and readings from the same source is a recipe for disaster.   If you want really stable readings divide your signal down to 1v1 and use the internal reference on the Arduino.

Can the DC-DC help with that? I don't need perfect readings but actually the temperature readings jump from 20°C to 40°C in a matter of seconds. (I take the average of some readings)

No. Like I said, you need automotive grade. That means it can cope with spikes in excess of 65V or so.

Really? An old car centraline can reach 65V? I didn't know that thanks

Like I said: noisy.

Yes but I tough less noisy. Using the usb charger I will get 5V. Since the VIN pin wants at least 7V can I connect the 5V from the charger to the 5V pin even if the LCD and the temperature sensor are already connected there?

Yes. Of course you can.

Thank you for your help, I thin that the question is resolved. I've a last doubt: can I trust the car charger or should I put something between the 5V pin and the output of it? Thanks

You can use a branded 5 V charger made for cars. You can directly connect this to 5 V pin of the Arduino.
By doing this:

you are protecting the Arduino from the noise as well as high voltage spikes coming from the car 12 V supply
protecting yourself and others coming in contact with the Arduino or the sensors connected to the Arduino.

You can also

consider filtering the analog data read
protection circuits such as surge protection diodes or a 5.7 V Zener across 5 V and Ground of Arduino


text:
Best way to ask Arduino for data from Python?
I'm trying to send numerical data from inertial sensors from my Arduino to a Python script via serial (PySerial).
I found that if I continuously send the data from the Arduino without stopping, the serial buffer fills up quickly and the sensor measurements that the Python reads becomes delayed.
To fix this, I thought of having the Python script send over a transmit command to the Arduino when it needs data. I'm sending a char 't' to signify this command, but the delay between Python sending the command and the Arduino sending the data is too large.
I'm wondering if there's a 'proper' way of doing this, as I'm sure it's probably been done before?

You should be able to get an instantaneous response to your commands. You must be doing something wrong in your code.

You're not trying to use readString on the Arduino to read one character from python are you?

ok, thinking about what you said ... it makes makes perfect sense to learn how to use a transmit command ... but it makes no sense to actually use it ... if the buffer overflows on Python side, then it will overflow on Arduino side if you pause comms .... does it really matter if some of the readings are lost? ... if lost data is not an issue, then frame data packets and simply ignore incomplete packets when they arrive on Python side

I'm reading strings on both sides Python and Arduino. I can't let the Arduino's output buffer overflow, because the buffer doesn't clear until I read from it on the Python side. I need the most recent sensor values (gyro, accel IMU), so if I let the buffer overflow and start reading from it, I'll get sensor data that is a few cycles old.

I'm wondering if it's possible that the baud rate I'm using is too high (19200-115200) for the IMU sensor? Maybe I'm reading data faster than the sensor can provide?

This is not a complete answer to your problem, but currently you seem to have some misconceptions, that prevent you from pin pointing the actual problem.
The data transmission from the sensor, over the Arduino to your python script on the PC has multiple places, where a bottleneck can appear. The total data rate will then be at maximum as large, as the smallest bottleneck allows it to be.
First you have a potential bottleneck in the communication between sensor and Arduino. You haven't stated, what kind of IMU chip you have and how it communicates. Typical IMU chips like the MPU series are interfaces via I2C or SPI. SPI can be sped up rather greatly, while I2C is not that easy to speed up. But it depends greatly on the capabilities of the used chip. You can find information about that in the corresponding datasheet of the chip.

The next interface is the Serial (UART) interface between Arduino and PC. This interface has a fixed baudrate. When you use Serial.write() or its siblings, you simply fill the send buffer of the Serial library. The data will then be send out automatically at the correct timing for your baudrate. The transmission always happens, if the python script is reading or not. The transmission also happens, when the serial buffer of the script is full. The Arduino does not know about the buffer being full. So in this case the data is not delayed, but lost.

The last - and probably most important - potential bottleneck is how you read and send the data on Arduino and in the python script. Here I'm covering the Arduino side.
You should not use functions like Serial.readString(), as they work with a timeout, which will slow down your code drastically. Instead you should read the Serial data byte by byte into a buffer, delimiting your message with a special character (for example the newline character \n). You check, if there is any data Serial.available(), and if yes, you read one byte into a char array, which is your own buffer. You are doing that repeatedly, until you read the delimiting character. Then you process the complete message. That way will give you some important improvements:

You can do things in the meantime (for example reading new data from your sensor)
It works without any arbitrary timeout, thus not slowing down your code unnecessaryly
The delimiting character frames a full message, so that you can distinguish two different messages from each other and thus easier process them

Considering the above, you should make the requirements clearer:

How much latency between the actual sensor measurements and the receiving in the python script is ok for you, meaning: How old can the measurements be, that the python script gets? (You just stated, that it is too large, but you have not mentioned how large)

Do you need continuous data transmission, or just one or a few sets of the IMU data?

Then you can check for the needed speed and data rate. Check, if all involved interfaces and codes can really handle your requirements.
Also it would be easier for us to help you, when you show your current code in your question.

Note that for single character commands you do not need message framing and buffering.


text:
Can analog pins be defined as either their analog name (A0) or their digital pin number?
Can analog pins be defined by their digital pin number, and be used for analog purposes?
For example, instead of defining A0 for a pinout with the Uno, it could be 14?
Where is this documented? Is there a PDF type manual related to this, but not so low level to get into the ATmega chip?

https://www.arduino.cc/en/Hacking/PinMapping2560

For example, instead of defining A0 for a pinout with the Uno, it could be 14?

Yes. In fact A0 is just a placeholder for the number 14.
For all these things you should look in the pins_arduino.h file (Arduino\variants\wifio) for any variant you are interested in. That's where most of these symbols are defined. For example:
#define PIN_A0   (14)
#define PIN_A1   (15)
#define PIN_A2   (16)
#define PIN_A3   (17)
#define PIN_A4   (18)
#define PIN_A5   (19)
#define PIN_A6   (20)
#define PIN_A7   (21)

static const uint8_t A0 = PIN_A0;
static const uint8_t A1 = PIN_A1;
static const uint8_t A2 = PIN_A2;
static const uint8_t A3 = PIN_A3;
static const uint8_t A4 = PIN_A4;
static const uint8_t A5 = PIN_A5;
static const uint8_t A6 = PIN_A6;
static const uint8_t A7 = PIN_A7;

Incidentally, on the Uno you can also just use 0 for A0 with analogRead().

You can use 0 for A0 only in analogRead.  If you are using it as a digital pin you still have to either call it 14 or A0.

@Delta_G Good point on the usage distinction.


text:
Reduce time between two consecutive SPI transfers on ESP32
I'm trying to drive an external DAC via SPI interface using ESP32 chip. But I cannot achieve the desired speed (>1M transfers/sec, each transfer consists of 16bits). The reason is not the SPI speed itself, which could be set as high as 40MHz, but the time delay between two consecutive SPI transfers.
A sample code is as follows:
#include <SPI.h>

void setup()
{
    Serial.begin(115200);
    SPI.begin();
    SPI.beginTransaction(SPISettings(40000000,MSBFIRST,SPI_MODE0));
}

void loop()
{
    unsigned long tstart=micros(),count=0;

    byte data[18]={0,1,2,1,3,1,0,1,2,1,3,1,0,1,2,1,3,1};

    while(micros()-tstart<1000000)
    {
        for(byte i=0;i<9;i++)
          SPI.transfer16(0b0101010110101010);
        count+=9;
    }

    Serial.println(count);
}

The output shows that ESP32 can do approximately 694,800 transfers/sec, still far away from my requirement of 1M transfers/sec. However, theoretically, using a 40M SPI bus, each transfer only takes 16/40M sec, which should enable a >2M transfers/sec speed, so the difference must originate from the time delay between two consecutive SPI transfers.
I know that these delays can possibly be canceled by transferring more data in a single transfer command. However, the interface of DAC requires me to pulse SYNC once (set it high and then low) before each SPI transfer, which is not possible if I use a single SPI transfer command.
I have searched for solutions online and found two related problems:
The one here suggests disabling all MUTEX commands in esp32-hal-spi.c/h. It seems reasonable, but I see no effects, probably because the compiler has already deleted those codes in optimization.
Another here suggests using RMT to replace SPI, but suffer from timing issues.
I think there is also room for improvement as I only need to output data, and I access SPI on a single thread, so the solution can be thread-unsafe.
So I'm here to ask, is there any way to accelerate the SPI transfers? Thanks a lot in advance!

How are you accounting for the time needed to call micros, do the subtraction, do the comparison, check the while condition, handle the for loop, and add to count?

@Delta_G, I've checked, checking micros() and adding count takes way less than a microsecond. 95%+ of time is still consumed on SPI.transfer(), which takes 1us+ on each call.

What DAC are you trying to drive?

@Majenko DAC108S085 manufactured by TI

I am not familiar with the SPI peripheral in the ESP32, but it looks like you can 1) confgure it to automatically assert the CS pin (for /SYNC) for each transaction, and 2) user DMA to stream large amounts of data quickly. How you would do all that I have no clue, but you'd be using ESP-IDF functions not Arduino functions to do it. And that's way beyond the scope of this site.

@Majenko thanks for your reply! I'm currently trying to (ab)use I2S interface to emulate SPI. would update if I succeeded. DMA seems not a good solution though, as preparing DMA takes time as well...

I know this is an old post, but did you managed  to solve it @Wjx ? I'm currently facing the same issue for a different DAC.


text:
CAN Bus Shield Initialization Failed
The Problem
I've been working on a project that requires the use of a CAN Bus Shield v2 on an Arduino. For most of the time it has worked great, completely as intended. But recently, I was trying to hookup a 24V heater to a MOSFET to be controlled by the Arduino. I had hooked it up the pin 2 which later I found out was a bad idea because pin 2 is for the interrupt signal. I uploaded the code and the heater did not turn on.
A while later I tried to upload code to the Arduino and it would not upload, citing a not in sync error. So, switched the Arduino board out for another one of the same model and the code uploaded just fine. But, the CAN Shield was throwing a "CAN Bus Shield Init FAILED" error over and over again. And the INT light was staying permanently on. And the Rx light would stay on if I tried to send a message on the bus from another node.
My question is, will I have to purchase a new shield or is there a way to fix this?
What I have tried

Turning it off and on again
Using the shield on the old Arduino
Wiping the Arduino and adding the code again
Reverting to an older piece of code
Setting pin 2 HIGH (this turned off the INT light but did not fix the init problem)
Sending various messages on the CAN Bus
Flipping the OBD switch on/off
Trying different resistors

simulate this circuit – Schematic created using CircuitLab

Sounds like maybe a bad wiring issue where you fried the Arduino? Can you post a wiring diagram? You can use the "Schematic" button in the editor when editing your question.


text:
Arduino MKR GSM 1400 fails to start up without Serial Monitor
This question is similar to another question, but I have added more details. See: MKR GSM 1400 Works only when connected to computer.
I have designed and built a custom board into which I plug an Arduino MKR GSM 1400. It's a basic IO abstraction level shifter as the system I am integrating to run on 24 V logic (done via opto-couplers). Everything is working perfectly and as-designed. I've added an I2C EEPROM.
When I boot the board from an external ATX supply +12 V line it doesn't complete setup. After I've left it for some time, I connect it to my PC USB port and open the serial monitor in the Arduino IDE and it simply completes the setup process and enters loop successfully.
Voltages are perfect. The 12-24 V supply is first fed through a standard 7810 (since I need +10 V for the analog lines of the controlled system) and then a 7805. The +5 V output of the 7805 is sent into the Vin of the Arduino. Measuring VIN with a DMM reads +5.07 V and VCC reads +3.33 V. I have a 3.7 V, 300 mAh 25C Li-Po connected to the battery port on the Arduino, to deal with the current requirements as specified in the documentation.
I thought this could be a power issue, so I also tried booting it with a 10 Ah USB Power bank that has 2 x 5 V, 2 A (3 A max) USB ports. Same result, until I connect the PC with the serial monitor.
Simplified Arduino Code:
#include <MKRGSM.h>
#include <Wire.h>

GSM gsm;
GPRS gprs;
GSMServer server(80);
GSMSSLClient client;
GSM_SMS sms;

void setup() {
  //Initialise Serial
  Serial.begin(9600);
  while(!Serial)
  {}
  Serial.println("Gineer.Industrial.GSM.Controller");
  Serial.println("www.gineer.co.za");
  Serial.print("Hardware Version: ");
  Serial.println(hwVersion);
  Serial.print("Software Version: ");
  Serial.println(swVersion);
  Serial.println();

  Serial.print("Connecting");

  bool connected = false;

  while (!connected) {

>>> Here is where it gets stuck until I plug in the USB Serial Monitor, and then it continues happily.

    if ((gsm.begin(SIMpinNumber) == GSM_READY) &&
        (gprs.attachGPRS(SIMgprsAPN, SIMgprsLogin, SIMgprsPassword) == GPRS_READY)) {
      connected = true;
    } else {
      Serial.print(".");
      delay(1000);
    }
  }
.
.
.

Interestingly, the +5 V output pin on the Arduino measures 4.68 V when not connected to the PC. I don't however use this pin as I have the 7805 on my board. All other voltages measure as above at all times.

your program does not fail to start up ....... take a look at your code ... examine any command lines that deal with Serial ... any of them look like they might hang up your code?

@jsotola Can you help me understand how Serial could do that? The way I understand it is that serial would just output without checking if it is connected anywhere. In fact, I can see this happening, until the point where it hangs.

https://www.arduino.cc/reference/en/language/functions/communication/serial/ifserial/

while(!Serial) {} will wait for a serial connection and in your program will block execution until it gets one.
Remove it and your program should continue without the serial monitor.

Copy and Paste will get you every time. When I noticed it I wanted to delete the question, but maybe it helps someone.


text:
Can I use an internal clock on Wemos D1 Mini?
I have a working Wemos D1 Mini setup measuring temperature and sending it over wifi to my server. Now I'm using a battery powered unit, and playing around with power consumption optimization and how to reduce it.
One thing I need is time (current, either epoch or DST) - so I implemented NTP, but everytime my ESP is waking up after deep-sleep, it needs to reconnect to wifi, gather time, measure temperature, send results.
This pdf states that ESP8266 has an internal clock. I'm having troubles finding anything beside "RTC shields on Wemos/Arduino" or "NTP on ESP8266" on the internet about something that is like an internal clock. There must be something, because otherwise it could not work (my understanding about clock and hardware is limited by now).
My question is: can I use NTP to update my internal clock, using it for some minutes (I think it will drift after some minutes), updating via NTP once in a while - to simply reduce network traffic and still use deep-sleep mode?
Any hints are welcome!

this is not an answer, but I want to show you how to simply  get NTP time in esp8266 Arduino: https://github.com/jandrassy/TelnetStream/blob/b1a24a033f84a9811a99d02389cc6b64c02c69c0/examples/TelnetStreamEsp8266Test/TelnetStreamEsp8266Test.ino#L27 This will set the time in the internal RTC (there is no other way)

I think the answer to your question can best be summed up by one word: "Kinda".
The best reasoning is the NodeMCU Lua documentation which states:

Time keeping on the ESP8266 is technically quite challenging. Despite being named RTC, the RTC is not really a Real Time Clock in the normal sense of the word. While it does keep a counter ticking while the module is sleeping, the accuracy with which it does so is highly dependent on the temperature of the chip. Said temperature changes significantly between when the chip is running and when it is sleeping, meaning that any calibration performed while the chip is active becomes useless mere moments after the chip has gone to sleep. As such, calibration values need to be deduced across sleep cycles in order to enable accurate time keeping. [...]

So while it's called RTC it's not an RTC in the traditional sense - it's merely a timer that runs even when sleeping, but not with any degree of accuracy.
You can access the current RTC count with the Non OS SDK function
uint32_t system_get_rtc_time()

You can combine that with
uint32_t system_rtc_clock_cali_proc()

which gives you the number of uS per tick of the RTC timer.
There's no way to change the RTC timer count, so you will have to work out some "delta magic" to update your own internal time value (an epoch value is simplest) from the difference between successive calls to get the RTC count.
All somewhat tricky and the accuracy won't be great anyway, so you'll be wanting to use NTP to update that epoch value regularly.
But it could give you a "rough idea" of how long you've been asleep for, etc.
You would have to run some experiments to know how much the time drifts compared to the NTP value in real usage.

Kinda, if you don't call deepSleep. Quoting the 3.0.2 SDK API Reference, "If an external hardware reset the chip via EXT_RST or CHIP_EN (such as timed wakeup from Deep-sleep), the RTC timer will be reset." Arduino sketch ported from mentioned reference.


text:
What sensors do I need to detect magnetic "take off"?
I want to build a sensor using arduino (or any other esp) measuring the release of a leg on a floor panel. I've build a prototype using copper plates and a BBC Micro:bit, which works fairly well. But I want to use magnetic sensors, determining release of the leg.
My education on magnetic is - simple. I know it exists. I know it's one of four basic forces in nature (ha!). But I don't know how to measure it using electronic circuits (I'm new to this topic).
Imagine one person stands on a plate, wearing magnets on his foot (say "magnetic socks"). I want to immediately detect when the person raises his leg. What kind of sensors do I need?

Hall sensor is the keyword here (it measures the magnetic field strength). Though this question is not really about Arduino. You can find many tutorials online on how to use a hall sensor with Arduino.

@chrisl where else could I ask such things? (thanks for the tip on Hall sensor)

The range of magnetism isn't great, so you'd have to place your foot at a very precise position, for the hall-effect sensor to "see" the magnet. I think your original idea is a lot better.

You have two options here, either a Hall Effect sensor or an Inductive Sensor. The hall effect sensor is probably the best option. This will likely need some calibration on your end to identify the exact value you record at "Take Off" for your setup.

@Michael Hirschler (OP) Out of curiosity why do you need the solution to be magnetic? I'm struggling to visualise the setup you described and why you wouldn't consider pressure sensors or a simple tactile button to detect when the leg in in contact with a surface? I'm just not certain if the Hall Effect sensor with give you a clean and constituent reading compared to other potential solutions. Deepening on the setup you may even be able to use the metal plate and leg as a large switch, closed when in contact & open at the moment of "Take Off". Just spit balling some ideas :)

A third (simpler) option: reed switches.

@JackSoldano at my sport (Taekwondo) we're wearing magnetic socks for detecting impact on vests for triggering a point (see olympic sports). The idea was to re-use these socks, so any athlete can test his speed on leaving the floor plate, and hitting a target. Maybe simple tactile buttons may do also - but I'm not an engineer, so I can't think about how to use them, without destroying them :-D
I need to read some books about this topic, an hall-/inductive-sensors (and reed switches), too.

I understand now! makes sense, yeah, I would probably scrap the inductive sensor as they are big. A hall effect / Reed switch might be the way forward If you really want to go the magnetic route. If you are already wearing magnetic socks that may be conductive?, I think it would be possible to create open/close a circuit from the persons foot through the ground metal plate and detect this from an Arduino, that would give you instantaneous detection of contact.

I managed to get a reed-switch. I'll try in next few days and keep you updated ;-)

Sadly the reed-switch isn't sensitive enough to detect those socks. I need to try something else. Thank you anyway!


text:
Two SSL connections at the same time on Uno WiFi rev 2
So I want to have one persistent SSL connection to a cloud server (Azure IoT Hub) to upload telemetry and another SSL connection to a server to perform a simple GET request every 30 minutes.
I've setup my first connection and telemetry is successfully sent, then I connect to the second server, I get a response, close the connection, but my first connection to Azure IoT Hub crashes.
I haven't found any information online on how many simultaneous SSL connections the Arduino Uno WiFi Rev. 2 supports nor any guidance on how to use more than 1 SSL connections. Any help would be greatly appreciated.

I have had some problems with using two sockets simultaneously with WiFiNINA versions > 1.3, see https://github.com/arduino-libraries/WiFiNINA/issues/87 . Maybe it's the same problem. Which WiFiNINA version are you using?

@ocrdu yes I think it's the same problem. I was using version 1.6.0.

Edit: Firmware version is 1.3, library version is 1.7

If things work OK when you use firmware 1.4 and this alternative library: https://github.com/ocrdu/WiFiNINA , then it's the same problem 8-).


text:
Why does my Wemos D1 Mini stops working while charging via solar?
I'm using an battery shield to recharge my battery. I want to use a solar panel, so I bought one (5V 240mA). I'm pretty sure, it won't recharge my battery fully, but that's not the point.
I've assembled my board with my shield, soldered the solar panel together with an schottky-diode and put it on USB (since the shield allows charging via USB). All fine, I get some electric power in the sun - yeah!
But my Wemos D1 Mini only runs for say 2-3 minutes and than ... dead? Restarting works, but only lasts again 2-3 minutes. This only happens while the battery shield is charging via solar. I already tested using any USB charging (my computer) - this simply works.
Basically I rebuild the circuit like described on TheAustrian/Wemos-D1-Mini-BME280-Weather-Station but only one solar panel attached and using the Wemos D1 Mini Battery Shield instead of the TP4056.
Any hints what's going on? Why can't I run the board while charging via solar? Did I miss something?

I would hazard a guess that the solar panel needs to be big enough to both charge the battery and run the Wemos D1 at the same time. Lack of current will cause bad things to happen.

@Majenko how can I be sure? What specs do I need to read? :-D

The TP4056 Module will output a max of 4.2V which is less than the 5V the Wemos D1 Mini is expecting on its 5V connection (Assuming you have connected the circuit as shown in the Github guide). When the solar panel is charging it's likely that the TP4056 is causing a driving issue on the supply of the Wemos causing it to potentially Brownout .
I would not connect the solar panel to the Wemos like this, I would have it connected to the battery then the battery connected to a 5V Step Up Power Converter like shown below (This reduces efficiency but give the MCU a stable supply),

My recommendation for the wiring,

Thank you for explaining, but as far as I can see, this the Wemos D1 battery shield does provide a boost converter (step-up converter?). But I also just noticed: it states 0.5A or max. 1A charging current. Maybe my problems lies in using one solar providing 0.25A?

As I stated in my question: I'm using the Wemos D1 battery shield instead the TP4056.

Sorry I should have re-read you question, okay so the module is getting 5V which is good. The symptoms still sound like the Wemos is browning out. It's very possible the solar panel is not generating enough current to power the regulator (You could get a multi-meter on the output to see what's going on under load). Is the battery completely drained, do you have a way to fully charge it and repeat the test? In theory the solar panel should only be charging the battery not directly driving the 5V regulator.

Yes I do have one. I'm new to electronics, so: where do I need to measure output? On the solar panel or output of the shield (a.k.a input of Wemos)? V or A?

I would measure the voltage cross the 5V connection on the Wemos module (So Wemos 5V to GND). Keep measuring it while the Wemos run & see if it changes when the Wemos crashes (The voltage will likely drop < 5V then potentially jump back up to 5V once the crash has occured and the current load has dropped). If the 5V supply is stable during the crash you may need to switch to measuring current (Amps A). So in line 5V as shown here - https://www.electronics-notes.com/articles/test-methods/meters/how-to-measure-current.php


text:
ESP32-POE/ISO unstable after 10 days of power up
i have one ESP32-POE and ESP32-POE and i'm using the Olimex RS485 module to read a power meter that is placed near the ESP32 (5 meters of CAT5 cable - 9600 8N1).
My device has this workflow (it's powered via PoE using a Cisco 2960x switch):

Boot and acquire a DHCP address
Connect to the server and check if there is a new ota package to download
Read via modbus (Using ModbusMaster library) the power meter
Prepare the data in JSON format using ArduinoJson library and send it to the broker using PubSubClient
Wait for five minutes using Millis and start over with the loop

This is the main logic that "blocks" the loop and wait for some minutes:
void loop() {
  wdt_reset();
  MQTT_connect();

  client_subscriber_loop(); // loop subscriber mqtt

  unsigned long currentMillis = millis();
  if (currentMillis - previousMillisTaskDataPublisher > MQTT_PUBLISH_EVERY) {
    if (DEBUG == 1)
      Serial.printf("Free internal heap on Loop Enter %u\n", ESP.getFreeHeap());
    //  OTA Check
    trueverit_ota_check_update();
    wdt_reset();

    publish_data();
    if (DEBUG == 1)
      Serial.printf("Free internal heap on Loop Enter %u\n", ESP.getFreeHeap());

    previousMillisTaskDataPublisher = currentMillis;
  }
}

As you can see, i've also have Watchdog timer enabled and it is feeded in the loop or function that have to feed it (Modbus read, etc...)
Now, here comes the issues, this works exactly for 10 days and after that the MCU goes in loop, the LAN green led will flash indefinitely and nothing work, leaving the ESP32 in a undefined state.
This is the debug message that i see on arduino console:

There is no way to make it work a part of power off and power on the device.
This is extremely uncomfortable...in my case i have 25 of those devices placed far away from my office (600km) and i can't go every time to reboot them every ten days.
Maybe is hardware related issue? a software issue on ModbusMaster library?
Any toughts?

please, no pictures of text ... include the debug message as text ... format it the sane as code

You could have the watchdog timer timeout if you get a network error. Then the MCU will just reset. It would be interesting to see if  lowering MQTT_PUBLISH_EVERY also make the problem occur faster than 10 days.

Is the console output from right before the ESP malfunctions? There is no way to make it work a part of power off and power on the device. does that include pressing the reset button?

Have you considered performing a software reset every 24h as a workaround?

Tomorrow I'll remove the publish delay and test it. - about what asked from Gerben, yes, this is the console output right before the ESP malfunction, it doesn't include the reset pressing button (if I reset the device with reset button it will start working).

HTTP_UPDATE_FAIL_ERROR (-104) means that the server disconnected for some reason, and your code went into a trap state without the ability to establish a reconnect. The code you posted doesn't provide any clue on how you handle the reconnect when it happened.


text:
How to easily invoke Simple REST Service trigerred using Arduino UNO + ESP8266 WIFI Shield programmed with AT command?
My Question is How to easily invoke Simple REST Service trigerred using Arduino UNO + ESP8266 WIFI Shield programmed with AT command? I am new to this Subject and gone through many tutorial over internet but so far I could not making this working as per my requirement
My Requirement: Invoke a simple Get request originated from Arduino Uno and via ESP8266 WIFI Shield to submit to server and process the response.
What all I have done so far:

Used below Blynk example to Submit Up time to the Server and View in MobileThis is Working which means hardware setup at my side should be ok, but I dont want to Submit request to Blynk Server and I want to Submit request to my REST server and first of all I want to do a simple GET request may be to any already working API for ex: http://jsonplaceholder.typicode.com/posts/1
#define BLYNK_PRINT Serial
 #include <ESP8266_Lib.h>
 #include <BlynkSimpleShieldEsp8266.h>

 // You should get Auth Token in the Blynk App.
 // Go to the Project Settings (nut icon).
 char auth[] = "xyz";

 // Your WiFi credentials.
 // Set password to "" for open networks.
 char ssid[] = "xyz";
 char pass[] = "xyz";

 // Hardware Serial on Mega, Leonardo, Micro...
 //#define EspSerial Serial1

 // or Software Serial on Uno, Nano...
 #include <SoftwareSerial.h>
 SoftwareSerial EspSerial(2, 3); // RX, TX

 // Your ESP8266 baud rate:
 #define ESP8266_BAUD 115200

 ESP8266 wifi(&EspSerial);

 BlynkTimer timer;

 void myTimerEvent()
 {
   // You can send any value at any time.
   // Please don't send more that 10 values per second.
   Blynk.virtualWrite(V5, millis() / 1000);
 }

 void setup()
 {
   // Debug console
   Serial.begin(115200);

   // Set ESP8266 baud rate
   EspSerial.begin(ESP8266_BAUD);
   delay(10);

   Blynk.begin(auth, wifi, ssid, pass);
   // You can also specify server:
   //Blynk.begin(auth, wifi, ssid, pass, "blynk-cloud.com", 80);
   //Blynk.begin(auth, wifi, ssid, pass, IPAddress(192,168,1,100), 8080);

   // Setup a function to be called every second
   timer.setInterval(1000L, myTimerEvent);
 }

 void loop()
 {
   Blynk.run();
   timer.run(); // Initiates BlynkTimer
 }

Output :
  ___  __          __
   / _ )/ /_ _____  / /__
  / _  / / // / _ \/  '_/
 /____/_/\_, /_//_/_/\_\
        /___/ v0.6.1 on Arduino Uno

[517] Connecting to xyz
[13550] AT version:1.1.0.0(May 11 2016 18:09:56)
SDK version:1.5.4(baaea 1
[23591] Failed to connect WiFi
[31752] Ready (ping: 11ms).
[70474] Ready (ping: 12ms).
[86528] Ready (ping: 13ms).

Though I get Failed to connect to wifi but probably it retries and works there after as I can see timer in Mobile APP which is progressing.

Invoke HTTP request using AT Command, but I am getting output as ">" which I am not able to get as why the output is like this:
#include <SoftwareSerial.h>

SoftwareSerial ESP8266(2, 3);

String Network = "xyz";
String Password = "xyz";

void setup()
{

  Serial.begin(9600);

  ESP8266.begin(115200);
  ESP8266.println("AT+CIOBAUD=9600");
  readESP8266(4000);

  ESP8266.begin(9600);
  InitESP8266();
  ConnectToWebsite();
}

void loop()
{
   while(ESP8266.available())
   {
     Serial.println(ESP8266.readString());
   }

}

/* Function to initialise ESP8266 */
void InitESP8266()
{

  ESP8266.println("AT");
  readESP8266(2000);

  ESP8266.println("AT+CWMODE=3"); //Wifi mode
  readESP8266(5000);

  ESP8266.println("AT+CWJAP=\""+ Network + "\",\"" + Password +"\""); //connect wifi
  readESP8266(10000);

  ESP8266.println("AT+CIFSR"); // IP adress
  readESP8266(1000);

  ESP8266.println("AT+CIPMUX=1");  // multiple connections
  readESP8266(1000);

}

/* Function to connect to the server */
void ConnectToWebsite()
{

  ESP8266.println("AT+CIPSTART=1,\"TCP\",\"jsonplaceholder.typicode.com\",80"); //connect to website
  readESP8266(10000);

  ESP8266.println("AT+CIPSEND=1,114");
  readESP8266(2000);

  String httpreq = "GET /posts/1 HTTP/1.1";
  // Make a HTTP request:
  ESP8266.println(httpreq);
  readESP8266(10000);

  readESP8266(5000);

  //Serial.println("\r\n");
}

//read and display message
void readESP8266(const int timeout)
{
  String reponse = "";
  long int time = millis();
  while( (time+timeout) > millis())
  {
    while(ESP8266.available())
    {
      char c = ESP8266.read();
      reponse+=c;
    }
  }
  Serial.print(reponse);
}````

Output:
OK

OK
WIFI DISCONNECT
WIFI CONNECTED
WIFI GOT IP

OK
+CIFSR:APIP,"192.168.4.1"
+CIFSR:APMAC,"abcd"
+CIFSR:STAIP,"192.168.0.169"
+CIFSR:STAMAC,"abcd"

OK

OK
1,CONNECT

OK

OK
> 1,CLOSED

If I use WIFI ESP then I am getting following error

// Emulate Serial1 on pins 6/7 if not present
#ifndef HAVE_HWSERIAL1
#include "SoftwareSerial.h"
SoftwareSerial Serial1(2, 3); // RX, TX
#endif

char ssid[] = "xyz";            // your network SSID (name)
char pass[] = "xyz";        // your network password
int status = WL_IDLE_STATUS;     // the Wifi radio's status

char server[] = "arduino.cc";

// Initialize the Ethernet client object
WiFiEspClient client;

void setup()
{
  // initialize serial for debugging
  Serial.begin(115200);
  // initialize serial for ESP module
  Serial1.begin(9600);
  // initialize ESP module
  WiFi.init(&Serial1);

  // check for the presence of the shield
  if (WiFi.status() == WL_NO_SHIELD) {
    Serial.println("WiFi shield not present");
    // don't continue
    //while (true);
  }

  // attempt to connect to WiFi network
  while ( status != WL_CONNECTED) {
    Serial.print("Attempting to connect to WPA SSID: ");
    Serial.println(ssid);
    // Connect to WPA/WPA2 network
    status = WiFi.begin(ssid, pass);
  }

  // you're connected now, so print out the data
  Serial.println("You're connected to the network");

  printWifiStatus();

  Serial.println();
  Serial.println("Starting connection to server...");
  // if you get a connection, report back via serial
  if (client.connect(server, 80)) {
    Serial.println("Connected to server");
    // Make a HTTP request
    client.println("GET /asciilogo.txt HTTP/1.1");
    client.println("Host: arduino.cc");
    client.println("Connection: close");
    client.println();
  }
}

void loop()
{
  // if there are incoming bytes available
  // from the server, read them and print them
  while (client.available()) {
    char c = client.read();
    Serial.write(c);
  }

  // if the server's disconnected, stop the client
  if (!client.connected()) {
    Serial.println();
    Serial.println("Disconnecting from server...");
    client.stop();

    // do nothing forevermore
    while (true);
  }
}

void printWifiStatus()
{
  // print the SSID of the network you're attached to
  Serial.print("SSID: ");
  Serial.println(WiFi.SSID());

  // print your WiFi shield's IP address
  IPAddress ip = WiFi.localIP();
  Serial.print("IP Address: ");
  Serial.println(ip);

  // print the received signal strength
  long rssi = WiFi.RSSI();
  Serial.print("Signal strength (RSSI):");
  Serial.print(rssi);
  Serial.println(" dBm");
}````

Output:
````[WiFiEsp] I >>> TIMEOUT >>>
[WiFiEsp] >>> TIMEOUT >>>
[WiFiEsp] Initializing ESP module
[WiFiEsp] >>> TIMEOUT >>>
[WiFiEsp] >>> TIMEOUT >>>
[WiFiEsp] >>> TIMEOUT >>>
[WiFiEsp] >>> TIMEOUT >>>
[WiFiEsp] >>> TIMEOUT >>>
[WiFiEsp] Cannot initialize ESP module
[WiFiEsp] >>> TIMEOUT >>>
[WiFiEsp] No tag found
WiFi shield not present
Attempting to connect to WPA SSID: xyz
[WiFiEsp] >>> TIMEOUT >>>

Please let me know in case you figure out the issue.

you don't set the AT baud rate in the WiFiEsp sketch. use AT+UART=9600,8,1,0,0 to set 9600 baud as default

@jsotola tried formatting with ctrl+k but it's not taking effect, looks like a bug in stack overflow :D

@Juraj meaning set these in WiFi esp sketch code??

It’s not a bug in Stack Overflow.

doesn't matter how you execute it. it will be remembered as default

@Rajesh To make a code block inside of an enumeration, you need to add another 4 spaces at the beginning of each line, so 4 spaces for the enumeration item and another 4 for the code block. That is not a bug, but just the way, that such markdown languages work, that SE uses. It is easier to copy the text into a decent text editor, command it to indent the corresponding lines by 4 spaces and then copy it back to the question editor. The toolbar of the editor is only meant for easier formatting

Done formatting as requested

Judge from the sketches you've tried, you are jumping from one example code to another example code without understanding how actually the code works. On your sketch 2, if a request-URI is not a full URL, you need to send extra http header "Host: jsonplaceholder.typicode.com" to indicate which server you want to get data from, and you also need to send an extra CR-LF (as in your sketch 3 and see HTTP/1.1 Request). On sketch 3, as mentioned by @Juraj, you need to setup the baud rate with AT command.

Thanks @hcheung, I am able to send request after formatting as suggested but unable to read response. Any idea what could be the issue now: https://arduino.stackexchange.com/questions/77341/unable-to-read-arduinoesp8266-full-get-response


text:
Code is not looping correctly when running on battery
static const int dry = 570;
static const int wet = 225;
static const int RELAY = 2;
static const unsigned long DELAY_1_S      = 1000;
static const unsigned long DELAY_1_MINUTE = DELAY_1_S * 60;
static const unsigned long DELAY_1_HOUR   = DELAY_1_MINUTE * 60;
static boolean watering = false;

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

void loop() {
  int sensorVal = analogRead(A0);
  int percentageHumidity = map(sensorVal, wet, dry, 100, 0);
  Serial.print(percentageHumidity);
  Serial.println("%");
  if (!watering && percentageHumidity < 60){
    watering = true;
    Serial.println("Watering!!!");
    digitalWrite(RELAY, HIGH);
    delay(3*DELAY_1_S);
    digitalWrite(RELAY, LOW);
    watering = false;
  }
  Serial.println(DELAY_1_S * 10);
  delay(10*DELAY_1_S);
}

I have an analog reading at A0 from a capacitance water sensor. If the sensors read a value of 60% or less humidity it will activate a water pump. The water pump is connected through a 5v relay and the water pump has its independent power supply. For some reason, the code works when connected to the USB as intended, but when I power it with the battery it connects always the water pump.

Which board and which battery do you use? How are they connected?

Show your wiring.  If it works on USB but not on battery then it probably isn't the code that's the issue.  You got all the grounds connected?

Are your wet and dry values the same when running from battery? Have you determined if they should be changed?


text:
Unable to read Arduino+ESP8266 full get Response
Using below code I am able to invoke HTTP Get request, but I am not able to read full HTTP Response. Observing only output like( +IPD,0,141:HTTP/1.7. ). Please let me know how can I read full response?
Any Idea what is the issue?
#include <SoftwareSerial.h>

#define RX 2
#define TX 3
String WIFI_SSID = "xyz";       // Your WiFi ssid
String PASSWORD = "xys";         // Password

String HOST = "192.168.0.156";
String PATH = "/test";
String PORT = "8080";

int countTrueCommand;
int countTimeCommand;
boolean found = false;

SoftwareSerial esp8266(RX, TX);

void setup() {
  Serial.begin(9600);
  esp8266.begin(9600);
  esp8266.println("AT");
  Serial.println(esp8266.read());
  sendCommandToESP8266("AT", 5, "OK");
  sendCommandToESP8266("AT+CWMODE=1", 5, "OK");
  sendCommandToESP8266("AT+CWJAP=\"" + WIFI_SSID + "\",\"" + PASSWORD + "\"", 20, "OK");
}

void loop() {
  String postRequest = "GET " + PATH  + " HTTP/1.1\r\n" +
                       "Host: " + HOST + "\r\n" +
                       "Accept: *" + "/" + "*\r\n" +
                       "\r\n";

  sendCommandToESP8266("AT+CIPMUX=1", 5, "OK");
  sendCommandToESP8266("AT+CIPSTART=0,\"TCP\",\"" + HOST + "\"," + PORT, 15, "OK");
  String cipSend = "AT+CIPSEND=0," + String(postRequest.length());
  sendCommandToESP8266(cipSend, 4, ">");
  sendData(postRequest);
  readESP8266(8000);
  sendCommandToESP8266("AT+CIPCLOSE=0", 5, "OK");
}

void sendCommandToESP8266(String command, int maxTime, char readReplay[]) {
  Serial.print(countTrueCommand);
  Serial.print(". at command => ");
  Serial.print(command);
  Serial.print(" ");
  while (countTimeCommand < (maxTime * 1))
  {
    esp8266.println(command);
    if (esp8266.find(readReplay))
    {
      found = true;
      break;
    }

    countTimeCommand++;
  }

  if (found == true)
  {
    Serial.println("Success");
    countTrueCommand++;
    countTimeCommand = 0;
  }

  if (found == false)
  {
    Serial.println("Fail");
    countTrueCommand = 0;
    countTimeCommand = 0;
  }

  found = false;
}

void sendData(String postRequest) {
  Serial.println(postRequest);
  esp8266.println(postRequest);
  delay(1500);
  countTrueCommand++;
}

void readESP8266(const int timeout)
{
  String reponse = "";
  long int time = millis();
  while( (time+timeout) > millis())
  {
    while(esp8266.available())
    {
      reponse+=esp8266.readString();
    }
  }
  Serial.print(reponse);
}

Output:
Success
1. at command => AT+CWMODE=1 Success
2. at command => AT+CWJAP="xyz","xys" Success
3. at command => AT+CIPMUX=1 Success
4. at command => AT+CIPSTART=0,"TCP","192.168.0.156",8080 Success
5. at command => AT+CIPSEND=0,56 Success
GET /test HTTP/1.1
Host: 192.168.0.156
Accept: */*

busy s...

Recv 56 bytes

SEND OK

+IPD,0,141:HTTP/1.7. at command => AT+CIPCLOSE=0 Success

+IPD,0,141 means there are 141 bytes data return from the response, your code simply closed too early without read and parsing the data.

But I have already added delay of 8 sec, shall I add more delay?? readESP8266(8000); If you can provide any code that will be helpful

It is not about the delay (actually 8s is way too long), it is about continue to read the data, sorry I don't have time to write the code for you, but you can read one of my library on reading and parsing the response.

@hcheung Thanks for your help, I was able to perform HTTP GET request using LiteESP8266Client.h but 1 issue I am facing is after few call probably Arduino memory is becoming full, any idea how we can fix that

Finally the HTTP Get request with Arduino Uno + ESP8266 Wifi shield which is working is below:
// This is a demo example using a public http server for testing both GET and POST requests
#include <Arduino.h>
#include <LiteESP8266Client.h>

#define PACKET_MTU 1500    // Standard network MTU is 1500 bytes

LiteESP8266 radio;

const char ssid[] PROGMEM = "xyz";    //change it to your wifi SSID
const char password[] PROGMEM = "abc";    //change it to your wifi password
const char host[] PROGMEM = "192.168.0.156";
const int port = 8080;

const char http_get_request[] PROGMEM = "GET /test HTTP/1.1\r\n";
const char http_useragent[] PROGMEM = "User-Agent: Arduino-stm32/0.1\r\n";
const char http_content_type_json[] PROGMEM = "Content-Type: application/json\r\n";
const char http_host[] PROGMEM = "Host: 192.168.0.156\r\n";
const char http_close_connection[] PROGMEM = "Connection: close\r\n\r\n";
const char http_content_length_header[] PROGMEM = "Content-Length: ";
const char success[] PROGMEM = "success";
const char failed[] PROGMEM = "failed";
const char CRLF[] PROGMEM = "\r\n";
const char error_data_null[] PROGMEM = "Error: data came back null.";

void setupStationMode() {
  Serial.print("Setup station mode... ");
  if (radio.set_station_mode()) {
    Serial.println("success");
  } else {
    Serial.println("failed");
  }
}

void joinAP() {
  Serial.print("Join AP ");
  Serial.print(ssid);
  Serial.print("... ");
  if (radio.connect_to_ap(ssid, password)) {
    Serial.println("Success");
  } else {
    Serial.println("Failed");
  }
}

void establishTcpConnect() {
  Serial.print("Establish TCP Connection... ");
  if (radio.connect_progmem(host, port)) {
    Serial.println( "Success");
  } else {
    Serial.println( "Failed");
  }
}

void getHttpPacket() {
  char *data;
  while ((data = radio.get_response_packet(PACKET_MTU, 5000))) {
    if (data) {
      Serial.println("Packet Received...");
      Serial.println(data);
    } else {
      Serial.println(error_data_null);
    }
  }
  free(data);
}

void httpGet() {
  Serial.println("Sending GET request... ");
  radio.send_progmem(http_get_request);
  radio.send_progmem(http_useragent);
  radio.send_progmem(http_host);
  radio.send_progmem(http_close_connection);
}
void setup() {
  delay(2000);
  radio.begin(9600,2,3);
  Serial.begin(9600);
  while (!Serial) {};

  setupStationMode();
  joinAP();
}

void loop() {
  establishTcpConnect();

  httpGet();
  getHttpPacket();
  }

Output:
Setup station mode... success
Join AP ⸮... Success
Establish TCP Connection... Success
Sending GET request...
Packet Received...
HTTP/1.1 200
Content-Type: text/plain;charset=UTF-8
Content-Length: 27
Date: Fri, 07 Aug 2020 13:04:03 GMT
Connection: close

Greetings from Spring Boot!

But one issue I am facing is after few call the HTTP invocation is getting stopped probably memory being full. Will check this.

If you run the example on the httpbin.org test site, do you face the same problem?

BTW, don't post your new problem as an "answer", since your code is deviated and totally different from your original question, you should post it as a new question.

The problem could be coming from your server at 192.168.0.156/test, so you should run your sketch on httpbin.org server to make the problem is not caused by this client sketch first.

Posted new Question: https://arduino.stackexchange.com/questions/77353/arduino-esp8266-wifi-shield-get-request-with-liteesp8266client-stops-after-few-h . Though output of 192.168.0.156/test is quite small

@hcheung tried with other REST server as suggested and same issue is observed:

I have updated response here: https://arduino.stackexchange.com/questions/77353/arduino-esp8266-wifi-shield-get-request-with-liteesp8266client-stops-after-few-h


text:
Adeept Arduino Mega 2560 isn't recognized
So recently, I purchased an Arduino Mega 2560 Kit from Amazon, which was customized from this company called Adeept. But when I tried to plug it into my computer, it didn't recognize it. This means my device manager didn't change in any way, shape, or form. The Arduino IDE that I fully downloaded couldn't upload code, and I also tried using different USB cords, and I tried using another computer as well, but it still didn't work.
Is there a driver that I need to upload or something else that I'm missing?
Thank you for your time :)

ask Adeept ... BTW, if windows does not detect it, then trying Arduino IDE is an exercise in futility


text:
ESP-NOW and WIFI and OTA at the same time on Sender and Receiver
I am trying to set up two ESP32s so that they can be updated via OTA and at the same time send sensor readings using ESP-NOW, from Sender Board to Receiver Board.
For this to work both boards must connect to wifi and simultaneously send messages over ESP-NOW.
I don't mind using a mode where a button is pressed and Wifi is only then enabled but switching wifi on and off seems to have intermittent success.
I have tried setting the channels to the same on both boards but this does not work.
In the example below I have stripped all the OTA code out and the code needed for ESP-NOW and just the line for WIFI enable

WiFi.begin(ssid, password);

which when enabled causes the delivery to fail.
Here is my Sender Code:
        #include <esp_now.h>
        #include <WiFi.h>
        #include <Wire.h>
        #define ssid "MYNETWORKSSID"
        #define password "mynetworkpassword"

         const int sNine = 33;

         #define CHAN_AP 2

        uint8_t broadcastAddress[] = {0x24, 0x62, 0xAB, 0xDC, 0x70, 0x90};
        int hall;

        String success;

        typedef struct struct_message {
            int hall;
        } struct_message;
        struct_message hallReadings;

        // Callback when data is sent
        void OnDataSent(const uint8_t *mac_addr, esp_now_send_status_t status) {
          Serial.print("\r\nLast Packet Send Status:\t");
          Serial.println(status == ESP_NOW_SEND_SUCCESS ? "Delivery Success" : "Delivery Fail");
          if (status ==0){
            success = "Delivery Success :)";
          }
          else{
            success = "Delivery Fail :(";
          }
        }

        void setup() {
          // Init Serial Monitor
          Serial.begin(115200);
          WiFi.mode(WIFI_STA);
         WiFi.begin(ssid, password); // PROBLEMATIC LINE

          // Init ESP-NOW
          if (esp_now_init() != ESP_OK) {
            Serial.println("Error initializing ESP-NOW");
            return;
          }
          // Once ESPNow is successfully Init, we will register for Send CB to
          // get the status of Trasnmitted packet
          esp_now_register_send_cb(OnDataSent);

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

          // Add peer
          if (esp_now_add_peer(&peerInfo) != ESP_OK){
            Serial.println("Failed to add peer");
            return;
          }
        }

        void loop() {
          // getReadings();

           hallReadings.hall = analogRead(sNine);

          esp_err_t result = esp_now_send(broadcastAddress, (uint8_t *) &hallReadings, sizeof(hallReadings));

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

Here is my Receiver code:
#include <esp_now.h>
#include <WiFi.h>
#include <Wire.h>

 const int sNine = 15;

//Wi-Fi channel (must match the gateway wi-fi channel as an access point)
#define CHAN_AP 2

// Define variables to store incoming readings
int incomingHall;

//Structure example to send data
//Must match the receiver structure
typedef struct struct_message {
    int hall;
} struct_message;

// Create a struct_message to hold incoming sensor readings
struct_message incomingReadings;

void updateDisplay(){

  Serial.print(incomingReadings.hall);
}

// Callback when data is received
void OnDataRecv(const uint8_t * mac, const uint8_t *incomingData, int len) {
  memcpy(&incomingReadings, incomingData, sizeof(incomingReadings));
  incomingHall = incomingReadings.hall;
}

void setup() {
  // Init Serial Monitor
  Serial.begin(115200);
  // Set device as a Wi-Fi Station
  WiFi.mode(WIFI_STA);
  // Init ESP-NOW
  if (esp_now_init() != ESP_OK) {
    Serial.println("Error initializing ESP-NOW");
    return;
  }
  // Register for a callback function that will be called when data is received
  esp_now_register_recv_cb(OnDataRecv);
}

void loop() {

  updateDisplay();
  delay(100);
}

what is your specific question?

How can I have OTA enabled on both boards and also use ESP-now? when I activate wifi ESPnow stops working. Thanks!

If you want to switch the softAP connection On/OFF you can do like StefanL38 suggests and have the Receiver transmit a ESP-NOW message with a value to the Sender, but you don't need a reboot. You can drop softAP and come up as STA or vise versa, for example.
    if(incomingid == 3){
      incomingValue = incomingReadings.Value;

      // to allow OTA, using Elegant OTA, haven't tried others.

    if(incomingValue == 1){
      WiFi.softAP(ssid,password,6);
      Serial.print("Connecting to ESP32 SSID ");
      Serial.println(ssid);
      IPAddress IP = WiFi.softAPIP();
      Serial.print("AP IP address: ");
      Serial.println(IP);
      WiFi.printDiag(Serial);
    }

      // to disconnect and allow ESP-NOW via Station mode.

   else if(incomingValue == 0){
      WiFi.softAPdisconnect(true);
      delay(1000);
      WiFi.mode(WIFI_STA);
      delay(1000);
      WiFi.printDiag(Serial); // STA Defaults to channel 1
      esp_wifi_set_promiscuous(true);
      esp_wifi_set_channel(6, WIFI_SECOND_CHAN_NONE); // channel 6 setup
      esp_wifi_set_promiscuous(false);
      WiFi.printDiag(Serial);
    }
  }

Do you know where do you put this code. When I try to put this code anywhere other than Set up the ESP8266 crashes as it uploads the firmware.  Is the EEPROM a way to use it in set up section ?

It would go under the Callback when data is received function of ESP NOW ie… void OnDataRecv

Another method that works if you don't mind having both at the same time:
Instead of WiFi.begin(ssid, password);
I use WiFi.softAp(ssid,password,channel); for both Sender and Receiver.

I do something similar on a ESP8266 retrieving time from a NTP-server.
Though it is just a "work around".

I connect to the router retrieving the NTP-time.
storing the time-information into RTC-RAM including a flag that indicates "time received"
then do a software-RESET
the setup-function checks this flag to decide if the ESP8266 shall connect to the router or shall keep WiFi OFF and activate ESP-NOW

if you want to use this for OTA it could "work" like this
sending a special ESP-NOW-Message initiating setting a flag "do_OTA" in RTC-RAM and then re-boot
the setup-function looks for this flag "do_OTA" to be set does what its name says
clearing the "do_OTA"-flag
What I don't know is writing new code into flash is a different thing than just re-booting through a software-reset. So maybe the content of the RTC-RAM gets lost through the update-process.
If so you could write the flag into flash using LittleFS
best regards Stefan