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

Blynk connected but virtualWrite and BLYNK_WRITE is not working

Hi!
I’m looking for help. I made project to control temperature in some remote house, run heater when necessary, send data to control it and adjust it remotely. Because not reliable WiFi I used library ESP8266WiFiMulti.h to connect to all available network&Blynk by timer (to prevent code stack).

Result is following: WiFi is connecting, Blynk is connecting BUT data is not posting and not getting back.

Please advice whats is wrong?
PS - this is one of my first code and I far not good in coding so ready to constructive critics

MY CODE:

#include <ESP8266WiFi.h>
#include <ESP8266WiFiMulti.h>
#include "GyverTimer.h"  

#include <BlynkSimpleEsp8266.h>
#include "DHT.h"
#include <SPI.h>
#include <Wire.h>
#include <EEPROM.h>

#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#define OLED_RESET D4
Adafruit_SSD1306 display(OLED_RESET);
#define NUMFLAKES 10
#define XPOS 0
#define YPOS 1
#define DELTAY 2


#define LOGO16_GLCD_HEIGHT 16 
#define LOGO16_GLCD_WIDTH  16 

#define DHTPIN D6
#define DHT2PIN D5
#define DHTTYPE DHT11
#define DHT2TYPE DHT22
#define RELEY D3
#define potent_pin A0

GTimer myTimer(MS);
ESP8266WiFiMulti wifiMulti;
const uint32_t connectTimeoutMs = 5000;

DHT dht(DHTPIN, DHTTYPE);
DHT dht2(DHT2PIN, DHT2TYPE);


float Hin;
float Tin;
float Hout;
float Tout;
int valBase = 6;
int target;
int potent;
int INET;
bool valueR;
boolean value4;

int delta = 2;
int addr_targ = 101;
int addr_reley = 102;
int addr_last = 103;
int addr_Time = 104;
void blynk();


const char* auth = "***********-**********";


BLYNK_WRITE(V11) {
  int pinValue = param.asInt();
  EEPROM.write(addr_targ, pinValue);
  Serial.println("inet: " + String(pinValue)); }


void setup() {
  
  WiFi.persistent(false);
  display.begin(SSD1306_SWITCHCAPVCC, 0x3C);
  display.display();
  delay(2000);
  display.setTextSize(1);
  display.setTextColor(WHITE);
  display.setCursor(0,0);
  
  display.clearDisplay();
  Serial.begin(115200);
   WiFi.mode(WIFI_STA);

  
  wifiMulti.addAP("****_Guest", "****4321");
  wifiMulti.addAP("*****WiFi", "19491949");
  wifiMulti.addAP("Redmi", "*******1975");
  wifiMulti.addAP("P**ot", "P*******240195a");
  wifiMulti.addAP("V******", "******04");
  wifiMulti.addAP("TP-LINK_E******", "1*********9");
  
  
  dht.begin();
  pinMode (RELEY, OUTPUT);
  EEPROM.begin(512);
  EEPROM.put(addr_targ, valBase );
  myTimer.setInterval(50000);
 

}

void loop() {

  float value1 = dht.readTemperature();
  float value2 = dht.readHumidity();
  float value6 = dht2.readTemperature();
  float value7 = dht2.readHumidity();
  int INET = EEPROM.read(addr_targ);
 

  potent = analogRead(potent_pin);      
  potent = map(potent, 0, 1023, 5, 30);    
  potent = constrain(potent, 5, 30);
  

  if (potent >= INET) { 
    target = potent;
  }
      else if (potent <= INET) {
        target = INET;
      }
 

  if (value1 <= target - delta) {
    digitalWrite(RELEY, HIGH);
    bool valueR = 1;
    EEPROM.put(addr_reley, valueR );
   
  }

  else if (value1 >= target) {
    digitalWrite(RELEY, LOW);
    bool valueR = 0;
    EEPROM.put(addr_reley, valueR );
 
  }


  display.setTextSize(1);
  display.setTextColor(WHITE);
  display.setCursor(0,0);
  display.println("TEMP.inside: "+String(value1));
  display.println("Hymid.inside: "+String(value2));
  display.println("TEMP.outside: "+String(value6));
  display.println("Hymid.outside: "+String(value7)); 
  
  display.println(": ");
  display.println("ZADANO V RUCHNU: "+String(potent));
  display.println("TEMP.targrt I-NET: "+String(INET));
  display.display();
  unsigned long millis(200); 
  display.clearDisplay();

if (myTimer.isReady())   {   Serial.println("BLYNK BEGIN");
    blynk();}
  
}

