#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <ESP32Servo.h>
Servo motor1;
Servo motor2;
int pos = 0;
const int trigpin = 18;
const int echopin = 19;
const int photo_resistor = 36; // LDR on pin 36
LiquidCrystal_I2C lcd(0x27, 20, 4); // Adjust the I2C address if needed
int led1 = 5; // LED 1 connected to pin 5
int led2 = 27; // LED 2 connected to pin 27
double distancecm;
double duration;
double distanceinch;
void setup() {
//Serial.begin(9600);
pinMode(trigpin, OUTPUT);
pinMode(echopin, INPUT);
pinMode(led1, OUTPUT); // Define LED 1 pin as output
pinMode(led2, OUTPUT); // Define LED 2 pin as output
motor1.attach(12); // Attach servo to pin 12
motor2.attach(14); // Attach servo to pin 14
motor1.write(0); // Start motor1 at opposite direction (180 degrees)
motor2.write(180); // Start motor2 at opposite direction (0 degrees)
lcd.init(); // Initialize LCD with default settings (20x4)
lcd.clear(); // Clear the LCD at startup
lcd.setBacklight(1); // Turn on backlight
lcd.setCursor(0, 0);
lcd.print("Complete");
lcd.setCursor(0, 1);
lcd.print("Automation ");
delay(1000); // Wait for the startup message to show
lcd.clear();
}
void loop() {
// Measure distance using ultrasonic sensor
digitalWrite(trigpin, LOW);
delayMicroseconds(2);
digitalWrite(trigpin, HIGH);
delayMicroseconds(10);
digitalWrite(trigpin, LOW);
duration = pulseIn(echopin, HIGH);
distancecm = (duration * 0.034) / 2;
// If distance is greater than 10 cm, turn off the entire system
if (distancecm > 10) {
digitalWrite(led1, LOW); // Turn off LED 1
digitalWrite(led2, LOW); // Turn off LED 2
analogWrite(led1, 0); // Ensure no brightness for LED 1
analogWrite(led2, 0); // Ensure no brightness for LED 2
motor1.write(90); // Stop motor1
motor2.write(90); // Stop motor2
lcd.clear(); // Clear LCD
lcd.setCursor(0, 0);
lcd.print("System Off");
return; // Exit the loop to stop everything
}
// Read the LDR value (light intensity)
int photo = analogRead(photo_resistor);
// Control LED based on distance
if (distancecm < 100) {
lcd.setCursor(0, 0);
lcd.print("LED: ON "); // Display LED status
} else {
lcd.setCursor(0, 0);
lcd.print("LED: OFF "); // Display LED status
}
// Adjust LED brightness based on LDR sensor value
int brightness = map(photo, 0, 4095, 0, 255); // Map LDR value to PWM range
analogWrite(led1, brightness); // Set brightness of LED 1
analogWrite(led2, brightness); // Set brightness of LED 2
// Display LDR value on the second row of the LCD
lcd.setCursor(0, 1);
lcd.print("LDR: ");
lcd.print(photo);
delay(500); // Delay for 500 ms to avoid screen flickering
/*if (Serial.available() > 0) {
String message = Serial.readStringUntil('\n');
message.trim();
if (message == "SUCCESS") {
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Access Granted");
lcd.setCursor(0, 1);
lcd.print("Gates - OPENING");
motoropen();
delay(400);
}
}*/
}