Virtual LED's Output

I create another project about sensor MQ2 connected to Blynk
Details :
• My hardware: esp8266
• Samsung A14 (Android 13, One UI Core 5)
• Indonesia
• Blynk at version 1.3.2
This is my program:

#define BLYNK_TEMPLATE_ID           "TMPxxxxxx"
#define BLYNK_TEMPLATE_NAME         "Sensor MQ2"

#define BLYNK_PRINT Serial
#include <ESP8266WiFi.h>
#include <BlynkSimpleEsp8266.h>

char auth[] = "xxxxxxx";

char ssid[] = "PC1";
char pass[] = "passxxxxx";

int mq2 = D2;  
int data = 0;
void setup()
{
  
  Serial.begin(9600);
  //Blynk.config(auth);
  Blynk.begin(auth, ssid, pass);

  
  pinMode(mq2, INPUT);
}
void loop()
{

  Blynk.run();

  
  data = digitalRead(mq2);
  Serial.print("Status Sensor MQ-2 (Digital): ");
  Serial.println(data);


  Blynk.virtualWrite(V1, data);

  delay(1000);
}

The program runs well
The issue is:
When sensor mq2 detected, the output of virtual LED on Blynk is LOW (OFF), and vice versa

You shouldn’t be using delays in your void loop, or have Blynk.virtualWrite in your void loop.
Instead, you should be using BlynkTimer to call a separate function once every second.
Read this for more info…

Implement this change and post your updated code, then I’ll show you how to overcome your virtual LED issue.

Pete.

This is my fixed program:

You clearly didn’t understand the “keep your void loop clean” tutorial, and you seem to have grabbed some random code from another sketch which has nothing to do with what you’re trying to achieve.

Revert to your original code then follow the “keep your void loop clean” tutorial properly.

Pete.

Sorry for my mistake, Here’s the correct code:

#define BLYNK_TEMPLATE_ID "TMPxxxx"
#define BLYNK_TEMPLATE_NAME "Sensor MQ2"

#define BLYNK_PRINT Serial
#include <ESP8266WiFi.h>
#include <BlynkSimpleEsp8266.h>

char auth[] = "xxxxxx";

// Koneksi Wi-Fi
char ssid[] = "PC1";
char pass[] = "passxxxxxx";

BlynkTimer timer;

int mq2 = D2;
int data = 0;

void sensorDataSend()
{
  data = digitalRead(D2);         // reading sensor from analog pin
  Blynk.virtualWrite(V1, data);  // sending sensor value to Blynk app
}
void setup()
{
  // Memulai Serial dan Blynk
  Serial.begin(9600);
  Blynk.begin(auth, ssid, pass);

  // Setup pin digital sebagai input
  pinMode(mq2, INPUT);
  timer.setInterval(1000L, sensorDataSend);
}
void loop()
{
  // Jalankan Blynk
  Blynk.run();
  timer.run();
}

What’s next step?

You have two options…

Change this line:

So that you invert the signal by sending the logical opposite of the value that is read from the sensor. This is done using the logical NOT operator, which is an exclamation mark (!).
Your new code would look like this…

Blynk.virtualWrite(V1, !data); // sending inverted sensor value to Blynk app

Option 2 is to change the V1 datastream in the Blynk console so that instead of having a min/max value of 0/1 you invert this with a min/max value of 1/0

Option 1 (using the logical NOT operator in your code is probably the neatest solution.

Pete.