void blynk() {
  float Tin = dht.readTemperature();
  float Hin = dht.readHumidity();
  float Tout = dht2.readTemperature();
  float Hout = dht2.readHumidity();

  if (wifiMulti.run(connectTimeoutMs) == WL_CONNECTED) {
   Blynk.connect();
   Blynk.config(auth);
    
  
    Serial.println("WiFi connected");
    Serial.println("IP address: ");
    Serial.println(WiFi.localIP());
     
    if ( Blynk.connected()) { 
                Blynk.run();
                Serial.print("Blynk Connected");
              Blynk.syncAll();
             
 bool valueR = EEPROM.read(addr_reley);
                if (valueR == 1) {        Blynk.virtualWrite(V3, HIGH);    }
                      else if  (valueR == 0)   {      Blynk.virtualWrite(V3, LOW);    }

              Blynk.virtualWrite(V6, Tin);
              Blynk.virtualWrite(V7, Hin);
              Blynk.virtualWrite(V8, Tout);
              Blynk.virtualWrite(V9, Hout);
              Serial.println("RELEY: " + String(valueR));
            
              unsigned long millis(5000);
              Serial.println("Temp. in: " + String(Tin));
              Serial.println("Temp. out: " + String(Tout));
                             }
   
    
    else if ( ! Blynk.connected() ) { 
   Serial.print("Blynk NOT Connected");
    WiFi.disconnect();
    WiFi.mode(WIFI_OFF);
    //Serial.println(WiFi.status());
    return;   }}

  if (WiFi.status() != WL_CONNECTED) {
    unsigned long millis(5000);
    Serial.println("No Conncetion");
    WiFi.disconnect();
  }

  WiFi.disconnect();
  WiFi.mode(WIFI_OFF);
  Serial.println(WiFi.status());
  return;
} 

@Vitalii_Mamchur 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.

@PeteKnight thanks, I did.

First of all, your void loop is a mess, and not compatible with Blynk.

Read this:

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

Secondly, you shouldn’t be using ERPROM, as it has a very limited read/write life. You should use SPIFFS, or preferably LittleFS.

I’d also suggest adding #define BLYNK_PRINT Serial to the beginning of your sketch, then you’ll get more info about the Blynk connection process in your serial monitor.

Pete.

Dear @PeteKnight!

Thanks, as i mentioned above, it’s just one of my firs code, mainly assembled from examples, but it’s work any way. About usage SPIFFS and LittleFS instead ERPROM interesting, need to be learned.

But still not understand why I see in Blynk app and Serial monitor that connection is established but no data sent / received? Any idea?

You don’t have any code in your sketch to write data to Blynk, but you need to sort-out your void loop before you add that code, otherwise you will flood the Blynk server.

I’d suggest that you take a look at the Sketch Builder examples for the DHT sensor to see how it should be done.

Pete.

The main idea of my code was work with no internet connection, I like blynk because it simple BUT it totally useless without internet connection, code simply stack. On this reason was separated main function in void loop from wifi connection and Blynk connection.

If we look at standard example :

#include <SoftwareSerial.h>
SoftwareSerial DebugSerial(2, 3); // RX, TX

#define BLYNK_PRINT DebugSerial
#include <BlynkSimpleStream.h>

#include <SimpleTimer.h>
#include <DHT.h>
#define DHTPIN 5         

#define DHTTYPE DHT11     // DHT 11
//#define DHTTYPE DHT22   // DHT 22, AM2302, AM2321
//#define DHTTYPE DHT21   // DHT 21, AM2301

DHT dht(DHTPIN, DHTTYPE);
SimpleTimer timer;


char auth[] = "YourAuthToken";

void sendSensor()
{
  float h = dht.readHumidity();
  float t = dht.readTemperature(); // or dht.readTemperature(true) for Fahrenheit

  if (isnan(h) || isnan(t)) {
    Serial.println("Failed to read from DHT sensor!");
    return;
  }
  
  Blynk.virtualWrite(V5, h);
  Blynk.virtualWrite(V6, t);
}

void setup()
{
   DebugSerial.begin(9600);

  
  Serial.begin(9600);
  Blynk.begin(Serial, auth);
  timer.setInterval(1000L, sendSensor);
}

void loop()
{
  Blynk.run();
  timer.run(); // Initiates SimpleTimer
}

