#include <WiFi.h>
#include <HTTPClient.h>
#include <DHT.h>
#define DHTPIN 15 // Pin connected to the DHT22 sensor
#define DHTTYPE DHT22 // DHT22 sensor type
const char* ssid = "Wokwi-GUEST"; // Wokwi default Wi-Fi SSID
const char* password = ""; // No password needed for Wokwi
DHT dht(DHTPIN, DHTTYPE);
String apiKey = "EPU4MHFG3HLF7XYO"; // Your ThingSpeak Write API Key
const char* server = "api.thingspeak.com";
void setup() {
Serial.begin(115200); // Start serial communication
WiFi.begin(ssid, password); // Connect to Wokwi Wi-Fi
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("Connected to WiFi.");
dht.begin(); // Start DHT sensor
}
void loop() {
// Read temperature and humidity from DHT22 sensor
float temperature = dht.readTemperature();
float humidity = dht.readHumidity();
if (isnan(temperature) || isnan(humidity)) {
Serial.println("Failed to read from DHT sensor!");
return;
}
// If connected to WiFi, send data to ThingSpeak
if (WiFi.status() == WL_CONNECTED) {
HTTPClient http;
String url = String("http://") + server + "/update?api_key=" + apiKey +
"&field1=" + String(temperature) + "&field2=" + String(humidity);
http.begin(url); // Start the HTTP connection
int httpResponseCode = http.GET(); // Send the HTTP GET request
if (httpResponseCode > 0) {
String response = http.getString();
Serial.println(httpResponseCode); // Print response code
Serial.println(response); // Print response from server
} else {
Serial.println("Error on HTTP request");
}
http.end(); // Free resources
}
delay(15000); // ThingSpeak has a rate limit of 15 seconds between updates
}
Loading
esp32-devkit-c-v4
esp32-devkit-c-v4