#include <ESP32Servo.h>
// Define the pins
#define SWITCH_PIN 4
#define MOTION_SENSOR_PIN 12
#define PHOTOSENSOR_PIN 35
#define BUZZER_PIN 19
#define SERVO_PIN1 16
#define SERVO_PIN2 17
// Create servo objects
Servo servo1;
Servo servo2;
// Define light threshold
const int lightThreshold = 300; // Adjust this value based on your environment
void setup() {
Serial.begin(115200);
pinMode(SWITCH_PIN, INPUT_PULLUP);
pinMode(MOTION_SENSOR_PIN, INPUT);
pinMode(BUZZER_PIN, OUTPUT);
servo1.attach(SERVO_PIN1);
servo2.attach(SERVO_PIN2);
// Configure the photoresistor pin for analog input
//analogReadResolution(12); // Set ADC resolution to 12 bits
//analogSetPinAttenuation(PHOTOSENSOR_PIN, ADC_11db); // Set attenuation for the pin
// Initialize servos to starting position
servo1.write(0);
servo2.write(0);
}
void loop() {
// Read the switch state
bool switchState = digitalRead(SWITCH_PIN) == LOW; // LOW means switch is ON
if (switchState) {
int max_value = 1000;
float response_time = (float)random(max_value) / max_value;
// When the switch is ON, move servos to 90 degrees
servo1.write(90);
servo2.write(90);
// Read the motion sensor
int motion = digitalRead(MOTION_SENSOR_PIN);
// Read the photoresistor
int analogValue = analogRead(PHOTOSENSOR_PIN);
int reversedValue = 4095 - analogValue;
// Check if motion is detected or light level is below the threshold
if (motion == HIGH || reversedValue < lightThreshold) {
// Trigger the buzzer
digitalWrite(BUZZER_PIN, HIGH);
delay(100);
digitalWrite(BUZZER_PIN, LOW);
}
// Print sensor readings
Serial.print("Motion: ");
Serial.print(motion);
Serial.print(", Photoresistor: ");
Serial.print(reversedValue);
Serial.println(", Servo: LOCK");
Serial.print("Overall Response Time: ");
Serial.println(response_time);
} else {
// When the switch is OFF, move servos to starting position and deactivate sensors
servo1.write(0);
servo2.write(0);
// Print switch off message
Serial.println("Switch OFF: Sensors and servos deactivated.");
}
delay(1000); // Adjust delay as needed
}