#include <WiFi.h>
#include <HTTPClient.h>
const char* ssid = "Wokwi-GUEST"; // Use "Wokwi-GUEST" for simulation
const char* password = ""; // No password needed for Wokwi Wi-Fi simulation
const char* server = "http://api.thingspeak.com/update";
String apiKey = "YOUR_THINGSPEAK_API_KEY"; // Replace with actual API Key(optional Real world Test)
void setup() {
Serial.begin(115200);
// Connect to Wi-Fi
Serial.print("Connecting to WiFi");
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("\nConnected to WiFi!");
Serial.println("ESP32 IP Address: " + WiFi.localIP().toString());
}
void loop() {
if (WiFi.status() == WL_CONNECTED) {
HTTPClient http;
// Generate random sensor data for simulation
int temperature = random(20, 35);
int humidity = random(40, 80);
// Convert 'server' to String before concatenation
String url = String(server) + "?api_key=" + apiKey + "&field1=" + String(temperature) +
"&field2=" + String(humidity);
http.begin(url);
int httpResponseCode = http.GET();
http.end();
Serial.print("Data Sent to ThingSpeak - Temperature: ");
Serial.print(temperature);
Serial.print("°C, Humidity: ");
Serial.print(humidity);
Serial.println("%");
} else {
Serial.println("Wi-Fi Disconnected. Reconnecting...");
if (WiFi.status() != WL_CONNECTED) {
Serial.println("Reconnecting to WiFi...");
WiFi.disconnect();
WiFi.reconnect();
}
delay(15000); // Send data every 15 seconds
}