Learn the basics

Ultrasonic distance sensor

A click you cannot hear, its echo, and a stopwatch: how ultrasonic sensors measure, and our two kinds side by side, the HC-SR04 and the analog US-016.

the click → ← the echo

Ultrasonic distance sensor

One can sends a click, too high for us to hear. The other listens for the echo from the wall. A stopwatch measures how long the trip took. Sound needs about 29 µs for 1 cm, and the click went there and back, so:

distance in cm = time in µs ÷ 2 ÷ 29.1

More: see it slowly, our two sensors side by side, and how to read each

Our two sensors, side by side

HC-SR04
HC-SR04 times the echo
How
Trig makes the click; Echo stays HIGH as long as the trip takes
Pins
VCC · Trig · Echo · GND
Read it
a library, or pulseIn and the maths
Range
2 to 400 cm, about 3 mm steps
Nothing there
no echo: the library gives −1
Good for
most hobby projects: many examples online
US-016
US-016 an analog sensor
How
times the echo itself and gives a voltage: further = higher
Pins
VCC · Range · Out · GND
Read it
analogRead, no library
Range
2 to 300 cm (Range high or open, 3 mm a step), or up to 1 m (Range on GND, 1 mm a step)
Nothing there
the highest value: about 307 cm
Good for
simple code, and fine steps close up

Which would you choose? A parking assist that must see 3 m. A gate that only needs to know "a car is there". A ruler that measures a book on the table to the millimetre. A project that also uses every analog pin for knobs. Explain your choice to the person next to you.

Both see in a cone of about 15°. Soft things (a pillow, a jumper) and slanted surfaces send the sound away: then there is no echo, or a wrong one. Wait at least 60 ms between two clicks, or you may hear the old echo.

Reading the HC-SR04

#include <HCSR04.h>
UltraSonicDistanceSensor sensor(12, 11);    // Trig on 12, Echo on 11

void setup() { Serial.begin(9600); }
void loop() {
  Serial.println(sensor.measureDistanceCm());   // -1: nothing in range
  delay(200);
}

The HCSR04 library (by Martin Sosic, Library Manager) does the timing. Without it: Trig HIGH for 10 µs, then pulseIn(echoPin, HIGH) gives the time in µs, and time ÷ 2 ÷ 29.1 is the distance. Always treat −1 as "far away", not as "very close".

Reading the US-016

const int sensorPin = A0;               // OUT; Range on 5V (or open): up to 3 m

float measureDistance() {
  return analogRead(sensorPin) * 0.3;   // one step is 3 mm = 0.3 cm
}

void setup() { Serial.begin(9600); }
void loop() {
  Serial.println(measureDistance());
  delay(200);
}

The voltage on OUT goes from 0 V to 5 V for 0 to about 307 cm, and analogRead turns that into 0 to 1023: every step is 3 mm. With Range on GND the sensor measures up to about 1 m instead, 1 mm a step: then the number from analogRead is the distance in mm. The sensor checks Range only when it gets power. Check it with a tape measure: if every number is off by the same factor, change the 0.3 a little (calibrating).