String apiKey = "TEFKPUX88K03CLTT"; // Enter your Write API key from ThingSpeak
const char* ssid = "Wokwi-GUEST"; // your WiFi SSID
const char* pass = ""; // your WiFi password
const char* server = "api.thingspeak.com"; // ThingSpeak server
const int gasSensorPin = 34; // GPIO for Gas Sensor
const int ledPin = 22; // GPIO for Red LED
const int LED_wifi = 2; // GPIO for WiFi status LED (can use onboard LED)
WiFiClient client;
void setup() {
Serial.begin(115200);
pinMode(gasSensorPin, INPUT);
pinMode(ledPin, OUTPUT);
pinMode(LED_wifi, OUTPUT);
Serial.println("Connecting to WiFi...");
WiFi.begin(ssid, pass);
while (WiFi.status() != WL_CONNECTED) {
digitalWrite(LED_wifi, HIGH);
delay(500);
Serial.print(".");
digitalWrite(LED_wifi, LOW);
delay(500);
}
Serial.println("");
Serial.println("WiFi connected");
digitalWrite(LED_wifi, HIGH);
}
void loop() {
// Read gas sensor value
int gasSensorValue = analogRead(gasSensorPin);
// Control LED based on gas sensor reading
if (gasSensorValue > 500) {
digitalWrite(ledPin, HIGH); // Turn on LED if gas value exceeds 500
} else {
digitalWrite(ledPin, LOW); // Turn off LED otherwise
}
// Send data to ThingSpeak
sendDataToThingSpeak(gasSensorValue);
// Delay for 20 seconds before sending data again
delay(5000);
}
void sendDataToThingSpeak(int gasSensorValue) {
if (client.connect(server, 80)) { // Connect to ThingSpeak server
String postStr = apiKey;
postStr += "&field1=";
postStr += String(gasSensorValue);
postStr += "\r\n\r\n";
client.print("POST /update HTTP/1.1\n");
client.print("Host: api.thingspeak.com\n");
client.print("Connection: close\n");
client.print("X-THINGSPEAKAPIKEY: " + apiKey + "\n");
client.print("Content-Type: application/x-www-form-urlencoded\n");
client.print("Content-Length: " + String(postStr.length()) + "\n\n");
client.print(postStr);
Serial.print("Gas Sensor value: ");
Serial.println(gasSensorValue);
client.stop(); // Close the connection
Serial.println("Waiting for next update...");
} else {
Serial.println("Connection to ThingSpeak failed");
}
}