Bats find their way with sound, and so can your Arduino. The ultrasonic sensor sends out a short sound pulse that people can't hear and times how long the echo takes to come back.
What you'll learn
- How an ultrasonic sensor measures distance
- How to time a pulse with
pulseIn() - How to print values to the Serial Monitor
What you need
- UNO R3 board and USB cable
- Ultrasonic sensor (HC-SR04)
- Breadboard
- 4 jumper wires
Wiring

Build it step by step
Plug in all the parts first, then add the wires in this order. In each picture the new wires are bright and the ones from earlier steps are faded. Click a picture to see it larger.


| Sensor pin | UNO pin |
|---|---|
| VCC | 5V |
| Trig | 9 |
| Echo | 10 |
| GND | GND |
Build this circuit in EEMENTOR Lab
Wire it yourself in your browser before you touch a real wire. No sign-up, nothing to install.
Build it yourself
- The UNO and this lesson’s parts are already placed. Wire them using the wiring table above. Pins with no wire show red.
- Missing a part? Add it from the parts list on the left.
- Press Run, then try the inputs: click, hold or slide them under Selected.
- Then try this lesson’s sketch: paste it into the Code tab and press Compile & Run.
EEMENTOR Lab is free and in beta. Results are a guide; a real build can differ slightly. About the Lab
The sketch
const int TRIG_PIN = 9;
const int ECHO_PIN = 10;
void setup() {
Serial.begin(9600);
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
}
void loop() {
// Send a 10 microsecond pulse to start a measurement
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
// Time the echo (in microseconds), give up after 30 ms
long duration = pulseIn(ECHO_PIN, HIGH, 30000);
if (duration == 0) {
Serial.println("Out of range");
} else {
// Sound travels about 0.0343 cm per microsecond, there and back
float distanceCm = duration * 0.0343 / 2;
Serial.print("Distance: ");
Serial.print(distanceCm);
Serial.println(" cm");
}
delay(200);
}
Upload the sketch, then open Tools → Serial Monitor and set the speed to 9600 baud. Move your hand in front of the sensor and watch the distance change.
What you should see

How it works

The sound travels to the object and back, so the sketch divides the total time by two. At room temperature sound moves about 343 metres per second, which is 0.0343 cm per microsecond. The sensor works best between about 2 cm and 4 m.
Try this next
- Add the LED from lesson 1 and switch it on when something is closer than 20 cm.
- Open Tools → Serial Plotter to see the distance as a live graph.
Troubleshooting
- Always "Out of range": check that Trig and Echo aren't swapped.
- Jumpy readings: soft or angled surfaces reflect sound poorly. Point the sensor at a flat, hard object.