#include <WiFi.h>
#include <DHTesp.h>
#include <HTTPClient.h>
const char* ssid = "Wokwi-GUEST";
const char* password = "";
const char* serverName = "http://api.thingspeak.com/update";
String apiKey = "MJ4USI8T24YSBGBA";
unsigned long lastTime = 0;
unsigned long timerDelay = 10000;
const int DHT_PIN = 33;
DHTesp dhtSensor;
void setup() {
Serial.begin(115200);
dhtSensor.setup(DHT_PIN, DHTesp::DHT22);
WiFi.begin(ssid, password);
Serial.println("Connecting");
while(WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.print("Connected to WiFi network with IP Address: ");
Serial.println(WiFi.localIP());
Serial.println("Timer set to 10 seconds (timerDelay variable), it will take 10 seconds before publishing the first reading.");
// Random seed is a number used to initialize a pseudorandom number generator
}
void loop() {
//Send an HTTP POST request every 10 seconds
if ((millis() - lastTime) > timerDelay) {
//Check WiFi connection status
if(WiFi.status()== WL_CONNECTED){
WiFiClient client;
HTTPClient http;
TempAndHumidity data = dhtSensor.getTempAndHumidity();
Serial.println("Temp: " + String(data.temperature, 2) + "°C");
Serial.println("---");
http.begin(client, serverName);
// Specify content-type header
http.addHeader("Content-Type", "application/x-www-form-urlencoded");
// Data to send with HTTP POST
String httpRequestData = "api_key=" + apiKey + "&field1="+ data.temperature ;
int httpResponseCode = http.POST(httpRequestData); // Send HTTP POST request
Serial.print("HTTP Response code: ");
Serial.println(httpResponseCode);
http.end();
}
else {
Serial.println("WiFi Disconnected");
}
lastTime = millis();
}
}