My ESP-01 (Wifi Module) connected to arduino always disconnects and reconnects repeatedly to blynk.

My ESP-01 (Wifi Module) connected to arduino always disconnects and reconnects repeatedly to blynk.

Hello everyone, I know that this has become a fairly overused problem, I have seen several solutions on the internet and then implemented them into my project but it still seems to be problematic. At first I tried to code just to turn on 1 led only and it didn’t have any problem at all, then I tried to add some sensors like my original goal and changed most of the code of course then this main problem appeared. Btw, I’m still new at this so sorry if my code is still inefficient or I don’t know something yet.

I’m working on a device project that will transmit data on temperature, humidity, gas detection, fire detection and lights that can turn on automatically when there is no light for my school project.

Hardware: Arduino Uno with ESP-01 (Wifi) Connection
Blynk.cloud port 80
Blynk Library version 1.3.2
Sketch uses 25886 bytes (80%) of program storage space. Maximum is 32256 bytes.
Global variables use 1385 bytes (67%) of dynamic memory, leaving 663 bytes for local variables. Maximum is 2048 bytes.


#define BLYNK_TEMPLATE_ID "TMPL6lAXQsImD"
#define BLYNK_TEMPLATE_NAME "Project P5 Grade XII 12"
#define BLYNK_AUTH_TOKEN "BL7onBGBZD4p9_YytS7RwlKJM4DSWUhX"
#define BLYNK_PRINT Serial

#include <ESP8266_Lib.h>
#include <BlynkSimpleShieldEsp8266.h>
#include <DHT.h>

// WiFi Credentials
char ssid[] = "HARISBIKE";
char pass[] = "naura2017";

// Hardware Serial
#include <SoftwareSerial.h>
SoftwareSerial EspSerial(3, 2); // RX, TX
#define ESP8266_BAUD 115200
ESP8266 wifi(&EspSerial);

// Pin Definitions
#define DHT_PIN A0
#define MQ2_PIN A1
#define LDR_PIN A2
#define BUZZER_PIN 6
#define LED_PIN 5

// Sensor Definitions
#define DHTTYPE DHT22
DHT dht(DHT_PIN, DHTTYPE);
BlynkTimer timer;

// Global Variables
float humidity = 0;
float temperature = 0;
int MQ2_Val = 0;
int ldrValue = 0;

// Connection tracking
unsigned long lastConnectionAttempt = 0;
const unsigned long CONNECTION_TIMEOUT = 10000;  // 10 seconds
bool isConnectedToBlynk = false;

void triggerAlarmTone() {
  for (int i = 1000; i < 2000; i++) {
    tone(BUZZER_PIN, i);
    delay(1);
  }
  for (int i = 2000; i > 1000; i--) {
    tone(BUZZER_PIN, i);
    delay(1);
  }
}

void reconnectBlynk() {
  if (!Blynk.connected()) {
    Serial.println("Blynk not connected. Reconnecting...");
    
    // Attempt to reconnect
    Blynk.begin(BLYNK_AUTH_TOKEN, wifi, ssid, pass, "blynk.cloud", 80);
    
    // Update connection status
    isConnectedToBlynk = Blynk.connected();
    
    if (isConnectedToBlynk) {
      Serial.println("Reconnected to Blynk successfully!");
    } else {
      Serial.println("Failed to reconnect to Blynk.");
    }
  }
}

void monitorConnection() {
  // Check connection status
  if (!Blynk.connected()) {
    unsigned long currentTime = millis();
    
    // If not connected and enough time has passed since last attempt
    if (currentTime - lastConnectionAttempt >= CONNECTION_TIMEOUT) {
      reconnectBlynk();
      lastConnectionAttempt = currentTime;
    }
  }
}

void readDHTSensor() {
  humidity = dht.readHumidity();
  temperature = dht.readTemperature();
  
  if (isnan(humidity) || isnan(temperature)) {
    Serial.println("Failed to read from DHT sensor!");
    return;
  }

  // Only send data if connected to Blynk
  if (Blynk.connected()) {
    Blynk.virtualWrite(V5, humidity);
    Blynk.virtualWrite(V6, temperature);
  }

  Serial.print("Temperature: ");
  Serial.println(temperature);
  Serial.print("Humidity: ");
  Serial.println(humidity);
}

void readMQ2Sensor() {
  // Reading MQ2 Gas Sensor
  MQ2_Val = analogRead(MQ2_PIN);
  for (int x = 0; x < 100; x++) {
    MQ2_Val = MQ2_Val + analogRead(MQ2_PIN);
  }
  MQ2_Val = MQ2_Val / 100.0;

  // Only send data if connected to Blynk
  if (Blynk.connected()) {
    Blynk.virtualWrite(V0, MQ2_Val);
    Blynk.virtualWrite(V2, MQ2_Val);
  }

  Serial.print("MQ2 Level: ");
  Serial.println(MQ2_Val);
}

void checkGasLeak() {
  if (MQ2_Val > 900 && Blynk.connected()) {
    triggerAlarmTone();
    
    // Use Blynk.logEvent for notifications
    Blynk.logEvent("gas_alert", "Gas Leakage Detected!");
    
    Serial.println("ALERT: Gas Detected!");
    Blynk.virtualWrite(V7, 1);  // Gas alarm status
  } else {
    Blynk.virtualWrite(V7, 0);
  }
}

void readLDRSensor() {
  // Reading LDR Light Sensor
  ldrValue = analogRead(LDR_PIN);
  
  // Only send data if connected to Blynk
  if (Blynk.connected()) {
    Blynk.virtualWrite(V1, ldrValue);

    // Control light based on intensity
    if (ldrValue <= 300) {
      digitalWrite(LED_PIN, HIGH);  // Turn on light in dark
      Blynk.virtualWrite(V3, 1);
    } else {
      digitalWrite(LED_PIN, LOW);  // Turn off light in bright
      Blynk.virtualWrite(V3, 0);
    }
  }

  Serial.print("LDR Value: ");
  Serial.println(ldrValue);
}

