#include "DHTesp.h"
#include "WiFi.h"
WiFiClient client; // Changed to lowercase 'client' for consistency
const int sensorPin = 15;
String thingSpeakAddress = "api.thingspeak.com";
String request_string;
DHTesp dhtSensor;
// 1. Moved the function definition OUTSIDE of the loop()
void SendingData_thingspeak(float temp, float hum) {
if (client.connect("api.thingspeak.com", 80)) {
request_string = "/update?";
request_string += "key=";
request_string += "0L4PFQFIRVU921JY"; // Added missing semicolon
request_string += "&";
request_string += "field1="; // Added the '=' sign
request_string += temp; // Used the local parameter 'temp'
request_string += "&field2="; // Added field2 to send humidity data
request_string += hum; // Used the local parameter 'hum'
// Fixed spacing in the HTTP GET request ("GET " and " HTTP/1.1")
String httpRequest = String("GET ") + request_string + " HTTP/1.1\r\n" +
"Host: " + thingSpeakAddress + "\r\n" +
"Connection: close\r\n\r\n";
Serial.println(httpRequest);
client.print(httpRequest);
unsigned long timeout = millis();
// Wait for the server to respond
while (client.available() == 0) {
if (millis() - timeout > 5000) {
Serial.println(">>>> Client Timeout");
client.stop();
return;
}
}
// Read the response from the server
while (client.available()) {
String line = client.readStringUntil('\r');
Serial.print(line);
}
Serial.println();
Serial.println("Closing the connection");
} else {
Serial.println("Connection to ThingSpeak failed.");
}
}
void setup() {
Serial.begin(115200);
WiFi.disconnect();
// Explicitly set the ESP32 as a WiFi client
WiFi.mode(WIFI_STA);
// Capital 'W' in Wokwi-GUEST
WiFi.begin("Wokwi-GUEST", "");
while (WiFi.status() != WL_CONNECTED) {
delay(300);
Serial.print(".");
}
Serial.println("\nWiFi connected successfully");
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
dhtSensor.setup(sensorPin, DHTesp::DHT22);
}
void loop() {
delay(2000); // ThingSpeak only accepts data every 15 seconds on the free tier, increased to 2s for simulator stability
TempAndHumidity data = dhtSensor.getTempAndHumidity();
float t = data.temperature;
float h = data.humidity;
// 2. Moved the validation check BEFORE we try to send the data
if (isnan(h) || isnan(t)) {
Serial.println("Failed to get the data");
return;
}
// Call the function to send data
SendingData_thingspeak(t, h);
}