#include <WiFi.h>
#include <HTTPClient.h>
const char* ssid = "Wokwi-GUEST"; // Replace with your WiFi SSID
const char* password = ""; // Replace with your WiFi Password
String apiKey = "7XJ8I9DKZL4HT2G7"; // ThingSpeak API Key
const String server = "http://api.thingspeak.com/update";
int channelID = 2667740;
const int gasSensorPin = 34; // Gas sensor pin
const int ledPin = 22; // LED pin
int threshold = 400; // Gas level threshold for LED activation
void setup() {
Serial.begin(115200);
// Set LED pin as output
pinMode(ledPin, OUTPUT);
// Connect to WiFi
WiFi.begin(ssid, password);
Serial.println("Connecting to WiFi...");
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.print(".");
}
Serial.println("");
Serial.println("Connected to WiFi");
}
void loop() {
int gasLevel = analogRead(gasSensorPin); // Read gas sensor value
Serial.print("Gas Level: ");
Serial.println(gasLevel);
// Activate LED if gas level exceeds the threshold
if (gasLevel > threshold) {
digitalWrite(ledPin, HIGH);
} else {
digitalWrite(ledPin, LOW);
}
// Send data to ThingSpeak
if (WiFi.status() == WL_CONNECTED) {
HTTPClient http;
// Convert server to String and concatenate the URL components
String url = server + "?api_key=" + apiKey + "&field1=" + String(gasLevel);
http.begin(url);
int httpCode = http.GET(); // Send the request
if (httpCode > 0) {
String payload = http.getString(); // Get the response
Serial.println("Data sent to ThingSpeak: " + payload);
} else {
Serial.println("Error in sending data");
}
http.end(); // End connection
}
delay(15000); // Wait 15 seconds before sending data again (ThingSpeak limit)
}