#include <WiFi.h> // For ESP32 (use <ESP8266WiFi.h> if using ESP8266)
#include <ThingSpeak.h> // ThingSpeak library
// --- Pin Configuration ---
const int gasSensorPin = 34; // Analog pin connected to MQ sensor
// --- WiFi Configuration ---
const char* WIFI_NAME = "Wokwi-GUEST"; // Your Wi-Fi SSID
const char* WIFI_PASSWORD = ""; // Your Wi-Fi password
// --- ThingSpeak Configuration ---
unsigned long myChannelNumber = 3102966; // Replace with your ThingSpeak Channel ID
const char* myWriteAPIKey = "O51XD4FIEEZNA67O"; // Replace with your Write API Key
WiFiClient client;
int sensorValue;
void setup() {
Serial.begin(9600);
delay(100);
Serial.println("Gas Sensor with ThingSpeak");
// --- Connect to Wi-Fi ---
WiFi.begin(WIFI_NAME, WIFI_PASSWORD);
Serial.print("Connecting to WiFi");
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("\nWiFi Connected!");
// --- Initialize ThingSpeak ---
ThingSpeak.begin(client);
delay(2000); // Warm-up time for MQ sensor
}
void loop() {
// --- Read gas sensor value ---
sensorValue = analogRead(gasSensorPin);
Serial.print("Sensor Value: ");
Serial.print(sensorValue);
String gasType;
// --- Identify gas type based on threshold ---
if (sensorValue < 200) {
gasType = "Clean Air";
}
else if (sensorValue >= 200 && sensorValue < 400) {
gasType = "LPG/Propane";
}
else if (sensorValue >= 400 && sensorValue < 600) {
gasType = "Carbon Monoxide";
}
else if (sensorValue >= 600) {
gasType = "Smoke/Alcohol";
}
Serial.print(" - ");
Serial.println(gasType);
// --- Send data to ThingSpeak ---
ThingSpeak.setField(1, sensorValue); // Field 1 → raw sensor value
//ThingSpeak.setField(2, gasType); // Field 2 → detected gas type (as text)
int status = ThingSpeak.writeFields(myChannelNumber, myWriteAPIKey);
if (status == 200) {
Serial.println("Data sent successfully to ThingSpeak!");
} else {
Serial.println("Error sending data to ThingSpeak. HTTP error code: " + String(status));
}
delay(20000); // ThingSpeak accepts updates every 15 seconds (20s safe)
}