#include <OneWire.h>
#include <DallasTemperature.h>
// Define the pin numbers
const int LDR_PIN = 34; // Pin connected to LDR (photoresistor)
const int LED_PIN = 26; // Pin connected to LED
const int BUZZER_PIN = 25; // Pin connected to buzzer
const int ONE_WIRE_BUS = 15; // Pin connected to DS18B20 temperature sensor
// Define the threshold for LDR value (in lux)
const int LDR_THRESHOLD = 350; // Threshold value for turning on the LED and buzzer
const float TEMP_THRESHOLD = 55.0; // Threshold temperature (in Celsius)
// Initialize OneWire and DallasTemperature instances
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);
void setup() {
// Initialize the serial monitor for debugging
Serial.begin(115200);
// Set the LED and buzzer pins as outputs
pinMode(LED_PIN, OUTPUT);
pinMode(BUZZER_PIN, OUTPUT);
// Ensure LED and buzzer are off initially
digitalWrite(LED_PIN, LOW);
digitalWrite(BUZZER_PIN, LOW);
// Start communication with the DS18B20 sensor
sensors.begin();
}
void loop() {
// Read the LDR value (analog input)
int ldrValue = analogRead(LDR_PIN);
// Convert LDR value to Lux (simplified conversion)
float voltage = (ldrValue / 4095.0) * 3.3; // ESP32's max ADC value is 4095, and Vcc is 3.3V
float lux = voltage * 1000; // Approximation: Voltage * factor to get Lux value
// Print the LDR value and lux to the Serial Monitor for debugging
Serial.print("LDR Value: ");
Serial.print(ldrValue);
Serial.print(" | Lux: ");
Serial.println(lux);
// Request temperature reading from DS18B20
sensors.requestTemperatures();
float temperature = sensors.getTempCByIndex(0); // Get temperature in Celsius from the first sensor
// Print the temperature to the Serial Monitor
Serial.print("Temperature: ");
Serial.print(temperature);
Serial.println(" °C");
// Check if the LDR value (in Lux) exceeds the threshold or temperature exceeds the threshold
if (lux < LDR_THRESHOLD || temperature > TEMP_THRESHOLD) {
// If Lux or temperature is above threshold, turn on the LED and buzzer
digitalWrite(LED_PIN, HIGH); // Turn on the LED
digitalWrite(BUZZER_PIN, HIGH); // Turn on the buzzer
Serial.println("ALERT: Lux or temperature exceeds threshold! LED and Buzzer ON.");
} else {
// If Lux and temperature are below threshold, turn off the LED and buzzer
digitalWrite(LED_PIN, LOW); // Turn off the LED
digitalWrite(BUZZER_PIN, LOW); // Turn off the buzzer
}
// Delay for a short period before reading again
delay(500); // Half second delay
}