#include <Wire.h>
#include <LiquidCrystal_I2C.h>
// Initialize the LCD (I2C address: 0x27, 16 columns, 2 rows)
LiquidCrystal_I2C lcd(0x27, 16, 2);
// Defines pins numbers
const int trigPin = 9;
const int echoPin = 10;
const int buzzerPin = 3; // Buzzer connected to pin 3
// Defines variables
long echoDuration; // Changed variable name to avoid conflict
int distance;
const int thresholdDistance = 20; // Distance in cm to trigger the alarm
void setup() {
// Set up the pins
pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
pinMode(echoPin, INPUT); // Sets the echoPin as an Input
pinMode(buzzerPin, OUTPUT); // Sets the buzzerPin as an Output
// Initialise Serial Monitor
Serial.begin(9600);
// Initialise the LCD
lcd.init();
lcd.backlight();
lcd.setCursor(0, 0);
lcd.print("Distance: ");
}
void loop() {
// Clears the trigPin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Sets the trigPin on HIGH state for 10 microseconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Reads the echoPin, returns the sound wave travel time in microseconds
echoDuration = pulseIn(echoPin, HIGH);
// Calculating the distance
distance = echoDuration * 0.034 / 2; // Speed of sound wave divided by 2 (go-and-back)
// Prints the distance on the Serial Monitor
Serial.print("Distance: ");
Serial.println(distance);
// Display the distance on the LCD
lcd.setCursor(10, 0); // Move cursor to position
lcd.print(" "); // Clear previous value
lcd.setCursor(10, 0);
lcd.print(distance);
lcd.print("cm");
// Checks if the distance is below the threshold
if (distance < thresholdDistance) {
// Generate intermittent sound
tone(buzzerPin, 1000); // 1000 Hz frequency
delay(300); // Sound on for 300 ms
noTone(buzzerPin); // Turn off sound
delay(300); // Sound off for 300 ms
// Update LCD with alarm message
lcd.setCursor(0, 1); // Second row for alarm message
lcd.print("ALARM! Too Close");
} else {
noTone(buzzerPin); // Turn off the sound if the distance is safe
lcd.setCursor(0, 1); // Clear alarm message
lcd.print(" ");
}
delay(100); // Delay to avoid excessive updates
}
Comments
0 B
|👍
/👎
0 B
|👍
/👎