Blynk.run() not reconnecting to server

So, i have this in my loop on an esp8266:

void loop() {
  unsigned long startTime = micros();

  Blynk.run();

  for (byte i = 0; i<64 && !Blynk.connected(); i++){
    Blynk.run();
  }

  if ( wakeups % 30 == 0 ) {
    chirpOn();
    delay(50);
    readVal();
    chirpOff();
    for (byte j = 0; j < 16; j++) {
      Blynk.run();
    }
  }

  wakeups++;

  delay(10000 - (micros() - startTime)/1000);
}

I know it looks ugly with the delays and all, but it’s on a battery+solar cell so i’m actually using them to put the board into light sleep.

What happens is that at the first wifi disconnection, Blynk doesn’t seem to be reconnecting to the server, even though the wireless connection is restored (i can ping the board from a computer on the same network).

Do i ned something more than just Blynk.run()?

Just Blynk.run() without all that other stuff in loop().

What do you think the for loop and if statement does?

1 Like

The first for loop would hopefully restore a lost connection before anything else runs.

The if runs once every 30 loops.
Since the delay (sleep) at the end makes sure each loop lasts 10 seconds, every 5 minutes that if statement is true-> it turns on a moisture sensor and reads it.

The for nested in the if is just to make sure the data gets sent immediately.

Is there any reason you are using your light sleep code rather than the official deepSleep()?

a) light sleep doesn’t waste time and energy reconnecting to wifi, especially relevant with poor reception
b) because of reason a, i’m also less likely to have blackout periods in the history data
c) it’s just as official, just less explored :stuck_out_tongue:

Anyhow, i found my mistake, and it was rather dumb.

This is my sleep time:
delay(10000 - (micros() - startTime)/1000);

When (micros() - startTime)/1000 is greater than 10000 (the rest of the loop took more than 10 seconds) the subtraction causes an overflow and i get a very long sleep time.
If my maths isn’t as bogus as it has proven to be, for a 32 bit integer that’s roughly 50 days of delay!

Thanks anyway for trying to help :slight_smile:

That is why it’s “simpler” to use SimpleTimer, aka BlynkTimer.

It’s simpler, but it would mean that i’d have to renounce to timing precision for energy saving or vice-versa :wink: