#include <DHT.h>
#define LIGHT_SENSOR_PIN 4 // ESP32 pin GPIO4 (ADC0)
#define PIR_SENSOR_PIN 5 // Replace 5 with the actual pin number for PIR sensor
#define BUZZER_PIN 13 // Pin connected to the buzzer
#define TRIG_PIN 26 // Trigger pin of ultrasonic sensor (GPIO16)
#define ECHO_PIN 27 // Echo pin of ultrasonic sensor (GPIO17)
#define DISTANCE_THRESHOLD 30 // Distance threshold in centimeters for object detection
#define DHT_PIN 2 // Pin connected to DHT sensor (GPIO14)
#define DHT_TYPE DHT22 // DHT sensor type
DHT dht(DHT_PIN, DHT_TYPE);
void setup() {
Serial.begin(9600);
pinMode(PIR_SENSOR_PIN, INPUT);
pinMode(BUZZER_PIN, OUTPUT); // Initialize buzzer pin as output
pinMode(TRIG_PIN, OUTPUT); // Initialize ultrasonic sensor trigger pin as output
pinMode(ECHO_PIN, INPUT); // Initialize ultrasonic sensor echo pin as input
dht.begin(); // Initialize DHT sensor
}
void loop() {
int analogValue = analogRead(LIGHT_SENSOR_PIN);
bool motionDetected = false;
bool objectDetected = false;
// Check PIR sensor for motion detection
if (digitalRead(PIR_SENSOR_PIN) == HIGH) {
Serial.println("Motion detected by PIR sensor!");
motionDetected = true;
soundBuzzer(); // Function to sound the buzzer
}
// Check ultrasonic sensor for object detection
long duration, distance;
digitalWrite(TRIG_PIN, LOW); // Ensure the trigger pin is low
delayMicroseconds(2); // Short delay
digitalWrite(TRIG_PIN, HIGH); // Send 10 microsecond pulse to trigger
delayMicroseconds(10); // Delay
digitalWrite(TRIG_PIN, LOW); // Turn off trigger pulse
duration = pulseIn(ECHO_PIN, HIGH); // Read echo pulse
distance = duration * 0.034 / 2; // Calculate distance in centimeters
if (distance <= DISTANCE_THRESHOLD) {
Serial.print("Object detected at ");
Serial.print(distance);
Serial.println(" cm");
objectDetected = true;
// Check temperature with DHT sensor
float temperature = dht.readTemperature(); // Read temperature in Celsius
if (!isnan(temperature) && temperature > 30.0) { // Check if temperature is valid and high
soundHighTemperatureTone(); // Function to sound music-like tone for high temperature
} else {
soundBuzzer(); // Default function to sound the buzzer
}
}
// Output analog light value
Serial.print("Analog Value = ");
Serial.print(analogValue);
if (analogValue < 40) {
Serial.println(" => Dark");
} else if (analogValue < 800) {
Serial.println(" => Dim");
} else if (analogValue < 2000) {
Serial.println(" => Light");
} else if (analogValue < 3200) {
Serial.println(" => Bright");
} else {
Serial.println(" => Very bright");
}
delay(500);
}
void soundBuzzer() {
tone(BUZZER_PIN, 1500); // Sound the buzzer at 1500 Hz
delay(1000); // Tone duration
noTone(BUZZER_PIN); // Ensure buzzer is silent
}
void soundHighTemperatureTone() {
tone(BUZZER_PIN, 2000); // Sound a higher pitch tone (example)
delay(200); // Tone duration
noTone(BUZZER_PIN); // Ensure buzzer is silent
}