Blynk.run() is in main loop, so if we lost wifi mean nothing work!

There are ways around that, by using Blynk.config and Blynk.connect instead of Blynk.begin, as you’ve done in your original sketch, but there aren’t ways around putting Blynk.virtualWrite in a cluttered loop and flooding the server.

Pete.

Hey there, you can 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();
  }
}

I don’t think this sketch is going to help @Vitalii_Mamchur because it uses the blocking Blynk.begin command, and will always call Blynk.run if there’s a WiFi connection.

A better approach would be to use a Blynk.connected() test in the void loop, and only call Blynk.run if this evaluates to true, in combination with a timer that attempts to re-connect to WiFi and/or Blynk if they are currently disconnected.

Pete.

You mean something like this :

void loop(){
  timer.run();
  if(Blynk.connected() == true){
    Blynk.run();
  }
}

Yes.

Pete.

Hi!

I don’t see any sustainable difference between your:

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

and in my void setup

 myTimer.setInterval(50000);

than in loop

if (myTimer.isReady())   {   Serial.println("BLYNK BEGIN");
    blynk();
}

and after in separate function void blynk() we do connection to internet and authorization in blynk

if (wifiMulti.run(connectTimeoutMs) == WL_CONNECTED) {
   Blynk.connect();
   Blynk.config(auth);
    
  
    Serial.println("WiFi connected");
    Serial.println("IP address: ");
    Serial.println(WiFi.localIP());
     
    if ( Blynk.connected()) { 
                Blynk.run();
                Serial.print("Blynk Connected");
              Blynk.syncAll();

above parts work just fine, but not executed below code to post my data and get back target temperature:

bool valueR = EEPROM.read(addr_reley);
                if (valueR == 1) {        Blynk.virtualWrite(V3, HIGH);    }
                      else if  (valueR == 0)   {      Blynk.virtualWrite(V3, LOW);    }

              Blynk.virtualWrite(V6, Tin);
              Blynk.virtualWrite(V7, Hin);
              Blynk.virtualWrite(V8, Tout);
              Blynk.virtualWrite(V9, Hout);
              Serial.println("RELEY: " + String(valueR));

and

BLYNK_WRITE(V11) {
  int pinValue = param.asInt();
  EEPROM.write(addr_targ, pinValue);
  Serial.println("inet: " + String(pinValue)); }

any idea why? Thanks in advance for your help!

Blynk expects a constant connection to the Blynk server, with Blynk.run being executed at least once in every cycle of the void loop (which needs to not be delayed by blocking code or a cluttered void loop, so that it can execute hundreds if not thousands of times per second).

The strategy for handling a situation where you still want additional processing to continue uninterrupted when the connection to the Blynk server is down requires the approach we discussed above.

If for some reason you are trying to reduce internet traffic, and only connect to Blynk occasionally to send updates, then go offline, then a different approach is required.
However, f you do this then BLYNK_WRITE(vPin) callbacks won’t function as expected, and dome additional coding, such as the use of the BLYNK_CONNECTED() callback and the Blynk.syncVirtual(vPin) command are required.

Pete.

1 Like

You can try this :

void offline_mode()
{
// your offline code here
}

void loop()
{
  if(Blynk.connected() == true){
    Blynk.run();
  }
  else if(Blynk.connected() == false){
    Serial.println("Blynk Not Connected!");
    Blynk.connect();
    offline_mode();
  }
}

The problem with that approach is that Blynk.connect() will be executed on every void loop cycle, and this command has a default timeout period which blocks all other code execution. You can specify a different timeout period using Blynk.connect(timeout), but this doesn’t work that well - there are still relatively long blocking delays each time this command is called.

That’s why I said…

This allows you to decide how often to call the timer which attempts to do the re-connection.

Also, there are two parts to the re-connection. Blynk.connect() will attempt to use the current network (WiFi) connection to establish a connection to the Blynk server using the settings defined in Blynk.config, it wont attempt to establish or re0-establush a WiFi connection.
So the two part test is:

  1. check if WiFi is connected, and if not attempt to re-connect
  2. check is Blynk is connected and if not then attempt to re-connect.

Pete.

Dear Pete! do you have some example of usage below commands?

However, f you do this then BLYNK_WRITE(vPin) callbacks won’t function as expected, and dome additional coding, such as the use of the BLYNK_CONNECTED() callback and the Blynk.syncVirtual(vPin) command are required.

I’ll strongly appreciated if you post some. It’s help to better understand

Pete.