// Blynk credentials (from Blynk dashboard)
#define BLYNK_TEMPLATE_ID "TMPL3ma8D9ACv"
#define BLYNK_TEMPLATE_NAME "Assingment"
#define BLYNK_AUTH_TOKEN "7uxPQrIHdJ4W6LEs7U5Vo2lbhJ1F95uP"
#include <WiFi.h> // For WiFi connection
#include <DHT.h> // For DHT sensor
#include <BlynkSimpleEsp32.h> // For Blynk cloud communication
// Pin definitions
#define DHTPIN 14 // DHT22 data pin connected to GPIO13
#define DHTTYPE DHT22 // Sensor type
#define MQ2PIN 12 // MQ2 analog pin connected to GPIO32
// WiFi credentials
char ssid[] = "Wokwi-GUEST"; // Wokwi simulator WiFi
char pass[] = ""; // No password for Wokwi
char auth[] = BLYNK_AUTH_TOKEN; // Blynk authentication token
DHT dht(DHTPIN, DHTTYPE); // Initialize DHT sensor
void setup() {
Serial.begin(115200); // Start serial monitor
delay(100);
// Connect to WiFi
Serial.println("Connecting to WiFi...");
WiFi.begin(ssid, pass);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.print(".");
}
Serial.println("\nWiFi connected!");
Serial.print("IP Address: ");
Serial.println(WiFi.localIP());
// Connect to Blynk
Blynk.config(auth);
Blynk.connect();
// Start DHT sensor
dht.begin();
// MQ2 sensor needs 1 min warm-up
delay(60000);
Serial.println("MQ2 sensor warm-up complete.");
}
void loop() {
Blynk.run(); // Run Blynk
readAndSendSensorData(); // Read and send data
delay(2000); // Wait 2 seconds before next reading
}
// Function to read sensor values and send to Blynk
void readAndSendSensorData() {
float temp = dht.readTemperature(); // Read temperature
float hum = dht.readHumidity(); // Read humidity
int gasValue = analogRead(MQ2PIN); // Read gas sensor value
// Check if sensor reading failed
if (isnan(temp) || isnan(hum)) {
Serial.println("DHT read failed");
return;
}
// Show values in Serial Monitor
Serial.printf("Temperature: %.2f °C\n", temp);
Serial.printf("Humidity: %.2f %%\n", hum);
Serial.printf("Gas Sensor Value: %d\n", gasValue);
// Send values to Blynk
Blynk.virtualWrite(V0, temp); // Temperature - V0
Blynk.virtualWrite(V1, hum); // Humidity - V1
Blynk.virtualWrite(V2, gasValue); // Gas - V2
}