Disconnection Problem with Blynk IoT

Hello everyone, I have the same problem. Blynk keeps getting disconnected from the internet after printing “First Schedule is Done”. I don’t know what to do.

here is my code

To add an information about my problem, the BLYNK seems to reconnect after I put a new time to the START TIME INPUT widget, the BLYNK disconnects completely if the END TIME INPUT is done.

#define BLYNK_TEMPLATE_ID "TMPL6wdeIlza-"
#define BLYNK_TEMPLATE_NAME "Quickstart Template"


#define BLYNK_PRINT Serial
#include <WiFi.h>
#include <BlynkSimpleEsp32.h>
#include <ESP32Servo.h>
#include <WidgetRTC.h>
#include <NTPClient.h>
#include <WiFiUdp.h>
#include <DallasTemperature.h>
#include <OneWire.h>

#define ONE_WIRE_BUS 0
#define BLYNK_GREEN "#23C48E"
#define BLYNK_RED "#D3435C"

const long utcOffsetInSeconds = 28800;  // Adjust this based on your timezone.... 
WiFiUDP ntpUDP;
NTPClient timeClient(ntpUDP, "time.nist.gov", utcOffsetInSeconds);

#include <Wire.h>
#include "RTClib.h"
RTC_DS3231 rtc;

#define BLYNK_AUTH_TOKEN 

const char* ssid = "";
const char* pass = "TMFTFS23";

WidgetTerminal terminal(V3);
WidgetLED led1(V1);
WidgetLED led16(V16);
WidgetLED led15(V15);
WidgetLED led14(V14);
WidgetLED led5(V5);

OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);
Servo myservo;
BlynkTimer timer;

bool isFirstConnect = true;


int button;
int startTime1, endTime1, day1;
int startTime2,  endTime2, day2;
int startTime3, endTime3, day3;
int startTime4, endTime4, day4;
int current_time, current_day;

String displaycurrenttimepluswifi;
String message;

int wifisignal;

float temp;


BLYNK_WRITE(V0)  {
    button = param.asInt();

    if ( button == 1)
  {
    myservo.write(90);
  }

else { myservo.write(0);

}
    
  }

  BLYNK_WRITE(V10) {   // Scheduler #1 Time Input widget  
  
  startTime1 =param[0].asInt();
  endTime1 = param[1].asInt();

  }

  //TimeInputParam t(param);
//int dayadjustment = -1;  
    //if(weekday() == 1){
      //dayadjustment =  6; // needed for Sunday, Time library is day 1 and Blynk is day 7


  void DoAutoFeed()  {
    led1.off();
    DateTime now = rtc.now();

  int hour1 = now.hour();
   //if ( hour1 > 12 ) {
    //hour1 = hour1 - 12;}
  //if (HH == 0){ HH =12;}
  //if (HH > 12 ){ HH = HH -12;}
  int minute1 = now.minute();
  current_day = now.day();
  current_time = hour1 * 3600 + minute1 * 60;


 if (current_time == startTime1){ //&& Day == day1)
    myservo.write(90); // Rotate servo to 90 degrees if within scheduled time
    delay(1000); // Adjust delay as needed
  } else if (current_time == endTime1){// Day == day1) {
    myservo.write(0);
    Blynk.virtualWrite(V17, "First Schedule Done");
    while (current_time >= endTime1){ //&& Day == day1) {
      led1.on();
    }
  }

  }


  //TimeInputParam t(param);
 // unsigned int nowseconds = ((hour() * 3600) + (minute() * 60) + second());
  //unsigned int startseconds = (t.getStartHour() * 3600) + (t.getStartMinute() * 60);  
  //unsigned int stopseconds = (t.getStopHour() * 3600) + (t.getStopMinute() * 60);
  //int dayadjustment = -1;  
  //if(weekday() == 1){
    //dayadjustment = 6; // needed for Sunday Time library is day 1 and Blynk is day 7
  //}
  //if(t.isWeekdaySelected((weekday() + dayadjustment))){ //Time library starts week on Sunday, Blynk on Monday  
    //Schedule is ACTIVE today 
    //if(nowseconds >= startseconds - 31 && nowseconds <= startseconds + 31 ){    // 62s on 60s timer ensures 1 trigger command is sent
      //myservo.write(90);  // turn on virtual LED
      //Serial.println("Schedule 1 started");
    //}                  
    //if(nowseconds >= stopseconds - 31 && nowseconds <= stopseconds + 31 ){   // 62s on 60s timer ensures 1 trigger command is sent
      //myservo.write(0);   // turn OFF virtual LED
      //Serial.println("Schedule 1 finished");
  



void setup() {
  Serial.begin(115200);
  delay(100);
  myservo.attach(4);
  WiFi.begin(ssid, pass);
  rtc.begin();
  

  // Wait for WiFi connection
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("WiFi connected");

  delay(3000);

  if (!rtc.begin()) {
    Serial.println("Couldn't find RTC");
    Serial.flush();
    while (1) delay(10);
  }

  Blynk.begin(BLYNK_AUTH_TOKEN, ssid, pass, "blynk.cloud", 80);
  sensors.begin();
  timeClient.begin();
  timeClient.update();
  timer.setInterval(1000L, SensorsData);
   timer.setInterval(2500L, clockvalue);
   timer.setInterval(12000L, sendWifi);
   timer.setInterval(5000L, DoAutoFeed);


  // Adjust RTC time only if WiFi is connected
  if (WiFi.status() == WL_CONNECTED) {
    rtc.adjust(DateTime(timeClient.getEpochTime()));
  }
}

BLYNK_CONNECTED() {
if (isFirstConnect) {
  Blynk.syncAll();
isFirstConnect = false;
}
}

void sendWifi() {
  wifisignal = map(WiFi.RSSI(), -105, -40, 0, 100);
}

void clockvalue(){

  DateTime now = rtc.now();
  int HH = now.hour();
  if (HH == 0){ HH =12;}
  if (HH > 12 ){ HH = HH -12;}

  int MM = now.minute();
  String displayhour  = String(HH, DEC);
int hourdigits = displayhour.length();
if (hourdigits == 1){
  displayhour = "0" + displayhour;
}

  String displayminute = String(MM, DEC);
  int minutedigits = displayminute.length();
  if(minutedigits == 1){
    displayminute = "0" + displayminute;
  }
  displaycurrenttimepluswifi = "                                          Clock:  " + displayhour + ":" + displayminute + "               Signal:  " + wifisignal +" %";
  Blynk.setProperty(V17, "label", displaycurrenttimepluswifi);
  
}

void SensorsData() {
    led15.on();
    sensors.requestTemperatures();
    temp = sensors.getTempCByIndex(0);
    Serial.println(temp);
    Blynk.virtualWrite(V6, temp);
    Blynk.virtualWrite(V17, temp);
    

    if (temp >= 25 && temp <= 30) {
        // Turn on led7
        led15.setColor(BLYNK_GREEN);
        delay(1000);
    } else {
        // Turn off led7
        led15.setColor(BLYNK_RED);
        delay(1000);
    }
  }




void loop() {
  Blynk.run();
  timer.run();
  timeClient.update();
 


  delay(1000);
}

@Lebay You originally posted this in a topic called “Disconnection problem with Blynk Legacy Local Server”. The code you’ve posted is clearly not written for use with Blynk Legacy and your own Blynk local server, so I’ve moved your post to a new topic that I’ve given a more appropriate title.

Your code doesn’t include a command to output that message, did you mean “First Schedule Done” ?

You’re doing some very weird stuff in your sketch, including:

  • Creating your own WiFi connection then using Blynk.Begin() which automatically creates a WiFi connection
  • Using an external NTP time server rather than using Blynk’s internal NTP functionality, but only using this to set your hardware RTC module’s time when the device is started-up and connects to WiFi
  • Not setting your ESP32’s internal clock to the hardware RTC’s time, forcing you to constantly read the current time from the hardware RTC
  • Using blocking delay() commands in your sketch

Is this your code, or something that you’ve found elsewhere?

Pete.

Apologies, yes I mean First Schedule Done.

  • Do you mean I declared wifi.h when I don’t have to?
  • I didn’t know I could use BLYNK internal NTP, I used the NTP to set the time of my RTC hardware when it connects to the WIFI, because when I didn’t use the NTP, my RTC time was very delayed for 6 minutes and my project requires an output that is less than 6 seconds
  • I thought I didn’t need the ESP32 RTC since I have the RTC hardware, and I need to use the RTC hardware because my project needs to work even without the internet.
  • I used delay() because I read it that it avoids flooding the ESP32, or am I wrong?
    I used the codes that I found on the internet then editing in on my own

No. This is redundant (but read my comments regarding working without the internet below)…

Read this…

Hardware RTCs aren’t that accurate, so require synchronising with an external time source (NTP or Blink’s server time via the “RTC” functionality linked above) every so often. How often depends on your RTC hardware and the accuracy that you require. Normally you’d do this once every day or once every week.

Retrieving the time from the hardware RTC is slow, so you’d normally use the RTC to set the device’s internal time and use this instead.

This sketch won’t work without the internet for two reasons:

  • Blynki.begin() is a blocking function and all code execution will halt there if an internet or Blynk server connection can't be established. The solution is to manage you own WiFi connection (in other words dont delete the code that I said was redundant) then use the Blynk.config(BLYNK_AUTH_TOKEN)andBlynk.connect(optional timeout in millis)instead of usingBlynk.begin(). However, if you do this then you need to change teh way that your Blynk.run()` command is called in your void loop, to this…
     if(Blynk.connected())
     {
        Blynk.run();
     }
  • Your current WiFi connection routine is also blocking, so code execution will stop at that point if a WiFi connection can’t be established. You would need to use a routine which made a finite number of connection attempts before continuing.

You also need to add-in routines (via BlynkTimer) that regularly check if WiFi and/or Blynk are connected, and if not then attempt to re-connect.

If you search the forum for “Blynk.config()” you’ll find more on all of this.

You are wrong. delay() commands halt the execution of your code, preventing the regular handshake communication between your device and the Blynk server. BlynkTimer is used to prevent flooding the Blynk server.

Pete.

Thank you Pete! I will be incorporating these suggestions and will reply if the problem still exist. BTW, are these mainly the reason why BLYNK keep getting disconnected from the server?

It’s difficult to say, but it’s always best to sort-out the dodgy stuff then try to diagnose any remaining issues after that.
The serial monitor should give some clauses about the cause of the disconnection.

Pete.

Upon editing my code, I found out that BLYNK keeps disconnecting because of this. And I found some codes here about the BLYNK config and it works now. I’m still working on BLYNK RTC, but it’s not a Disconnection problem anymore so I think I’ll be commenting on a different forum. Thank you Pete!

You should avoid using while() commands with Blynk, as a general rule because they can also block execution of the void loop - which will cause a disconnection because Blynk.run() isn't being executed. Use if()` commands instead.

Pete.