void checkFireDetection() {
  if (temperature > 40 && Blynk.connected()) {
    triggerAlarmTone();
    
    // Use Blynk.logEvent for notifications
    Blynk.logEvent("fire_alert", "High Temperature Alert!");
    
    Serial.println("EMERGENCY: Fire Detected!");
    Blynk.virtualWrite(V8, 1);  // Fire alarm status
    digitalWrite(LED_PIN, LOW);  // Turn off LED
  } else {
    Blynk.virtualWrite(V8, 0);
  }
}

void setup()
{
  // Initialize Serial
  Serial.begin(115200);
  EspSerial.begin(ESP8266_BAUD);
  delay(10);

  // Configure Pins
  pinMode(BUZZER_PIN, OUTPUT);
  pinMode(LED_PIN, OUTPUT);

  // Connect to Blynk with error handling
  Blynk.begin(BLYNK_AUTH_TOKEN, wifi, ssid, pass, "blynk.cloud", 80);
  
  // Initialize Sensors
  dht.begin();
  
  // Setup Timers with different intervals
  timer.setInterval(2000L, readDHTSensor);       // Read temperature every 2 seconds
  timer.setInterval(1500L, readMQ2Sensor);       // Read gas every 1.5 seconds
  timer.setInterval(1000L, readLDRSensor);       // Read light every 1 second
  timer.setInterval(3000L, checkGasLeak);        // Check gas every 3 seconds
  timer.setInterval(5000L, checkFireDetection);  // Check temperature every 5 seconds
  
  // Add connection monitoring timer
  timer.setInterval(10000L, monitorConnection);  // Check connection every 10 seconds
}

void loop()
{
  Blynk.run();
  timer.run();
}


The SoftwareSerial library is trying to emulate a hardware UART with software. Unfortunately the Arduino Uno doesn’t have enough processing power to reliably support high baud rates via SoftwareSerial.

You need to tell your ESP-01 (via an AT command, which is best done using an FTDI adapter) to communicate at 9600 baud then change your sketch to use the same baud rate.
How you do this will depend on the firmware version of your ESP-01.

The issue is fully explained here…

Pete.

Hello Pete

First of all I would like to thank you for solving my baudrate problem, this time you set the baudrate to 9600 and it worked fine without interruptions, but there is one new problem that appears which is “buffer overflow” as shown below:

10:00:46.476 ->     ___  __          __
10:00:46.476 ->    / _ )/ /_ _____  / /__
10:00:46.523 ->   / _  / / // / _ \/  '_/
10:00:46.570 ->  /____/_/\_, /_//_/_/\_\
10:00:46.570 ->         /___/ v1.3.2 on Arduino Uno
10:00:46.617 -> 
10:00:46.617 ->  #StandWithUkraine    https://bit.ly/swua
10:00:46.664 -> 
10:00:46.664 -> 
10:00:47.086 -> [647] Connecting to dhika
10:00:50.320 -> [3827] AT version:1.2.0.0(Jul  1 2016 20:04:45)
10:00:50.367 -> SDK version:1.5.4.1(39cb9a32)
10:00:50.367 -> v1.0.0
10:00:50.367 -> Mar 11 2018 18:27:31
10:00:50.414 -> OK
10:00:57.586 -> [11060] +CIFSR:STAIP,"192.168.135.15"
10:00:57.586 -> +CIFSR:STAMAC,"5c:cf:7f:7e:73:74"
10:00:57.633 -> [11070] Connected to WiFi
10:01:08.555 -> [21993] Ready (ping: 593ms).
10:01:24.305 -> [37670] Buffer overflow
10:01:24.446 -> [37810] Buffer overflow
10:01:24.586 -> [37936] Buffer overflow
10:01:35.790 -> [49107] Ready (ping: 706ms).

I have read some similar issues and among them I indicated that if there is one void that uses a loop like for example the settings for my siren, it will shower my esp with a lot of data causing buffering when I want to send an output such as turning on the lights from a button on the Blynk platform, is there any way to solve it? Oh yes, the cause of the high ping above is because I use the hotspot from my smartphone using the internet network where the signal is quite suck here, but when I connect to wifi with high speed the result is the same, namely buffer overflow only the ping is smaller.

Below is a fragment of my code that might be causing the problem

void triggerAlarmTone() {
  for (int i = 1000; i < 2000; i++) {
    tone(BUZZER_PIN, i);
    delay(1);
  }
  for (int i = 2000; i > 1000; i--) {
    tone(BUZZER_PIN, i);
    delay(1);
  }
}

In advance, thank you for your help

First of all, you can’t ignore the long ping times, they could be causing this.

Blynk.begin() is a blocking function, and once it’s called it will block all processing until a WiFi and Blynk connection are established, so much of your connection handling code is redundant as it will never reach the…

code will never be executed.

I’d remove all of the Blynk.connected() checks like this…

as they don’t achieve anything.

What type of account do you have (Free, Maker, Pro)?
If it’s a free account, how many devices are allowed in your Billing screen?

Pete.

I use blynk free plan, it allows me to have at least 10 devices but 1 template can only use 1 device.

In that case, the free plan you are using is limited to 30,000 messages between the device and the Blynk server every month. After that, your device will be online, but not updating Blynk.

Your timers are calling functions that send a total of 232 messages pre minute.
At that rate, you will use up your monthly message allowance in 129 minutes.

Pete.