#include <WiFi.h>
#include <WiFiClient.h>
String apiKey = "TEFKPUX88K03CLTT";
const char* ssid = "Wokwi-GUEST";
const char* pass = "";
const char* server = "api.thingspeak.com";
const int gasSensorPin = 34;
const int ledPin = 22;
const int LED_wifi = 2;
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() {
int gasSensorValue = analogRead(gasSensorPin);
if (gasSensorValue > 500) {
digitalWrite(ledPin, HIGH);
} else {
digitalWrite(ledPin, LOW);
}
sendDataToThingSpeak(gasSensorValue);
delay(5000);
}
void sendDataToThingSpeak(int gasSensorValue) {
if (client.connect(server, 80)) {
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();
Serial.println("Waiting for next update...");
} else {
Serial.println("Connection to ThingSpeak failed");
}
}