#include <WiFi.h>
#include <ThingSpeak.h>
#define gasPin 34 // Analog input pin for MQ-2
#define buzzerPin 25 // Buzzer pin
#define RL 10000.0 // 10k Ohms
#define R0 3050.0 // Replace with your own calibrated R0 value
// Wi-Fi
const char* ssid = "Wokwi-GUEST"; // Change as needed
const char* password = ""; // Change as needed
// ThingSpeak
WiFiClient client;
unsigned long channelID = 2869806; // Your channel ID
const char* writeAPIKey = "6Y3JTFY09CMPEMNC"; // Your Write API key
void setup() {
Serial.begin(115200);
pinMode(buzzerPin, OUTPUT);
WiFi.begin(ssid, password);
Serial.print("Connecting to Wi-Fi");
while (WiFi.status() != WL_CONNECTED) {
Serial.print(".");
delay(1000);
}
Serial.println("\nWi-Fi Connected");
ThingSpeak.begin(client);
}
void loop() {
int adcValue = analogRead(gasPin);
float voltage = adcValue * (3.3 / 4095.0);
float Rs = (3.3 - voltage) * RL / voltage;
float ratio = Rs / R0;
// MQ-2 LPG/Smoke PPM calculation (approximation)
float ppm = 100 * pow(ratio, -2.6);
digitalWrite(buzzerPin, LOW);
Serial.print("Gas Concentration: ");
Serial.print(ppm);
Serial.println(" ppm");
// Send ppm data to ThingSpeak Field 3 ✅
ThingSpeak.setField(3, ppm);
int statusCode = ThingSpeak.writeFields(channelID, writeAPIKey);
if (statusCode == 200) {
Serial.println("ThingSpeak update successful.");
} else {
Serial.print("ThingSpeak update failed, Error code: ");
Serial.println(statusCode);
}
// Buzzer alert if ppm exceeds 500 (adjustable)
if (ppm > 500) {
digitalWrite(buzzerPin, HIGH);
delay(1000); // Buzzer ON
Serial.println("WARNING! High Gas Concentration Detected!");
} else {
digitalWrite(buzzerPin, LOW); // Buzzer OFF
}
delay(15000); // ThingSpeak minimum interval
}