int LDRPin = 13; // LDR connected to analog pin A0
int LEDPin = 2; // LED connected to digital pin 13
int threshold = 500; // Threshold value for light level (adjust as needed)
#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 20// upper temperature threshold
#define TEMP_LOWER_THRESHOLD 20 // lower temperature threshold
DHT dht22(DHT22_PIN, DHT_SENSOR_TYPE);
void setup() {
pinMode(LDRPin, INPUT); // Set LDR pin as input
pinMode(LEDPin, OUTPUT); // Set LED pin as output
Serial.begin(9600); // Initialize serial communication for debugging
Serial.begin(9600); // initialize serial
dht22.begin(); // initialize the DHT sensor
}
void loop() {
int LDRValue = analogRead(LDRPin); // Read the value from the LDR
Serial.println(LDRValue); // Print the LDR value to the Serial Monitor for debugging
if (LDRValue < threshold) {
// If the light level is below the threshold, turn on the LED
digitalWrite(LEDPin, HIGH);
} else {
// If the light level is above the threshold, turn off the LED
digitalWrite(LEDPin, LOW);
}
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
}
}
delay(100); // Small delay for stability
}