Arduino – Ultrasonic Distance Sensor Audible Alert

Description:

This project creates a distance sensor alarm like the backup distance buzzers in cars. The closer an object gets to the sensor the faster the buzzer beeps. This project can be connected to a battery pack and work without being connected to a computer.

Parts:

  • Arduino Uno
  • Ultrasonic Distance Sensor
  • Piezo Buzzer
  • Breadboard
  • Wires

Code:

  • This is a continuation of the Arduino – Ultrasonic Distance Sensor project.
#define buzzer 7 #define trigPin 8 #define echoPin 9 long duration; float distanceCM; float distanceInch; void setup() { pinMode(buzzer, OUTPUT); pinMode(trigPin, OUTPUT); pinMode(echoPin, INPUT); Serial.begin(9600); } void loop() { digitalWrite(trigPin, LOW); delayMicroseconds(2); digitalWrite(trigPin, HIGH); delayMicroseconds(10); digitalWrite(trigPin, LOW); duration = pulseIn(echoPin, HIGH); distanceCM = duration * 0.034 /2; distanceInch = duration * 0.0133 /2; Serial.print("Distance: "); Serial.print(distanceCM); Serial.print(" CM - "); Serial.print(distanceInch); Serial.println(" Inches"); if(distanceInch < 20){ digitalWrite(buzzer, HIGH); delay(50); digitalWrite(buzzer, LOW); delay(distanceInch * 10); } }
Code language: PHP (php)

Code with Comments:

//define buzzer pin as digital pin 7 #define buzzer 7 #define trigPin 8 #define echoPin 9 long duration; float distanceCM; float distanceInch; void setup() { pinMode(buzzer, OUTPUT); pinMode(trigPin, OUTPUT); pinMode(echoPin, INPUT); Serial.begin(9600); } void loop() { digitalWrite(trigPin, LOW); delayMicroseconds(2); digitalWrite(trigPin, HIGH); delayMicroseconds(10); digitalWrite(trigPin, LOW); duration = pulseIn(echoPin, HIGH); distanceCM = duration * 0.034 /2; distanceInch = duration * 0.0133 /2; Serial.print("Distance: "); Serial.print(distanceCM); Serial.print(" CM - "); Serial.print(distanceInch); Serial.println(" Inches"); //use an if statement for the buzzer to limit the distance for detection. //IF distance is less than 20 inches turn buzzer on if(distanceInch < 20){ digitalWrite(buzzer, HIGH); delay(50); digitalWrite(buzzer, LOW); //delay loop for distance in inches x 10. This gives pause that changes the beeps delay(distanceInch * 10); } }
Code language: PHP (php)