#include <WiFi.h>
#include <HTTPClient.h>
// Replace with your WiFi credentials
const char* ssid = "Your_SSID";
const char* password = "Your_PASSWORD";
// Replace with your ThingSpeak API Key
const char* apiKey = "QACOOKB4NUAMU5A6";
const char* server = "http://api.thingspeak.com/update";
// Define MQ-2 pin
const int mq2Pin = 34; // Analog pin connected to MQ-2 sensor output
void setup() {
Serial.begin(115200);
WiFi.begin(ssid, password);
Serial.print("Connecting to WiFi");
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("\nConnected to WiFi");
}
void loop() {
int gasValue = analogRead(mq2Pin); // Read the analog value from MQ-2
Serial.print("Gas Value: ");
Serial.println(gasValue);
if (WiFi.status() == WL_CONNECTED) {
HTTPClient http;
String url = String(server) + "?api_key=" + apiKey + "&field1=" + String(gasValue);
http.begin(url);
int httpResponseCode = http.GET();
if (httpResponseCode > 0) {
Serial.print("HTTP Response Code: ");
Serial.println(httpResponseCode);
if (httpResponseCode == 200) {
Serial.println("Data successfully sent to ThingSpeak.");
}
} else {
Serial.print("Error Code: ");
Serial.println(httpResponseCode);
}
http.end();
} else {
Serial.println("WiFi Disconnected");
}
delay(20000); // ThingSpeak allows updates every 15 seconds
}