Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
HC-SR04 (Ultrasonic range module) + Arduino + Pushbutton
// HC-SR04 (Ultrasonic range module)
#define buttonPin 2
#define ledPin 7
#define trigPin 11
#define echoPin 13
float duration, distance;
volatile int buttonState = 0;
void setup() {
Serial.begin (9600);
pinMode(buttonPin, INPUT);
pinMode(ledPin, OUTPUT);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
attachInterrupt(digitalPinToInterrupt(buttonPin), pin_ISR, CHANGE);
void pin_ISR() {
buttonState = digitalRead(buttonPin);
// LED is connected to pushbutton such that when push button is open, it is connected to 5V i.e. HIGH
// when push button is closed, it the circit is connected to ground (no-resistance), so reading is LOW.
digitalWrite(ledPin, buttonState ? LOW : HIGH);
void loop() {
if (buttonState == 1) {
// Write a pulse to the HC-SR04 Trigger Pin
digitalWrite(trigPin, LOW);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10); // API of HC-SR04 wants a 10ms HIGH signal on the trigger pin
digitalWrite(trigPin, LOW);
// Measure the response from the HC-SR04 Echo Pin
duration = pulseIn(echoPin, HIGH); // pulseIn is a brilliant inbuilt function that calculates for how long a pin was HIGH (or LOW, defined in param 2)
// Determine distance from duration
// Use 343 metres per second as speed of sound at 20 degree room temperature.
distance = (duration / 2) * 0.0343;
// Send results to Serial Monitor
Serial.print("Distance = ");
if (distance >= 400 || distance <= 2) {
Serial.println("Out of range, HC-SR04 has a range of 2cm to 400cm");
else {
// Precision 1 because I wanted to write to a 4 digit display, so max value would have been 399.9 but I ran out of arduino digital pins
Serial.print(distance, 1);
Serial.println(" cm");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment