#include <Servo.h>
#include <LiquidCrystal_I2C.h> // Include the LCD Library
// --- Configuration ---
Servo distanceGauge;
// I2C LCD Address is usually 0x27 in Wokwi
LiquidCrystal_I2C lcd(0x27, 16, 2);
// Pin Definitions
const int echoPin = 2;
const int trigPin = 3;
const int greenPin = 5;
const int redPin = 6;
const int servoPin = 9;
const int buzzerPin = 10;
const int potPin = A0;
// Variables
long duration;
int distance;
int safetyLimit;
void setup() {
Serial.begin(9600);
// 1. Setup Pins
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(redPin, OUTPUT);
pinMode(greenPin, OUTPUT);
pinMode(buzzerPin, OUTPUT);
// 2. Attach Servo
distanceGauge.attach(servoPin);
// 3. Initialize LCD
lcd.init();
lcd.backlight();
// Show a startup message
lcd.setCursor(0, 0); // Column 0, Row 0
lcd.print("System Starting");
lcd.setCursor(0, 1); // Column 0, Row 1
lcd.print("Please Wait...");
delay(2000);
lcd.clear();
// Draw static labels (to prevent screen flickering)
lcd.setCursor(0, 0);
lcd.print("Dist: cm");
lcd.setCursor(0, 1);
lcd.print("Limit: cm");
}
void loop() {
// --- A. Read Potentiometer (Limit) ---
int potValue = analogRead(potPin);
safetyLimit = map(potValue, 0, 1023, 10, 100);
// --- B. Read Ultrasonic Sensor (Distance) ---
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = duration * 0.034 / 2;
// --- C. Update Servo ---
int angle = map(constrain(distance, 0, 200), 0, 200, 0, 180);
distanceGauge.write(angle);
// --- D. Update LCD ---
// We only print the numbers to avoid clearing the whole screen (prevents flicker)
// Row 0: Real Distance
lcd.setCursor(6, 0);
lcd.print(" "); // Clean previous number
lcd.setCursor(6, 0);
lcd.print(distance);
// Row 1: Safety Limit
lcd.setCursor(7, 1);
lcd.print(" "); // Clean previous number
lcd.setCursor(7, 1);
lcd.print(safetyLimit);
// --- E. Logic: Safe vs Danger ---
if (distance < safetyLimit) {
// === DANGER ===
digitalWrite(redPin, HIGH);
digitalWrite(greenPin, LOW);
tone(buzzerPin, 1000);
// Optional: Show "!" on LCD to warn visually
lcd.setCursor(15, 0);
lcd.print("!");
}
else {
// === SAFE ===
digitalWrite(redPin, LOW);
digitalWrite(greenPin, HIGH);
noTone(buzzerPin);
// Clear warning
lcd.setCursor(15, 0);
lcd.print(" ");
}
delay(150); // Slightly slower update to make LCD readable
}