#include <LCD_I2C.h>
#define TRIGGER_PIN 2 // Arduino pin tied to trigger pin on the ultrasonic sensor.
#define ECHO_PIN 3 // Arduino pin tied to echo pin on the ultrasonic sensor.
#define BUZZER_PIN 9 // Arduino pin tied to 1 of the pins on the speaker/buzzer.
#define E5_NOTE 659.25
#define E6_NOTE 1318.51
LCD_I2C lcd(0x27, 16, 2);
double ALARM[] = {
E5_NOTE, E6_NOTE
};
void setup() {
pinMode(TRIGGER_PIN, OUTPUT); // Set the trigger pin as an output:
pinMode(ECHO_PIN, INPUT); // Set the echo pin as an input:
lcd.begin();
lcd.backlight();
}
void loop() {
// Clear the trigger pin condition:
digitalWrite(TRIGGER_PIN, LOW);
delayMicroseconds(2);
// Sets the trigger pin to HIGH state for 10 microseconds:
digitalWrite(TRIGGER_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIGGER_PIN, LOW);
// Reads the echo pin, and returns the sound wave travel time in microseconds:
long duration = pulseIn(ECHO_PIN, HIGH);
// Calculate the distance:
long distance = duration * 0.034 / 2; // Speed of sound wave divided by 2 (go and back)
//Display the distance on the LCD screen:
lcd.setCursor(2, 0);
lcd.print("Distance: ");
lcd.print(distance);
// Set an alarm to ring if the person gets closer than desired distance:
if(distance < 25){
tone(BUZZER_PIN, ALARM, 100000);
lcd.setCursor(2, 1);
lcd.print("ALARM ON!");
}
else {
noTone(BUZZER_PIN);
lcd.clear();
}
delay(20); // Wait for 500 milliseconds before next loop for the next distance reading.
}