#include <Wire.h>
#include <LiquidCrystal_I2C.h>
// Pins for Ultrasonic Sensor
const int trigPin = 9;
const int echoPin = 10;
// Pins for LEDs
const int led1 = 11; // LED 1
const int led2 = 12; // LED 2
const int led3 = 13; // LED 3
// Pin for Motor (simulated by LED)
const int motorPin = 3;
// I2C LCD
LiquidCrystal_I2C lcd(0x27, 16, 2);
void setup() {
// Initialize the Serial Monitor
Serial.begin(9600);
// Initialize the LCD
lcd.begin(16, 2);
lcd.print("Distance:");
// Set the Ultrasonic Sensor pins
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
// Set the LED pins
pinMode(led1, OUTPUT);
pinMode(led2, OUTPUT);
pinMode(led3, OUTPUT);
// Set the Motor pin
pinMode(motorPin, OUTPUT);
}
void loop() {
// Clear the trigPin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Set the trigPin on HIGH state for 10 microseconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Read the echoPin, returns the sound wave travel time in microseconds
long duration = pulseIn(echoPin, HIGH);
// Calculate the distance
int distance = duration * 0.034 / 2;
// Display the distance on the LCD
lcd.setCursor(0, 1);
lcd.print(" "); // Clear previous distance
lcd.setCursor(0, 1);
lcd.print(distance);
lcd.print(" cm");
// Turn on/off the motor based on distance
if (distance > 300) {
digitalWrite(motorPin, HIGH); // Turn on the motor
digitalWrite(led1, LOW);
digitalWrite(led2, LOW);
digitalWrite(led3, HIGH); // Green LED on
} else if (distance < 200) {
digitalWrite(motorPin, LOW); // Turn off the motor
digitalWrite(led1, HIGH); // Red LED on
digitalWrite(led2, LOW);
digitalWrite(led3, LOW);
} else {
digitalWrite(motorPin, LOW); // Turn off the motor
digitalWrite(led1, LOW);
digitalWrite(led2, HIGH); // Yellow LED on
digitalWrite(led3, LOW);
}
// Print the distance to the Serial Monitor (for debugging)
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
// Wait for a while before the next loop
delay(500);
}