ESP32 Stuck at Connecting to ****

Hello I have seen other people having similar issue as me, but I couldn’t implement their solution to my sketch and make it work.

Sometimes when I power up my ESP32 it gets stuck at “Connecting to ****” and I have to press the reset pin and at second try it will connect.

I want to implement a timeout function so if it gets stuck at connecting there will be a timeout after 30 seconds which set digital pin 9 as output, because it causes the ESP32 to reboot and try again.

/*************************************************************

  This is a simple demo of sending and receiving some data.
  Be sure to check out other examples!
 *************************************************************/

/* Fill-in information from Blynk Device Info here */
#define BLYNK_TEMPLATE_ID           "****"
#define BLYNK_TEMPLATE_NAME         "****"
#define BLYNK_AUTH_TOKEN            "****"

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

#define MaskinNumber V85

#include <WiFi.h>
#include <WiFiClient.h>
#include <BlynkSimpleEsp32.h>

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

BlynkTimer timer;

#define trButton 19      // training/reset button (being eliminated/modified)
#define processInput 19  // needs the sensor from the process
#define faultLED 3
#define readyLED 4
#define runningLED 5

bool needCalibration;  // set this to force a calibration run

enum bar { IDLE = 0,
           MEASURE,
           CHECK,
           IFAULT,
           NFAULT,
};

// Declaring a global variabl for sensor data
int sensorVal = 0;

//What to do when successfully connected to Blynk
BLYNK_CONNECTED() {

  //Makes sure that V1 is in sync in case of lost connection.
  Blynk.syncVirtual(V2);

  //Message that shows up in Serial Monitor.
  BLYNK_LOG("Connected to Blynk 🙌");

  //A LED lights up when connected to server.
  digitalWrite(21, HIGH);
}

//What to do when not connected to Blynk
BLYNK_DISCONNECTED() {

  //Message that shows up in Serial Monitor.
  BLYNK_LOG("Blynk disconnected");
}


//Virtual pin 1 in datastream
BLYNK_WRITE(V2) {

  // This monitors if the virtual pin value changes, then followed by the action.
  // In this case "if V1 value is ==1 then digitalWrite 26, HIGH else LOW"
  if (param.asInt() == 1) {

    pinMode(9, OUTPUT);

    // execute this code if the switch widget is now ON (Remember to set the on value to 1)
    digitalWrite(26, HIGH);  // Set digital pin 2 HIGH
  } else {
    // execute this code if the switch widget is now OFF(Remember to set the off value to 0)
    digitalWrite(26, LOW);  // Set digital pin 2 LOW
  }
}

