/*
* This ESP32 code is created by esp32io.com
*
* This ESP32 code is released in the public domain
*
* For more detail (instruction and wiring diagram), visit https://esp32io.com/tutorials/esp32-dht22-relay
*/
#include <DHT.h>
#define DHT22_PIN 23 // ESP32 pin GPIO23 connected to DHT22
#define RELAY_PIN 18 // ESP32 pin GPIO18 connected to relay
#define DHT_SENSOR_TYPE DHT22
#define TEMP_UPPER_THRESHOLD 30 // upper temperature threshold
#define TEMP_LOWER_THRESHOLD 15 // lower temperature threshold
DHT dht22(DHT22_PIN, DHT_SENSOR_TYPE);
void setup() {
Serial.begin(9600); // initialize serial
dht22.begin(); // initialize the DHT sensor
}
void loop() {
float temperature = dht22.readTemperature();; // read temperature in Celsius
if (isnan(temperature)) {
Serial.println("Failed to read from DHT22 sensor!");
} else {
if (temperature > TEMP_UPPER_THRESHOLD) {
Serial.println("Turn the relay on");
digitalWrite(RELAY_PIN, HIGH); // turn on
} else if (temperature < TEMP_LOWER_THRESHOLD) {
Serial.println("Turn the relay off");
digitalWrite(RELAY_PIN, LOW); // turn off
}
}
// wait a 1 seconds between readings
delay(1000);
}