#include <Wire.h>
#include <LiquidCrystal_I2C.h>
// Define pin connections for ultrasonic sensor
const int trigPin = 10;
const int echoPin = 9;
// Define LEDs
const int redLed = 12;
const int yellowLed = 13;
// Initialize LCD
LiquidCrystal_I2C lcd1(0x27, 16, 2); // LCD1 address and size
LiquidCrystal_I2C lcd2(0x3F, 16, 2); // LCD2 address and size (might vary depending on your I2C address)
void setup() {
// Start serial communication for debugging
Serial.begin(9600);
// Initialize ultrasonic sensor pins
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
// Initialize LED pins
pinMode(redLed, OUTPUT);
pinMode(yellowLed, OUTPUT);
// Initialize LCD displays
lcd1.begin(16, 2);
lcd2.begin(16, 2);
lcd1.print("Distance Sensor");
lcd2.print("Waiting...");
delay(2000); // Delay for initialization
}
void loop() {
// Trigger the ultrasonic sensor to send out a pulse
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Measure the time it takes for the pulse to return
long duration = pulseIn(echoPin, HIGH);
// Calculate the distance in centimeters
long distance = duration * 0.034 / 2; // Speed of sound is 0.034 cm/us, divided by 2 for round-trip
// Display distance on both LCDs
lcd1.clear();
lcd1.setCursor(0, 0);
lcd1.print("Distance:");
lcd2.clear();
lcd2.setCursor(0, 0);
lcd2.print("Dist: ");
lcd2.print(distance);
lcd2.print(" cm");
// LED control based on distance
if (distance < 10) {
// If the object is too close (less than 10 cm)
digitalWrite(redLed, HIGH); // Turn on red LED
digitalWrite(yellowLed, LOW); // Turn off yellow LED
} else if (distance >= 10 && distance < 50) {
// If the object is at a safe distance (between 10 cm and 50 cm)
digitalWrite(redLed, LOW); // Turn off red LED
digitalWrite(yellowLed, HIGH); // Turn on yellow LED
} else {
// If the object is far enough
digitalWrite(redLed, LOW); // Turn off red LED
digitalWrite(yellowLed, LOW); // Turn off yellow LED
}
// Delay before next measurement
delay(500);
}