BLYNK
BLYNK.IO       📲 GETTING STARTED       📗 DOCS       ❓HELP CENTER       👉 SKETCH BUILDER

Reconnection problem when the power goes out

Hello, please help. When the power is out, the router turns off when the power is back. I have a problem not to connect again

#define BLYNK_TEMPLATE_ID "**************"
#define BLYNK_DEVICE_NAME "****************"
#define BLYNK_AUTH_TOKEN "****************";
#define BLYNK_PRINT Serial
#include <ESP8266WiFi.h>
#include <BlynkSimpleEsp8266.h>
#include <WiFiManager.h>
#include <DNSServer.h>
#include "uptime.h"
#include <Ticker.h>
Ticker ticker;


char auth[] = BLYNK_AUTH_TOKEN;

#define TRIGGER_PIN 0    //Reset wifi 
#define LED_PIN 2        // led wifi
    
#define vPIN_UPTIME                 V0

bool IsFirstRun   = 1;

BlynkTimer   UltraTimer;

void tick()
{
  int state = digitalRead(LED_PIN);
  digitalWrite(LED_PIN, !state);
}
void configModeCallback (WiFiManager *myWiFiManager) {
  ticker.attach(0.2, tick);
}


BLYNK_CONNECTED() 
{
  if (IsFirstRun==1)
  {
    //Blynk.syncVirtual();
    IsFirstRun=0;
  }
}


void UPTIME(){
 

   uptime::calculateUptime();
   Serial.println(" "+String(uptime::getDays())+" days "+String(uptime::getHours())+":"+String(uptime::getMinutes())+":"+String(uptime::getSeconds()));
   Serial.print("\n");
   Blynk.virtualWrite(vPIN_UPTIME," "+String(uptime::getDays())+" days "+String(uptime::getHours())+":"+String(uptime::getMinutes())+":"+String(uptime::getSeconds()));

  
  
}





void setup()
{
  Blynk.config(auth);
  Serial.begin(115200);
  IsFirstRun = 1 ;
  UltraTimer.setInterval(1000L, UPTIME);


  pinMode(TRIGGER_PIN, INPUT_PULLUP);
  pinMode(LED_PIN, OUTPUT);
  
  WiFiManager wifiManager;
  wifiManager.setConnectTimeout(120);
  ticker.attach(0.6, tick);
  wifiManager.setAPCallback(configModeCallback);
  if (!wifiManager.autoConnect("ULTRA TECH IOT")) {                          //    your ap name
    ESP.reset();
    delay(1000);
  }
ticker.detach();
digitalWrite(LED_PIN, HIGH);

  WiFi.mode(WIFI_STA);
  while (Blynk.connect() == false) {}
  
}

void loop()
{
  
  Blynk.run();
  UltraTimer.run();
{
  int count = 0;

  while(digitalRead(TRIGGER_PIN) == LOW) {
    delay(100);
    count++;
    if(count > 30) {
  
      WiFi.disconnect();
      digitalWrite(LED_PIN, LOW);
      delay(1000);
      count = 0;
      digitalWrite(LED_PIN, HIGH);
      delay(100);
      ESP.reset();
      delay(1000);
    }
  }
}
}   


You can’t use delay in the void loop, you should keep your void loop clean as possible. Read this :

https://docs.blynk.io/en/legacy-platform/legacy-articles/keep-your-void-loop-clean

Thank you my friend @John93 can you provide a code that supports the wifi manager that is free of errors

Try this :

/*************************************************************
  Download latest Blynk library here:
    https://github.com/blynkkk/blynk-library/releases/latest
  Blynk is a platform with iOS and Android apps to control
  Arduino, Raspberry Pi and the likes over the Internet.
  You can easily build graphic interfaces for all your
  projects by simply dragging and dropping widgets.
    Downloads, docs, tutorials: http://www.blynk.cc
    Sketch generator:           http://examples.blynk.cc
    Blynk community:            http://community.blynk.cc
    Follow us:                  http://www.fb.com/blynkapp
                                http://twitter.com/blynk_app
  Blynk library is licensed under MIT license
  This example code is in public domain.
 *************************************************************
  This example shows how to keep WiFi connection on ESP8266.
 *************************************************************/

/* Comment this out to disable prints and save space */
#define BLYNK_PRINT Serial

/* Fill-in your Template ID (only if using Blynk.Cloud) */
//#define BLYNK_TEMPLATE_ID   "YourTemplateID"


#include <ESP8266WiFi.h>
#include <BlynkSimpleEsp8266.h>

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

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


