#include <Wire.h>
#include <LiquidCrystal_I2C.h>
// defines pin numbers
const int trigPin = 9;
const int echoPin = 10;
const int buzzer = 11;
const int redLedPin = 13;
const int greenLedPin = 8;
const int stopButtonPin = 4; // Stop button pin
// Set the LCD address to 0x27 for a 16 chars and 2 line display
LiquidCrystal_I2C lcd(0x27, 16, 2);
// defines variables
long duration;
int distance;
bool stoppedManually = false; // Flag for manual stop
void setup() {
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(buzzer, OUTPUT);
pinMode(redLedPin, OUTPUT);
pinMode(greenLedPin, OUTPUT);
pinMode(stopButtonPin, INPUT_PULLUP); // Set the stopButtonPin as an INPUT_PULLUP
// Initialize the LCD
lcd.init();
lcd.backlight();
Serial.begin(9600);
}
void loop() {
// Read the state of the stop button
bool stopButtonState = digitalRead(stopButtonPin) == LOW; // Active LOW button
// Only allow the stop button to work if the distance is less than 100
if (stopButtonState && distance <= 100) {
stoppedManually = true;
}
// Clears the trigPin conditionally if not manually stopped
if (!stoppedManually) {
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Sets the trigPin on HIGH state for 10 micro seconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Reads the echoPin, returns the sound wave travel time in microseconds
duration = pulseIn(echoPin, HIGH);
// Calculating the distance
distance = duration * 0.034 / 2;
}
// Display the distance on the LCD
lcd.setCursor(0, 0);
lcd.print("Dist: ");
lcd.print(distance);
lcd.print(" cm ");
// Conditions to turn the LEDs and buzzer on/off based on the distance
if (!stoppedManually && distance <= 100) {
digitalWrite(greenLedPin, HIGH);
digitalWrite(buzzer, HIGH);
} else {
digitalWrite(greenLedPin, LOW);
digitalWrite(buzzer, LOW);
}
// Handle red LED and LCD message for critical distance
if (!stoppedManually && distance > 200) {
digitalWrite(redLedPin, HIGH);
lcd.setCursor(0, 1);
lcd.print("All Good! ");
} else {
digitalWrite(redLedPin, LOW);
}
// Handle LCD message for manual stop
if (stoppedManually) {
lcd.setCursor(0, 1);
lcd.print("Manual Stopped "); // Clear the rest of the line with spaces
} else if (distance <= 100) {
lcd.setCursor(0, 1);
lcd.print("Critical! ");
} else {
lcd.setCursor(0, 1);
lcd.print(" "); // Clear the second line
}
// Prints the distance on the Serial Monitor
Serial.print("Distance: ");
Serial.println(distance);
}