#include <WiFi.h> // Include the WiFi library
#include "DHTesp.h" // Include the DHT sensor library
#include "ThingSpeak.h" // Include the ThingSpeak library
const int DHT_PIN = 15; // Define the pin connected to the DHT sensor
const int LED_PIN = 13; // Define the pin connected to the LED
const char* WIFI_NAME = "Wokwi-GUEST"; // Define your WiFi SSID
const char* WIFI_PASSWORD = ""; // Define your WiFi password
const int myChannelNumber = 2546305; // Define your ThingSpeak channel number
const char* myApiKey = "K8EZ827FJT1VE31L"; // Define your ThingSpeak API key
const char* server = "api.thingspeak.com"; // Define the ThingSpeak server
DHTesp dhtSensor; // Initialize a DHT object
WiFiClient client; // Initialize a WiFi client
void setup() {
Serial.begin(115200); // Initialize serial communication
dhtSensor.setup(DHT_PIN, DHTesp::DHT22); // Setup DHT sensor
pinMode(LED_PIN, OUTPUT); // Set LED pin as output
WiFi.begin(WIFI_NAME, WIFI_PASSWORD); // Connect to WiFi
while (WiFi.status() != WL_CONNECTED){ // Wait until connected
delay(1000);
Serial.println("Wifi not connected");
}
Serial.println("Wifi connected !"); // Indicate WiFi connection
Serial.println("Local IP: " + String(WiFi.localIP())); // Print local IP
WiFi.mode(WIFI_STA); // Set WiFi mode to station
ThingSpeak.begin(client); // Begin ThingSpeak client
}
void loop() {
TempAndHumidity data = dhtSensor.getTempAndHumidity(); // Read temperature and humidity
ThingSpeak.setField(1,data.temperature); // Set field 1 with temperature
ThingSpeak.setField(2,data.humidity); // Set field 2 with humidity
if (data.temperature > 35 || data.temperature < 12 || data.humidity > 70 || data.humidity < 40) {
digitalWrite(LED_PIN, HIGH); // Turn on LED if conditions met
}else{
digitalWrite(LED_PIN, LOW); // Turn off LED if conditions not met
}
int x = ThingSpeak.writeFields(myChannelNumber,myApiKey); // Write data to ThingSpeak
Serial.println("Temp: " + String(data.temperature, 2) + "°C"); // Print temperature
Serial.println("Humidity: " + String(data.humidity, 1) + "%"); // Print humidity
if(x == 200){
Serial.println("Data pushed successfully"); // Print success message if data pushed successfully
}else{
Serial.println("Push error" + String(x)); // Print error message if data push failed
}
Serial.println("---"); // Print separator
delay(10000); // Delay for 10 seconds before next iteration
}