/* This simple project describes how to make an ultrasonic alarm system using Ultasonic Sensor (HC-SR04) and a buzzer.*/
// Firstly, the connections of the ultrasonic Sensor. Connect +5V and GND normally and trigger pin to 12 & echo pin to 13.
#define trigPin 12
#define echoPin 13
int Buzzer = 8; // Connect the buzzer pin to 8
int duration, distance; // to measure the distance and time taken
void setup() {
Serial.begin(9600);
// Define the output and input objects (devices)
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(Buzzer, OUTPUT);
}
void loop() {
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = (duration / 2) / 29.1;
// When distance is greater than or equal to 200 OR less than or equal to 0, the buzzer is off
if (distance >= 200 || distance <= 0) {
Serial.println("No object detected");
digitalWrite(Buzzer, LOW);
} else {
Serial.println("Object detected \n");
Serial.print("Distance = ");
Serial.print(distance); // prints the distance if it is between the range 0 to 200
tone(Buzzer, 400); // play a tone of 400Hz
}
}