Code isn't working without connected Blynk

Hi,

Did you ever get your arduino Sketch to run when Blynk is not connected to the internet?

No ,i don’t get.
I was is search of this but know i’m working on different project.

It’s a little more complicated than it first seems but the 2 basic steps are:

'1. Bail out of the while loop that you MUST have in setup()

int mytimeout = millis() / 1000;
while (Blynk.connect() == false) { 
  if((millis() / 1000) > mytimeout + 8){  // try for less than 9 seconds
    break;
  }
} 

'2. Only process blynk.run() in the main loop() when you are connected.

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

Further requirements are SimpleTimer to check if router / server is now running so a connection to Blynk can be made etc.

HTH

2 Likes

Hi, I’m new to blynk and not that good with codes…
I copy/paste your codes and added the libraries (i got them
from the blynk ethernet sample)
#define BLYNK_PRINT Serial
#include <SPI.h>
#include <Ethernet.h>
#include <BlynkSimpleEthernet.h>

I’m using W5100
I did the changes to the blynk library
Getting the error:
‘beep’ was not declared in this scope

Am I missing any libraries or something?
Any help would be great! (Emphasis on “im no good at coding”) :slight_smile:

beep() is a standard Arduino function so I don’t know why you have a problem with it.

Just comment the line out for now and proceed with out.

hello!

beep() is just a function i declared somewhere else, in my sketch, it is used to generate buzzer sounds, if an event occurs.

as costas said, you can safely delete them, no problem. otherwise, the code should work. i’m using this in a home automation project, the arduino have to run continuously, even when there is no internet connection, because the physical light switches are wired to the arduino.

Got it, i commented out all the beep, now I got a new error:
‘updateBlynk’ was not declared in this scope

really sorry for stupid questions. I’m just totally bad at this, but your code is the exact thing I need for my project. :grin:

I think I should not comment it out (looks important i guess), but when I did (just for the sake of uploading) the device was not able to connect (but it kept on trying though)
any thoughts? (I can connect fine when i use the default sample files (ethernet & usb)

your code is missing some { or } or these are in the wrong spot/s.

ok, please copy paste your sketch here, without modifying anything (remove token of course :slight_smile: )

Hi again guys, the project was abandoned for some time, but for the couple of the last days I’ve back to the code and this thread and came with this code (NodeMCU, ESP8266):

#define BLYNK_DEBUG // Optional, this enables lots of prints
#define BLYNK_PRINT Serial
#include <ESP8266WiFi.h>
#include <BlynkSimpleEsp8266.h>
#include <SimpleTimer.h>

const char* espHostname   = "ESP_HOSTNAME";
const char* ssid          = "AP_NAME";
const char* password      = "AP_PASSWORD";
const char* host          = "BLYNK_SERVER_IP";
const char  auth[]        = "BLYNK_AUTH";
const int   checkInterval = 30000;

const int   butPin       = D3;
const int   ledPin       = D4;
const int   relPin       = BUILTIN_LED;
int   x                  = 0; // start as OFF
int   butState;
int   oldButState;

SimpleTimer timer;

void blynkCheck() {
  if (WiFi.status() == 3) {
    if (!Blynk.connected()) {
      Serial.println("WiFi OK, trying to connect to the Blynk server...");
      Blynk.connect();
    }
  }
  if (WiFi.status() == 1) {
    Serial.println("No WiFi connection, offline mode.");
  }
}

void setup()
{
  pinMode(butPin, INPUT);     //Button for turning on the light
  pinMode(ledPin, OUTPUT);    //LED on when relay is off, and backwards
  pinMode(relPin, OUTPUT);    //Relay
  digitalWrite(relPin, HIGH);
  digitalWrite(ledPin, LOW);
  Serial.begin(9600);
  WiFi.hostname(espHostname);
  WiFi.begin(ssid, password);
  Blynk.config(auth, host);
  timer.setInterval(checkInterval, blynkCheck);
}

void loop()
{
  timer.run();
  if (Blynk.connected()) Blynk.run();
  butState = digitalRead(butPin);
  if (butState == HIGH && oldButState == LOW) {
    if (x == 1) { //ON
      digitalWrite(relPin, LOW);
      digitalWrite(ledPin, HIGH);
      Blynk.virtualWrite(V0, HIGH);
      x = 0;
    }
    else { //OFF
      digitalWrite(relPin, HIGH);
      digitalWrite(ledPin, LOW);
      Blynk.virtualWrite(V0, LOW);
      x = 1;
    }
  }
  oldButState = butState;
}

BLYNK_WRITE(V0)
{
  int val = param.asInt();
  digitalWrite(ledPin, val);
  digitalWrite(relPin, !val);
  x = !x;
}

BLYNK_CONNECTED()
{
  Serial.println("Reconnected, syncing with cloud.");
  Blynk.syncAll();
}

So that’s the code “as is” for my project (controllable light switch for the room). It have controllable interval of checking the connection here:

const int   checkInterval = 30000;

After booting it works for 30000ms (30 seconds) with offline mode, then trying to connect.
If WiFi connected and Internet is ok, it works well, with reconnects to the blynk server every 30 seconds.
If WiFi is available, but have no internet — it stucks for ~10 seconds then working offline, till another timer call.
If no WiFi connection — it doesn’t try to connect to the Blynk, just logging to the console and goes offline.

The default 30 seconds interval is nice for debug, but for real-world working consider setting it for 300000 or 600000 (5-10 minutes).

1 Like

hello sir i tried ur code it works good when its connected .
when I unpluge the internet cable the physical buttons works very good no freeze.
but when I reconnect the internet cable the blynk wont reconnect again , can u plz guide me how to do that .
this is my code

#define BLYNK_PRINT Serial    // Comment this out to disable prints and save space
#include <ESP8266WiFi.h>
#include <BlynkSimpleEsp8266.h>

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

int switchPin = D1;
int ledPin = D2;
boolean lastButton = LOW;
boolean currentButton = LOW;
boolean ledOn = false;

void setup()
{
  Serial.begin(9600);
  Blynk.begin(auth, ssid, pass);
  pinMode(switchPin, INPUT);
  pinMode(ledPin, OUTPUT);

int mytimeout = millis() / 1000;
while (Blynk.connect() == false) { 
  if((millis() / 1000) > mytimeout + 8){  // try for less than 9 seconds
    break;
  }
}

  
}

boolean debounce(boolean last)
{
  boolean current = digitalRead(switchPin);
  if (last != current)
  {
    delay(5);
    current = digitalRead(switchPin);
  }
  return current;
}

BLYNK_WRITE(V10) //Function to test status from BLYNK widget to PHOTON
{
int state = param.asInt();
if (state ==1)
{
 ledOn = !ledOn;
}
else if (state ==0)
{
digitalWrite(ledPin,ledOn);
}
}
void loop()
{
  currentButton = debounce(lastButton);
  if (lastButton == LOW && currentButton == HIGH)
  {
    ledOn = !ledOn;
  }
  lastButton = currentButton;
  
  digitalWrite(ledPin, ledOn);
  
if(Blynk.connected()){
    Blynk.run();
  }
  
//Blynk.run();
}

@dananmo you need this bit

Study the many SimpleTimer examples and then decide how often you want to check if an internet connection is available. The function you then need to call from SimpleTimer would be something like this:

void reconnect(){
  int mytimeout = millis() / 1000;
  while (Blynk.connect() == false) { 
    if((millis() / 1000) > mytimeout + 8){  // try for less than 9 seconds
      break;
    }
  }
}

thank u very much sir u were very helpful thanks again now its working good thanks

Ηι @Costas!! please I need your advise…
When im using
Blynk.config(auth);
Blynk.connect(3333);

the result on serial monitor is always this:
[0]
___ __ __
/ _ )/ /_ _____ / /__
/ _ / / // / _ / '/
/
//_, /////_
/
__/ v0.4.4 on Arduino Mega

[5001] Connecting to blynk-cloud.com:8442
[10002] Connecting to blynk-cloud.com:8442
[15003] Connecting to blynk-cloud.com:8442
[20004] Connecting to blynk-cloud.com:8442
[25005] Connecting to blynk-cloud.com:8442
[30006] Connecting to blynk-cloud.com:8442
[35007] Connecting to blynk-cloud.com:8442

why i can not connect;;should I do and something else;;Thanks!!

The sketch was for ESP. I don’t think Blynk has a config() for Arduino’s.

Oh? That might explain my own issues when I was playing around with it… something I didn’t pursue due to general lack of need.

@Gunner with ESP’s you can make the internet connection prior to connecting to Blynk whereas the internet connection is all built in to the blocking Blynk.begin() for Arduino’s.

For Arduino’s you would need to build in a manual timeout to circumvent the blocking routine and ensure loop() contains something like this:

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

and SimpleTimer to check and reconnect etc.

I’m a little surprised that config() and connect() actually compile on an Arduino.