int lastConnectionAttempt = millis();
int connectionDelay = 5000; // try to reconnect every 5 seconds

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

  Blynk.begin(auth, ssid, pass);
}

void loop()
{
  // check WiFi connection:
  if (WiFi.status() != WL_CONNECTED)
  {
    // (optional) "offline" part of code

    // check delay:
    if (millis() - lastConnectionAttempt >= connectionDelay)
    {
      lastConnectionAttempt = millis();

      // attempt to connect to Wifi network:
      if (pass && strlen(pass))
      {
        WiFi.begin((char*)ssid, (char*)pass);
      }
      else
      {
        WiFi.begin((char*)ssid);
      }
    }
  }
  else
  {
    Blynk.run();
  }
}

Thank you, I will give it a try

1 Like

It seems that it is not available on wifimanager

What is the error ?

I want to configure network name and password via wifi manager

I would recommend you to use blynk.edgent instead.

blynk edgent causes esp8266 to crash and then reboots again I can’t find a solution to the problem I want to use wifimanager

Why, what’s the error ?

Can I see the sketch ?
The sketch you used with blynk edgent.

#define BLYNK_TEMPLATE_ID "TMPLad2-LRb9"
#define BLYNK_DEVICE_NAME "timeer"
#define BLYNK_FIRMWARE_VERSION        "0.2.0"
#define BLYNK_PRINT Serial
#define APP_DEBUG
#include "BlynkEdgent.h"
#include <TimeLib.h>
#include <SoftwareSerial.h>
#include <ModbusMaster.h>
#include "uptime.h"

#define vPIN_UPTIME                   V0
#define vPIN_Relay1                   V1   // فيرجوال ريلي 1
#define vPIN_LedRelay1                V2   // ليد ريلي 1
#define vPIN_Time                     V3  // الساعة
#define vPIN_Date                     V4  // التاريخ
#define vPIN_Timer1                   V5  // مؤقت 1
#define vPIN_OnOffTimr1               V6   // تفعيل وتعطيل مؤقت 1
#define vPIN_VOLTAGE                  V7 // فولت الكهرباء
#define vPIN_CURRENT_USAGE            V8 // الحمل
#define vPIN_ACTIVE_POWER             V9
#define vPIN_ACTIVE_ENERGY            V10
#define vPIN_FREQUENCY                V11 //الهرتز
#define vPin_HighVoltageAC            V12 // الحد الاعلى للفولط 
#define vPin_LowVoltAC                V13 // القيمة الدنيا للفولت
#define vPin_HighCurrentAC            V14 //القيمة العليا للحمل
#define vPin_AutoInterrupter          V15 //الوضع التلقائي
#define OTA_HOSTNAME "PZEM-004v3"

BlynkTimer   UltraTimer;

WidgetLED LedRelay1(vPIN_LedRelay1);

SoftwareSerial pzem(D5,D6); // (RX,TX) connect to TX,RX of PZEM for NodeMCU  
ModbusMaster node;
double voltage_usage, current_usage, active_power, active_energy, frequency, power_factor, over_power_alarm; 
uint8_t result;  uint16_t data[6];




BLYNK_CONNECTED()                     // استعادة القيم من السيرفر بعد اعادة اقلاع الجهاز
{
  Blynk.sendInternal("rtc", "sync");
}

int StartH1;
int StartM1;
int StartS1;
int StopH1;
int StopM1;
int StopS1;


const int Relay1  = D4;
float Voltage = 50;
float LowVolt = 0;
float BlynkVoltage = 25;
bool AlertMsgLowVolt = 0;
float HighVoltAC = 300;
float LowVoltAC = 150;
float HighCurrentAC=100;
bool IsFirstRun   = 1;
bool MsgHighVolt  = 1;
bool MsgCurrent   = 1;
bool MsgLowVoltAC = 1;
bool AutoInterrupter=HIGH;

///////////////// BLYNK_WRITES ////////////////////////////



BLYNK_WRITE(vPIN_Relay1)                        // اداة التحكم في الريلي
{
  if (param.asInt() == 1)
  {
    digitalWrite(Relay1, HIGH);
    LedRelay1.on();
    Serial.println("Relay1 on");
       
  }
  else
  {
    digitalWrite(Relay1, LOW);
    LedRelay1.off();
    Serial.println("Relay1 off");
   
  }
}




BLYNK_WRITE(vPIN_Timer1) {
  setTime1(param);
}


BLYNK_WRITE(InternalPinRTC)                          
{
  const unsigned long DEFAULT_TIME = 1357041600; // Jan 1 2013
  unsigned long blynkTime = param.asLong();
  
  if (blynkTime >= DEFAULT_TIME)           
  {
   setTime(blynkTime);                     
  String Time = String(hour()) + ":" + minute() + ":" + second();
  String Date = String(day()) + "-" + month() + "-" + year();
  Serial.println(Time);
  Serial.println(Date);
  Serial.println(String("Day: ") + weekday()); 
  //Blynk.virtualWrite(vPIN_Time,Time);    
  }
}



/////////////////////// VOIDS /////////////////////////



void checkTime() {
  Blynk.sendInternal("rtc", "sync"); // Actualiza la hora con el servidor
}


void setTime1(BlynkParam param) {

  TimeInputParam t(param);

  if (t.hasStartTime()) {
    Serial.println(String("Hora de inicio: ") +
    t.getStartHour() + ":" +
    t.getStartMinute() + ":" +
    t.getStartSecond());
    StartH1 = t.getStartHour() ;
    StartM1 = t.getStartMinute() ;
    StartS1 = t.getStartSecond() ;
    Serial.println("StartH1: "+String(StartH1));
    Serial.println("StartM1: "+String(StartM1));
    Serial.println("StartS1: "+String(StartS1));
  }

  if (t.hasStopTime()) {
    Serial.println(String("Hora de finalización: ") +
    t.getStopHour() + ":" +
    t.getStopMinute() + ":" +
    t.getStopSecond());
    StopH1 = t.getStopHour() ;
    StopM1 = t.getStopMinute() ;
    StopS1 = t.getStopSecond();
    Serial.println("StopH1: "+String(StopH1));
    Serial.println("StopM1: "+String(StopM1));
    Serial.println("StopS1: "+String(StopS1));
  }

  for (int i = 1; i <= 7; i++) {
    if (t.isWeekdaySelected(i)) {
      Serial.println(String("Day ") + i + " is selected");
    }
  }
}



void UPTIME(){
 

   uptime::calculateUptime();
   Serial.println(" "+String(uptime::getDays())+" days "+String(uptime::getHours())+":"+String(uptime::getMinutes())+":"+String(uptime::getSeconds()));
   Serial.print("\n");
   Blynk.virtualWrite(vPIN_UPTIME," "+String(uptime::getDays())+" days "+String(uptime::getHours())+":"+String(uptime::getMinutes())+":"+String(uptime::getSeconds()));
}



