#include <Adafrut_Sensor.h>
#include <DHT.h>
#include <WiFi.h>
#include <ThingSpeak.h>
#define DHTPIN 4 // Define the pin to which the DHT sensor is connected
#define DHTTYPE DHT22 // Use DHT22 sensor, change to DHT11 if you're using that
one
const char *ssid = "Wokwi-GUEST"; // Your WiFi network SSID
const char *password = ""; // Your WiFi password
const char *thingSpeakApiKey = "
QS6YHDUWZ2MABHA3"; // Your ThingSpeak API Key
const long updateInterval = 15000; // Update interval in milliseconds (15
seconds)
DHT dht(DHTPIN, DHTTYPE);
WiFiClient client;
void setup() {
Serial.begin(115200);
dht.begin();
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("Connected to WiFi");
ThingSpeak.begin(client);
}
void loop() {
// Delay for a few seconds to avoid flooding the sensor
delay(2000);
// Read temperature and humidity data from the sensor
float humidity = dht.readHumidity();
float temperature = dht.readTemperature();
// Check if any reading failed and exit if so
if (isnan(humidity) || isnan(temperature)) {
Serial.println("Failed to read from DHT sensor!");
return;
}
// Print temperature and humidity to the Serial Monitor
Serial.print("Temperature: ");
Serial.print(temperature);
Serial.println(" °C");
Serial.print("Humidity: ");
Serial.print(humidity);
Serial.println(" %");
// Update ThingSpeak channel with the sensor data
ThingSpeak.writeField(2267508, 1, temperature, thingSpeakApiKey);
ThingSpeak.writeField(2267508, 2, humidity, thingSpeakApiKey);
Serial.println("Data sent to ThingSpeak.");
delay(updateInterval);
}