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).