#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#define TRIGGER_PIN 3 // Ultrasonic sensor trigger pin
#define ECHO_PIN 2 // Ultrasonic sensor echo pin
#define BUZZER_PIN 4 // Piezo buzzer pin
#define LED_RED_PIN 5 // Red LED pin
#define LED_YELLOW_PIN 6 // Yellow LED pin
#define LED_GREEN_PIN 7 // Green LED pin
#define LCD_ADDRESS 0x27 // I2C address of the LCD
#define LCD_COLUMNS 16 // Number of LCD columns
#define LCD_ROWS 2 // Number of LCD rows
LiquidCrystal_I2C lcd(LCD_ADDRESS, LCD_COLUMNS, LCD_ROWS);
void setup() {
pinMode(TRIGGER_PIN, OUTPUT);
pinMode(BUZZER_PIN, OUTPUT);
pinMode(LED_RED_PIN, OUTPUT);
pinMode(LED_YELLOW_PIN, OUTPUT);
pinMode(LED_GREEN_PIN, OUTPUT);
lcd.begin(LCD_COLUMNS, LCD_ROWS);
lcd.backlight();
Serial.begin(9600);
}
void loop() {
long duration;
int distance;
// Trigger the ultrasonic sensor
digitalWrite(TRIGGER_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIGGER_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIGGER_PIN, LOW);
// Measure the echo duration to calculate the distance
duration = pulseIn(ECHO_PIN, HIGH);
distance = duration * 0.034 / 2; // Calculate distance in centimeters
// Display the distance on the LCD
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Distance: ");
lcd.print(distance);
lcd.print(" cm");
// Check the distance and provide feedback using LEDs and buzzer
if (distance <= 20) {
// Play a tone and turn on the red LED for close proximity
tone(BUZZER_PIN, 1000, 200);
digitalWrite(LED_RED_PIN, HIGH);
digitalWrite(LED_YELLOW_PIN, LOW);
digitalWrite(LED_GREEN_PIN, LOW);
} else if (distance <= 50) {
// Play a tone and turn on the yellow LED for moderate proximity
tone(BUZZER_PIN, 800, 200);
digitalWrite(LED_RED_PIN, LOW);
digitalWrite(LED_YELLOW_PIN, HIGH);
digitalWrite(LED_GREEN_PIN, LOW);
} else {
// Turn on the green LED for safe distance
noTone(BUZZER_PIN);
digitalWrite(LED_RED_PIN, LOW);
digitalWrite(LED_YELLOW_PIN, LOW);
digitalWrite(LED_GREEN_PIN, HIGH);
}
delay(200); // Adjust the delay as needed
}