#include "DHT.h"
#include <WiFi.h>
#include <HTTPClient.h>
// adds the sensor library
#define DHTPIN 15
//sensor data is connected to GPIO 15
#define DHTTYPE DHT22
const int greenLed = 18;
const int redLed = 19;
const int buzzer = 21;
const char* ssid = "Wokwi-GUEST";
const char* password = "";
String apiKey = "2CL5HW30YLELBGRM";
const char* server = "https://api.thingspeak.com/update";
DHT dht(DHTPIN, DHTTYPE);
void setup() {
Serial.begin(9600);
dht.begin();
//STARTS the sensor
pinMode(greenLed, OUTPUT);
pinMode(redLed, OUTPUT);
pinMode(buzzer, OUTPUT);
Serial.print("Connecting to WiFi");
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println();
Serial.println("WiFi connected!");
}
void loop() {
float temperature = dht.readTemperature();
//reads the temperature
float humidity = dht.readHumidity();
//reads humidity
Serial.print("Temperature: ");
Serial.print(temperature);
Serial.println(" °C");
Serial.print("Humidity: ");
Serial.print(humidity);
Serial.println(" %");
if (temperature >= 32){
digitalWrite(greenLed, LOW);
digitalWrite(redLed, HIGH);
digitalWrite(buzzer, HIGH);
Serial.println("Status: Critically hot - buzzer activated");
//if temp is more than or equal to 32 on red led and buzzer.
}
else if (temperature >= 25){
digitalWrite(greenLed, LOW);
digitalWrite(redLed, HIGH);
digitalWrite(buzzer, LOW);
Serial.println("Status: Warning - high temperature");
//if temperature is more than 25 on red led light.
}
else if (temperature <= 0){
digitalWrite(greenLed, LOW);
digitalWrite(redLed, HIGH);
digitalWrite(buzzer, HIGH);
Serial.println("Status: Critically cold - buzzer activated");
//if temp is less than or equal to 0 on red led and buzzer.
}
else if (temperature <= 10){
digitalWrite(greenLed, LOW);
digitalWrite(redLed, HIGH);
digitalWrite(buzzer, LOW);
Serial.println("Status: Warning - low temperature");
//if temperature is less than or equal to 10 on redlight.
}
else {
digitalWrite(greenLed, HIGH);
digitalWrite(redLed, LOW);
digitalWrite(buzzer, LOW);
Serial.println("Status: Normal environment");
//otherwise on green led light.
}
Serial.println("-----------------");
if (WiFi.status() == WL_CONNECTED) {
// if wifi is connected it sends temperature and humidity to ThingSpeak.
HTTPClient http;
//builds the web request URL
String url = String(server) + "?api_key=" + apiKey +
"&field1=" + String(temperature) +
"&field2=" + String(humidity);
http.begin(url);
int httpResponseCode = http.GET();
Serial.print("HTTP Response code: ");
Serial.println(httpResponseCode);
http.end();
}
delay(2000);
//waits 2 secs because DHT sensors shouldnt read too quickly.
}