#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27, 16, 2); // I2C address 0x27
int trigPin = 13; // TRIG pin
int echoPin = 12; // ECHO pin
float duration_us, distance_cm;
const int buzzerPin = 10;
//const int buttonPin = 7; //
const int buttonPin = 2;
long duration;
int distance;
bool alertEnabled = true;
bool prev_alertEnabled = true;
void buttonISR() {
if(prev_alertEnabled == alertEnabled)
{
alertEnabled = !alertEnabled;
delay(500);
}
}
void setup() {
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(buzzerPin, OUTPUT);
pinMode(buttonPin, INPUT_PULLUP); // Using internal pull-up resistor
lcd.init();
lcd.backlight();
lcd.setCursor(0, 0);
lcd.print("Distance:");
Serial.begin(9600);
attachInterrupt(digitalPinToInterrupt(buttonPin), buttonISR, LOW);
}
void loop()
{
// Clear the trigPin by setting it LOW
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Set the trigPin HIGH for 10 microseconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Read the echoPin and calculate the distance
duration = pulseIn(echoPin, HIGH);
distance = duration * 0.034 / 2;
// Display the distance on the LCD
lcd.setCursor(0, 1);
lcd.print(" "); // Clear previous data
lcd.setCursor(0, 1);
lcd.print(distance);
lcd.print(" cm");
// Check the distance and activate the buzzer if alert is enabled
if (alertEnabled == false) {
lcd.setCursor(0, 1);
lcd.print("Off ");
}
buzzerControl();
delay(500); // Wait for a short period before the next measurement
prev_alertEnabled = alertEnabled;
}
void buzzerControl(){
if (alertEnabled && distance < 20) { // You can adjust the threshold distance
digitalWrite(buzzerPin, HIGH);
Serial.println("buzzer ON ");
} else {
digitalWrite(buzzerPin, LOW);
Serial.println("buzzer OFF ");
}
delay(500);
}