The other point is that I was under the impression that Blynk.connect(3333); tried for 10s based on a multiplier of 3 in the library. 3 does appear in the library as part of the connection / timeout parameters but I’m assured 3333 is simply 3333ms not 9999ms.

@Spyrosgreece could you change (3333) to () which means the default 10s timeout.

As there is no indication of ESP exclusivity in the DOC’s (which honestly doesn’t guarantee anything :wink: ) I figured it was fully compatible… and I just confirmed that Blynk.config(Serial, auth); not only compiled, but runs fine… however I will have to go back and hook up something to the Arduino to allow “off server” functionality and test again with Blynk.disconnect() & Blynk.connect() on Arduino.

1 Like

I can confirm this works just fine for me on MEGA2560.

byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
 if (Ethernet.begin(mac) == 0) {
       Serial.println("Failed to configure Ethernet using DHCP");
       // give the Ethernet shield a second to initialize:
     }
     delay(1000);
     Serial.println("connecting using Ethernet...");
   
     
        Blynk.config(auth_local_server, "192.168.0.251", 8442); 

and I use this logic to check reconnection (note my code is design to allow me to use either ARDUINO MEGA2560 or ESP8266

//===== RE CONNECT IF BLYNK NOT CONNECTED ===== 
// (called every xxx seconds using SimpleTimer)

void reconnectBlynk() {
if (!Blynk.connected()) {
    number_of_times_blynk_lost_connection++;
    
    #ifdef USE_MEGA2650 
      wdt_reset();  // give it as much time as possible to re-check ethernet
    #endif
    
     #ifdef USE_ESP8266
      ESP.wdtFeed();
    #endif
    
    #ifdef USE_MEGA2560
     int return_value = Ethernet.maintain();
    #endif
    
    #ifdef USE_ESP8266
      if (WiFi.status() != WL_CONNECTED)
       {
          WiFi.begin(ssid, pass);                           // Connect to WiFi network
          Serial.println(F("Waiting to connect to Wifi:"));
          long waittime = millis()+ 7000;                  // 7 seconds wait time
          while (WiFi.status() != WL_CONNECTED) {           // Wait for board to connect to WiFi network
             delay(500);                                    
             Serial.print(F("."));  
             if (millis() > waittime)
              { break; }                                   
          }                                                 
           Serial.println(F(" "));  
      }
    #endif

    #ifdef USE_MEGA2560
     #ifdef DISPLAY_DEBUG_ETHERNET
       switch (return_value) {
       case 0 :
        Serial.println (F("0 returned from Ethernet.maintain - i.e. nothing happened"));
        break;
      case 1 :
        Serial.println (F("1 returned from Ethernet.maintain - i.e. renew failed"));
        break;
      case 2 :
        Serial.println (F("2 returned from Ethernet.maintain - i.e. renew success"));
        break;
      case 3 :
        Serial.println (F("3 returned from Ethernet.maintain - i.e. rebind fail"));
        break;
      case 4 :
        Serial.println (F("4 returned from Ethernet.maintain - i.e. rebing success"));
        break;           
    }
     #endif
    #endif
    
    #ifdef USE_MEGA2560
          wdt_disable(); // disable wdt otherwise it will trigger !
     #endif  

      #ifdef USE_ESP8266
          ESP.wdtDisable();
      #endif
      
 
    if(Blynk.connect(3333)) {
 
     
      bool isFirstConnect = true; // assume this is first time we connected to Blynk again :-) i.e. ensure BLYNK_CONNECTED()to executed again, now that we re-connected
      number_of_times_blynk_lost_connection++;
   
       #ifdef USE_MEGA2560
      	wdt_enable(WDTO_8S); // re-enable wdt
         BLYNK_LOG("Essendon MEGA Reconnected to Blynk");
      #endif
     
      #ifdef USE_ESP8266
       ESP.wdtEnable(WDTO_8S);    // enable Watch Dog Time WDT for 8s
         BLYNK_LOG("Essendon Wemos Reconnected to Blynk");
      #endif
    } 
    else {
       
        #ifdef USE_MEGA2560
        wdt_enable(WDTO_8S); // re-enable wdt
        BLYNK_LOG("Essendon Home SCR MEGA Not reconnected to Blynk");
       #endif
    
       #ifdef USE_ESP8266
        ESP.wdtEnable(WDTO_8S);    // enable Watch Dog Time WDT for 8s   // 
        BLYNK_LOG("Reconnected to Blynk");
      #endif
    }
  }
}