void Timr1()                                         // تابع المؤقت رقم 1
{
 

    if ((hour() == StartH1) and (minute() == StartM1) and (second() > StartS1))
    {
      digitalWrite(Relay1, HIGH );
      Serial.println("Relay on");
      Blynk.virtualWrite(V1,1);
      LedRelay1.on();
          
    }


    if ((hour() == StopH1) and (minute() == StopM1) and (second() > StopS1))
    {
      
      digitalWrite(Relay1, LOW );
      Serial.println("Relay off ");
      Blynk.virtualWrite(V1,0);
      LedRelay1.off();
         
    }
    
  }


  void pzemdata(){

    result = node.readInputRegisters(0x0000, 10);   
    if (result == node.ku8MBSuccess)  
    {
    voltage_usage      = (node.getResponseBuffer(0x00) / 10.0f);
    current_usage      = (node.getResponseBuffer(0x01) / 1000.000f);
    
    if (AutoInterrupter==HIGH)  
    {
        if ((voltage_usage > HighVoltAC)and(MsgHighVolt==1)) 
        {
        //  Blynk.notify("ارتفع فولت الكهرباء اكثر من القيمة المحددة");
         // Blynk.virtualWrite(vPIN_LogTerminal,"ارتفع فولت الكهرباء اكثر من القيمة المحددة الوقت:  " +String(hour()) + ":" + minute() + ":" + second()+"  " +String (day()) + "-" + month() + "-" + year() );
          MsgHighVolt=0;
        }
        if ((voltage_usage < HighVoltAC)and(MsgHighVolt==0))
       {    
       MsgHighVolt=1;
      // Blynk.notify("عودة فولت الكهرباء للحد الطبيعي");
       //Blynk.virtualWrite(vPIN_LogTerminal,"عودة فولت الكهرباء للحد الطبيعي الوقت:  " +String(hour()) + ":" + minute() + ":" + second()+"  " +String (day()) + "-" + month() + "-" + year() );
         
       }
        
        if ((current_usage > HighCurrentAC)and(MsgCurrent==1)) 
        {
         // Blynk.notify("تجاوز الحمل القيمة المحددة ");  
          //Blynk.virtualWrite(vPIN_LogTerminal,"تجاوز الحمل القيمة المحددة  الوقت:  " +String(hour()) + ":" + minute() + ":" + second()+"  " +String (day()) + "-" + month() + "-" + year() );
          MsgCurrent=0;
        }

        if ((current_usage < HighCurrentAC)and(MsgCurrent==0))
       {    
       MsgCurrent=1;
      // Blynk.notify("عودة الحمل للحد الطبيعي");
       //Blynk.virtualWrite(vPIN_LogTerminal,"عودة الحمل للحد الطبيعي الوقت:  " +String(hour()) + ":" + minute() + ":" + second()+"  " +String (day()) + "-" + month() + "-" + year() );
         
       }
  
        if ((voltage_usage < LowVoltAC)and(MsgLowVoltAC==1))
        {
        //  Blynk.notify("انخفض فولط المولدة أكثر من القيمة المحددة");
        //  Blynk.virtualWrite(vPIN_LogTerminal,"انخفض فولط المولدة أكثر من القيمة المحددة  الوقت:  " +String(hour()) + ":" + minute() + ":" + second()+"  " +String (day()) + "-" + month() + "-" + year() );
          MsgLowVoltAC=0;
        } 
        if ((voltage_usage > LowVoltAC)and(MsgLowVoltAC==0))
       {    
       MsgLowVoltAC=1;
      // Blynk.notify("عودة فولت الكهرباء للحد الطبيعي");
      // Blynk.virtualWrite(vPIN_LogTerminal,"عودة فولت الكهرباء للحد الطبيعي الوقت:  " +String(hour()) + ":" + minute() + ":" + second()+"  " +String (day()) + "-" + month() + "-" + year() );
         
       }               
      }
      
    //active_power       = (node.getResponseBuffer(0x03) / 10.0f);
    //active_energy      = (node.getResponseBuffer(0x05) / 1000.0f);
    frequency          = (node.getResponseBuffer(0x07) / 10.0f);

    }

  Serial.print("VOLTAGE:           ");   Serial.println(voltage_usage);   // V
  Serial.print("CURRENT_USAGE:     ");   Serial.println(current_usage, 3);  //  A
  //Serial.print("ACTIVE_POWER:      ");   Serial.println(active_power);   //  W
  //Serial.print("ACTIVE_ENERGY:     ");   Serial.println(active_energy, 3);  // kWh
  Serial.print("FREQUENCY:         ");   Serial.println(frequency);    // Hz
  Serial.println("====================================================");
  
  Blynk.virtualWrite(vPIN_VOLTAGE, voltage_usage);
  Blynk.virtualWrite(vPIN_CURRENT_USAGE, current_usage);
  //Blynk.virtualWrite(vPIN_ACTIVE_POWER,active_power);
  //Blynk.virtualWrite(vPIN_ACTIVE_ENERGY, active_energy);
  Blynk.virtualWrite(vPIN_FREQUENCY, frequency);
}


void setup()
{
  BlynkEdgent.begin();
  Serial.begin(250000); 
  pinMode(Relay1,OUTPUT);
  UltraTimer.setInterval(1000L, checkTime);
  UltraTimer.setInterval(5000L, Timr1);
  UltraTimer.setInterval(1000L, UPTIME);
  UltraTimer.setInterval(1000L, pzemdata);
  Serial.println("Start serial");
  pzem.begin(9600);
  Serial.println("Start PZEM serial");
  node.begin(1, pzem);
  Serial.println("Start PZEM"); 
  
}


void loop()
{
  
 BlynkEdgent.run();
 UltraTimer.run();

}

I will give it a try as soon as possible, and I will let you know if I figure it out.

Greetings.

Try It for Algorithm Sistem :slight_smile:
‘’’
[Unformatted code removed by moderator]

It’s a good idea, thank you, I’ll give it a try

No, it’s a bad idea that uses four times more memory than necessary.

Pete.

@Bisri please edit your post, using the pencil icon at the bottom, and add triple backticks at the beginning and end of your code so that it displays correctly
Triple backticks look like this:
```

Pete.

I Think Can Using More Than Sistem Delay Interval(4 Or 5), But With Using Same Delay Interval,

1 Sistem Timing For 1 Function Or Methode Algorithm,

When Using 2 Sistem Timing Interval, But Using Different Delay Or Not Compability(Count Or Value Timing 1 And Timing 2)Can Make Project Crash,