//This is for preventing dataoverflow so it only sends the updated value with certain intervals.
//The update interval is defined by timer.setInterval in the void setup section.
void myTimerEvent() {
  // You can send any value at any time.
  // Please don't send more that 10 values per second.

  //send among of seconds that has past to virtual pin V0
 // Blynk.virtualWrite(V0, millis() / 1000);

  // This function describes what will happen with each timer tick
  // e.g. writing sensor value to datastream V2
  Blynk.virtualWrite(MaskinNumber, sensorVal);
  Serial.println(sensorVal);
}
void setup()
{

    // Define LED pins
  pinMode(readyLED, OUTPUT);
  pinMode(runningLED, OUTPUT);
  pinMode(faultLED, OUTPUT);
  pinMode(trButton, INPUT_PULLUP);
  pinMode(processInput, INPUT_PULLUP);
  pinMode(26, OUTPUT);
  pinMode(21, OUTPUT);

  needCalibration = true;

  // Debug console
  Serial.begin(115200);
  Serial.println();
  // Give Serial Monitor some time to connect
  delay(3000);

  pinMode(12, OUTPUT);

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


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

unsigned int counter;
unsigned char state = IDLE;  // does. is.
unsigned long now;
unsigned long timeLimit;
unsigned long timer1;

unsigned long previousMillis = 0; // Gemmer det tidspunkt, hvor LED'en sidst blev opdateret
const long interval = 1000; // Blink interval (i millisekunder)


void loop()
{

  // runs BlynkTimer
  timer.run();

  // Runs all Blynk stuff
  Blynk.run();

 unsigned long currentMillis = millis(); // Hent antallet af millisekunder siden Arduino startede


    now = millis();

  bool controlX = digitalRead(processInput) == HIGH;
  bool buttonState = digitalRead(trButton) == HIGH;

  static bool lastButtonState;
  static bool buttonPress;

  if (buttonState != lastButtonState) {
    if (buttonState) {
      buttonPress = !buttonPress;
    }
    lastButtonState = buttonState;
  }

  switch (state) {
    case IDLE:
      sensorVal = 5;
      digitalWrite(readyLED, HIGH);
      digitalWrite(runningLED, LOW);
      if (controlX) {
        timer1 = now;
        //      if (buttonPress || needCalibration) {
        if (needCalibration) {
          state = MEASURE;
          Serial.print("training for time\n");
          buttonPress = false;
          needCalibration = false;
        } else {
          state = CHECK;
          Serial.print("X up. monitoring time\n");
        }
      }
      break;

    case CHECK:
      sensorVal = 10;
      digitalWrite(readyLED, LOW);
      digitalWrite(runningLED, HIGH);
      if (now - timer1 > timeLimit) {
        state = IFAULT;
        break;
      }
      if (!controlX) {
        Serial.print("X down     made it by ");
        Serial.println(timeLimit - (now - timer1));
        state = IDLE;
      }
      break;

    case MEASURE:
      sensorVal = 10;
      digitalWrite(readyLED, LOW);
      digitalWrite(runningLED, HIGH);
      if (!controlX) {
        timeLimit = now - timer1;
        timeLimit += timeLimit / 10;  // comfort margarine 10 percent here
        Serial.print("X down    new period = ");
        Serial.println(timeLimit);

        state = IDLE;
      }
      break;

    case IFAULT:
      Serial.print(" initialize fault mechanism");
      state = NFAULT;
      Serial.print(" / perpetuate fault mechanism\n");
      Blynk.logEvent("maskinstop");
      sensorVal = 1;
      digitalWrite(faultLED, HIGH);
      buttonPress = false;  // eat any stray button presses
      break;

    case NFAULT:
      digitalWrite(readyLED, LOW);
      digitalWrite(runningLED, LOW);
      digitalWrite(faultLED, millis() & 512 ? HIGH : LOW);

if (currentMillis - previousMillis >= interval) { // Tjek om det er tid til at tænde/slukke LED'en
    previousMillis = currentMillis; // Gem det aktuelle tidspunkt
 //   Serial.println(previousMillis);

      if (buttonPress) {
        Serial.print("sytem to IDLE\n");
        digitalWrite(faultLED, LOW);
        sensorVal = 1;
        buttonPress = false;
        needCalibration = true;
        state = IDLE;
      }
}
      break;
  }
}

Stop using Blynk.begin because it’s a blocking command.

Instead, manage your own WiFi connection then use Blynk.config and Blynk.connect (with an optional timeout).

Search the forum for “Blynk.config()” and you’ll see some examples.

Pete.

Yeah I see it mentioned a couple of times, but is the blynk.begin() the only line of code I should remove from my sketch or is there more to avoid conflicts?

I found this example:


void setup(){
//  Blynk.begin(auth, ssid, pass); don't use this
  WiFi.begin(ssid, pass);
  while ( WiFi.status() != WL_CONNECTED ) {
    delay ( 500 );
    Serial.print ( "." );
  }
  Blynk.config(auth);
}

How do I make the timeout function?

I know it’s something like:


If (?????) {
digitalPin(9, OUTPUT);
}

Timeout is an option parameter in Blynk.connect().
Do a bit of searching and you’ll find some examples.

Pete.

Blynk,Connect is a painful function and if you don’t use it carefully your code will stuck continuosly…

There is no need to do a HW reset with Pin 9 , you can set a timer or a counter then you do a soft restart toreboot the ESP.

Also when blynk is disconnected it has no sense to send to the terminal anything since it will not be sent.

I use this working code after too much struggeling with the Blynk.connect…

First in the Setup you execute the blynk.connect specifiying atimeout of 2 sec, if not specificied the code will be blocked for 30Sec if blynk.connect fails.

then every 10 Sec you call the Blynk check to set a variable Blynconnected if the connect is succesiful.

If not, you start another timers for 2 minutes, if blyckconnected is false for 2 minutes then you restart the esp.

in Setup you call this function only once after you have already checked that wifi is connected…

bool blynk::init() 
{
   _blynkIsConnected = false;   
  timer.setInterval(LiveUpdateInterval, SendLiveLed);// run some function at intervals per LiveUpdateInterval
  timer.setInterval(blynkIntervalInterval, checkBlynk);   // check connection to server per blynkIntervalInterval
  
  if(_wifiIsConnected)
    {
     Blynk.config(BLYNK_AUTH_TOKEN, BLYNK_SERVER);
     Blynk.connect(BlynkServerTimeout);
     _blynkIsConnected =Blynk.connected();
     DEBUG_PRINT("BLYNK: ");DEBUG_PRINTLN( _blynkIsConnected ? F("Connected") : F("Not Connected"));
     blynkAtiveTimer     = millis();
     blynkActive = false;
     ledInit();     
     terminal.clear();
  }
  return _blynkIsConnected;
}

Then in the blynkCheck call with the timer interval of 10 sec you do the following, the BlynkServerTimeout is 5 sec, or you can use connect with the timeout as before:

void checkBlynk() {
  if (wifiMulti.run(WiFi_TIMEOUT) == WL_CONNECTED)  
  {
    unsigned long startConnecting = millis(); 
    _blynkIsConnected = true;   
    _wifiIsConnected = true;

    while(!Blynk.connected()){
      Serial.println("Blynk Disconnected");
       Blynk.connect(BlynkServerTimeout);  
       if(millis() > startConnecting + BlynkServerTimeout){
        _blynkIsConnected = false;
        Serial.println("Unable to connect to server. ");
        break;
      }
    }
  }
  else 
    {
      _wifiIsConnected = false;
      _blynkIsConnected = false; 
    } 
  DEBUG_PRINT("WIFI: ");DEBUG_PRINTLN( _wifiIsConnected ? F("Connected") : F("Not Connected"));
  DEBUG_PRINT("BLYNK: ");DEBUG_PRINTLN( _blynkIsConnected ? F("Connected") : F("Not Connected"));  
  Serial.printf("\tChecking again Blynk connected in %is.\n", blynkIntervalInterval / 1000);
  Serial.println(".");
  blynkConnected = _blynkIsConnected;
}

In the main loop you pull continuosly the Blynkconnected variable , if true you do you code if not not you set another variable InternetLoss.

You continue to do the Blynck check every 10 sec, if for any reason blynckconnected becomes true again then reset the timer, otherwise if it continue to be false and a timer of 2 minutes passes the you do the ESP.restart.

Hope this will help.

I’m confused by this statement, but I guess that the issues you’re describing are caused by your use of Blynk.run() without first testing if Blynk.connected() is true.

It’s not actually necessary to use Blynk.connect() at all, because when you use Blynk.config(BLYNK_AUTH_TOKEN) each time Blynk.run() executes it will attempt to connect to the Blynk server using te default timeout of around 18 seconds.
This means that when you’re using Blynk.config(BLYNK_AUTH_TOKEN) you have to do a Blynk.connected() test before executing ‘Blynk.run()` like this…

If (Blynk.connected())
{
   Blynk.run();
 }

If you don’t do this then you’ll go through the cycle of attempting to connect, waiting for the timeout period, then attempting to connect again if there is no internet connection or if the Blynk server isn’t reachable.

Using Blynk.connect() allows you to specify a timeout period in milliseconds, but there’s a limit to how low you can go with this timeout. In my experience somewhere around 5000ms (which gives an actual timeout period of around 6.5 seconds) works well, but it does depend on the latency of your internet connection.

It’s also worth knowing that Blynk.connected() will continue to return true after the Blynk connection is dropped, until the Blynk heartbeat period has passed and a failed ping occurs. The default timeout is around 45 seconds, so if it’s important to you that you’re aware that the server disconnection has occurred ASAP then you might want to specify a different timeout.

The subject is discussed in more detail in this topic…

Pete.

Who said that I execute blynk.run before executing the blynk.connect?

if you do as you said

If (Blynk.connected())
{
   Blynk.run();
 }

in the main loop you will exhaust the Code while continuosly pulling the blynk.connect I think you don’t mean it.

This is my main Loop, I use the vairable Blynckconnected comming from the interrupt timer every 10 sec to check Blynk connected and not using blynk connected itself in the main loop…

    
       if ( blynkConnected )
          {
            myBlynk.blynkRun();
            queuValidData = (xQueueReceive(g_event_queue_handle, &queuDataID, 5 / portTICK_RATE_MS) == pdPASS);
            if(queuValidData) 
                  {
                  myBlynk.getData ();
                  if (hmi == BLYNK)    
                    {
                     queuData = myBlynk.blynkData; 
                     processBlynkQueu(); 
                    }
                  }
            InternetLoss = false;   resetNetgeerAfterInternetLossTimer = millis();
            netGeerReset = false;   restartAfterResetNG = millis();
                 }

       else if( !InternetLoss && !blynkConnected)  
          {
            DEBUG_PRINTLN("Blynk Disconnected , Internet Loss!!!");
            InternetLoss = true; 
            resetNetgeerAfterInternetLossTimer = millis();
            blynkEvent=false; 
            myBlynk.sendToBlynk = false;
            myBlynk.sendToBlynkLeds = false;
          }
       myBlynk.blynkRunTimer();

Again I confirm that blybk.connect is a painful function that must be used carefuly…

I think you’re getting confused between the Blynk.connected() logical test and the optional Blynk.connect() command.

If you take a look at the code and resulting serial output that I linked to, you’ll see that my approach works perfectly and allows the user to tweak the settings to minimise the disruption caused by attempting to re-connect to WiFi and Blynk to suit their needs.

Pete.

I will check your code on my device and let you know… I will try to reproduce with blynk disconnection by giving a wrong token and see what will happen…

Regards

Probably better to test a real-life situation like I did in the tests I documented in that topic.

Pete.

Hi Pete,
I tested your code on ESP32, I’ve used my Mobile Phone as Wifi Access but I turned off the 4G data… Here is the result… There is 25 Sec during which the code is blocked … here: Am I missing something?

18:13:55.286 → Blynk connection attempt failed - not connected
18:14:20.290 → Checking connections… WiFi Okay, Blynk not connected

This is a complete Log…

18:13:50.285 → Checking connections… WiFi Okay, Blynk not connected
18:13:50.333 → Attempting to connect to Blynk…
18:13:50.333 → [67190] Connecting to blynk.cloud:80
18:13:50.333 → [67201] Connecting to blynk.cloud:8080
18:13:55.286 → Blynk.connect() attempt ended
18:13:55.286 → Blynk connection attempt failed - not connected
18:14:20.290 → Checking connections… WiFi Okay, Blynk not connected
18:14:20.290 → Attempting to connect to Blynk…
18:14:20.290 → [97190] Connecting to blynk.cloud:80
18:14:20.323 → [97211] Connecting to blynk.cloud:8080
18:14:25.307 → Blynk.connect() attempt ended
18:14:25.307 → Blynk connection attempt failed - not connected
18:14:50.303 → Checking connections… WiFi Okay, Blynk not connected

Found it, it is the interval of Blynk check connection timer call…
In this case, your code is very simple and working fine… :grinning:

Thanks