firmwareMIT
Arduino Uno: distance alarm
breadboardhub/arduino-distance-alarm
arduinounoultrasonicbuzzer
B
Mike M
v1.0.0 · UpdatedNov 24, 2026 ·0 downloads ·0 forks
Arduino sketchOpen in the Arduino playground
// Distance alarm: the HC-SR04 measures how far away something is.
// The buzzer beeps faster as it gets closer. The distance prints to serial.
const int TRIG = 9;
const int ECHO = 10;
const int BUZZER = 8;
void setup() {
Serial.begin(9600);
pinMode(TRIG, OUTPUT);
pinMode(ECHO, INPUT);
}
void loop() {
// A 10 microsecond pulse on TRIG sends a ping.
digitalWrite(TRIG, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG, LOW);
// ECHO stays HIGH 58 microseconds per cm. 0 means no echo within 30 ms.
long echo = pulseIn(ECHO, HIGH, 30000);
if (echo == 0) {
Serial.println("Nothing in range");
delay(250);
return;
}
int cm = (echo + 29) / 58; // to the nearest cm
Serial.print(cm);
Serial.println(" cm");
if (cm < 100) {
tone(BUZZER, 1000, 40);
delay(cm * 5 + 60); // closer: a shorter wait, faster beeps
} else {
delay(250);
}
}
Description
Measure distance with an HC-SR04 and beep faster as things get closer. It compiles and runs on a virtual Uno in the browser. Turn the sound on and slide the distance down. Then make it beep only under 30 cm.
Cite this design
@design{breadboardhub/arduino-distance-alarm,
title = {Arduino Uno: distance alarm},
author = {breadboardhub},
url = {https://www.breadboardhub.com/breadboardhub/arduino-distance-alarm},
version = {1.0.0}
}