#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <ESP32Servo.h>
Servo motor1;
Servo motor2;
int pos = 180;
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() {
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(pos); // Start motor1 at opposite direction (180 degrees)
motor2.write(pos); // 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();
Serial.begin(115200);
}
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(270); // 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)
i int photo = 0;
int numReadings = 10;
for (int i = 0; i < numReadings; i++) {
photo += analogRead(photo_resistor);
delay(10); // Delay between readings
}
photo /= numReadings; // Average the readings
// Map LDR value to PWM range and constrain it
int brightness = map(photo, 0, 4095, 0, 255);
brightness = constrain(brightness, 0, 255); // Ensure it's within PWM range
// Control LED brightness based on LDR value
ledcWrite(led1, brightness);
ledcWrite(led2, brightness);
// 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
}
// Display LDR value on the LCD
lcd.setCursor(0, 1);
lcd.print("LDR: ");
lcd.print(photo);
// Print LDR value to Serial Monitor for debugging
Serial.print("LDR value: ");
Serial.println(photo);
Serial.print("Distance (cm): ");
Serial.println(distancecm);
delay(500); // Delay for 500 ms to avoid screen flickering
}
}