Arduino
Beginner
Published on Jan 02, 2026
The HC-SR04 ultrasonic sensor is perfect for measuring distances from 2cm to 400cm. This tutorial will show you how to interface it with Arduino.
The sensor sends out ultrasonic sound waves and measures the time it takes for the echo to return. Using the speed of sound, we can calculate the distance.
const int trigPin = 9;
const int echoPin = 10;
void setup() {
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
Serial.begin(9600);
}
void loop() {
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
long duration = pulseIn(echoPin, HIGH);
float distance = duration * 0.034 / 2;
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
delay(500);
}
Learn the basics of Arduino programming and build your first LED blink project.
Read TutorialCreate a temperature and humidity monitoring system using DHT22 sensor. Display readings on LCD or serial monitor.
Read Tutorial