#define BLYNK_PRINT Serial
#define BLYNK_TEMPLATE_ID "TMPL25X8v8SVq"
#define BLYNK_TEMPLATE_NAME "IH720"
#define BLYNK_AUTH "4idLXCFezGWkNfgWz_XL946AH2tv8eHX"
#define USE_BLYNK_WM true
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <WiFi.h>
#include <WiFiClient.h>
#include <BlynkSimpleEsp32.h>
#define MQ2_ANA 34
#define MQ2_DIG 15
#define THRESHOLD 3000
#define BUZZER_PIN 12
#define LED_PIN 5
#define LCD_COLUMNS 16
#define LCD_ROWS 2
#define LCD_ADDRESS 0x27
#define SDA_PIN 21
#define SCL_PIN 22
#define RL 10
#define WIFI_SSID "Wokwi-GUEST"
#define WIFI_PASS ""
char auth[] = BLYNK_AUTH;
char ssid[] = WIFI_SSID;
char pass[] = WIFI_PASS;
int lastPrintedValue = -1;
LiquidCrystal_I2C lcd(LCD_ADDRESS, LCD_COLUMNS, LCD_ROWS);
int readMQ2() {
int adcValue = analogRead(MQ2_ANA);
int ppm = map(adcValue, 0, 4095, 200, 10000);
return ppm;
}
void setupLCD() {
Wire.begin(SDA_PIN, SCL_PIN);
delay(100); // Breve retraso para estabilización
lcd.init();
lcd.backlight();
lcd.clear();
}
void setupPins() {
pinMode(MQ2_ANA, INPUT);
pinMode(MQ2_DIG, INPUT);
pinMode(BUZZER_PIN, OUTPUT);
pinMode(LED_PIN, OUTPUT);
}
void printGasLevel(int value) {
if (value == lastPrintedValue) {
return;
}
lastPrintedValue = value;
lcd.setCursor(0, 0);
lcd.print("Gas: "); // Limpia toda la línea
lcd.setCursor(5, 0);
if (value < 1000) {
lcd.print(value);
lcd.print(" ppm");
} else {
// Para valores de 1000 o más, usamos formato con coma
lcd.print(value / 1000);
lcd.print(",");
// Aseguramos que siempre haya 3 dígitos después de la coma
if (value % 1000 < 10) {
lcd.print("00");
} else if (value % 1000 < 100) {
lcd.print("0");
}
lcd.print(value % 1000);
lcd.print(" ppm");
}
// Imprimir el estado en la segunda línea
lcd.setCursor(0, 1);
if (value > THRESHOLD) {
lcd.print("Advertencia ");
} else {
lcd.print("Normal ");
}
}
void handleAlarm(int gasLevel) {
bool isAlarmOn = gasLevel > THRESHOLD;
digitalWrite(BUZZER_PIN, isAlarmOn);
digitalWrite(LED_PIN, isAlarmOn);
}
void remoteUpdate(int value) {
Blynk.virtualWrite(V0, value);
}
void setup() {
Serial.begin(115200);
setupLCD();
setupPins();
Blynk.begin(auth, ssid, pass);
}
void loop() {
Blynk.run();
int analogValue = readMQ2();
int digitalValue = digitalRead(MQ2_DIG);
Serial.print("Analog: ");
Serial.println(analogValue);
Serial.print("Digital: ");
Serial.println(digitalValue);
printGasLevel(analogValue);
remoteUpdate(analogValue);
handleAlarm(analogValue);
delay(300);
}