#include <WiFi.h>
#include <HTTPClient.h>
#include <DHT.h>
#define DHTPIN 4 // GPIO pin for DHT11
#define DHTTYPE DHT11 // DHT11 sensor
DHT dht(DHTPIN, DHTTYPE);
// Replace with your WiFi credentials
const char* ssid = "Wokwi-GUEST";
const char* password = "";
// Replace with your ThingSpeak API key
String apiKey = "1D7BB11DLXH4UQ3Z";
String server = "https://api.thingspeak.com";
void setup() {
Serial.begin(115200);
dht.begin();
// Connect to Wi-Fi
WiFi.begin(ssid, password);
Serial.print("Connecting to WiFi");
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.print(".");
}
Serial.println("\nWiFi connected");
}
void loop() {
float temperature = dht.readTemperature();
float humidity = dht.readHumidity();
if (isnan(temperature) || isnan(humidity)) {
Serial.println("Failed to read from DHT sensor!");
return;
}
Serial.print("Temperature: ");
Serial.print(temperature);
Serial.println(" °C");
Serial.print("Humidity: ");
Serial.print(humidity);
Serial.println(" %");
if (WiFi.status() == WL_CONNECTED) {
HTTPClient http;
String url = server + "/update?api_key=" + apiKey +
"&field1=" + String(temperature) +
"&field2=" + String(humidity);
http.begin(url);
int httpCode = http.GET();
if (httpCode > 0) {
Serial.println("Data sent to ThingSpeak");
} else {
Serial.println("Error sending data");
}
http.end();
}
delay(20000); // Wait 20 seconds before sending the next data
}