Ultrasonic Sensor Projects: 15 HC-SR04 Projects with Code
15 ultrasonic sensor projects with the HC-SR04: parking sensor, water tank, height meter, radar, people counter, theremin. Range table, Uno, ESP32, Pico code.
Ultrasonic sensor projects are built around a cheap HC-SR04 module measuring distance with sound waves, and they're among the first things electronics beginners make: a parking sensor, a water tank level gauge, a height meter, a radar, a bin that opens by itself, a people counter and a theremin you play with your hand are just a few of them. In all of them the same sensor measures distance in the same way; what changes is how far the measurement needs to reach, how accurate it has to be and what the result is turned into.
In this guide you'll find 15 projects in a single table with their measuring range, required accuracy, extra parts and difficulty level. Then you'll see why the wiring differs on the Arduino Uno, ESP32 and Raspberry Pi Pico, a filtered measuring sketch you can use in every project, and code for an ESP32 smart bin, a two-sensor people counter on the Uno and a Pico theremin. The last section explains when the HC-SR04 isn't enough and you should switch to the waterproof JSN-SR04T or the laser-based VL53L0X.

How does the HC-SR04 work? Limits to know before your project
When you give the TRIG pin a 10-microsecond pulse, the sensor sends eight 40 kHz sound pulses and sets the ECHO pin HIGH. When the sound bounces off a surface and comes back, ECHO goes LOW; so the time ECHO stays HIGH is the sound's round-trip time. Since sound travels about 343 metres per second at 20 °C, the distance in centimetres is roughly time (µs) ÷ 58: 1166 µs means about 20 cm. Behind this simple formula there are a few limits that affect every project; the table below shows which one changes what. For a detailed look at the sensor basics, see the HC-SR04 distance sensor article.
| Property | Value | Effect on the project |
|---|---|---|
| Supply | 5 V, about 15 mA | On the ESP32 and Pico, power it from the pin that provides 5 V |
| Sound frequency | 40 kHz | Humans can't hear it, but cats and dogs may |
| Measuring range | 2–400 cm (reliable range about 3–250 cm) | Can't measure closer than 2 cm; beyond 3 m depends heavily on the surface |
| Beam angle | Cone about 15° wide | At 1 m it sees an area about 26 cm in diameter |
| Resolution | About 3 mm | In practice, expecting ±1 cm is realistic |
| Measuring cycle | At least 60 ms between two measurements | At most around 16 measurements per second |
| Temperature effect | Speed of sound changes by about 0.6 m/s per °C | About 3.5% error for a 20 °C difference |
15 ultrasonic sensor projects: measuring range, accuracy and extra parts
| # | Project | Measuring range | Required accuracy | Extra parts | Level |
|---|---|---|---|---|---|
| 1 | Parking sensor (beep and LED bar) | 3–150 cm | ±2 cm | Buzzer, 5 LEDs, 220 Ω resistors | Easy |
| 2 | Digital tape measure | 2–300 cm | ±0.5 cm | I2C LCD or OLED, button | Easy |
| 3 | Height meter | 20–100 cm from sensor to head | ±1 cm | I2C LCD, door frame or ceiling mount | Medium |
| 4 | Arduino radar | 5–200 cm | ±3 cm | SG90 servo, Processing on the computer | Medium |
| 5 | Obstacle-avoiding robot | 5–100 cm | ±5 cm | L298N, 2 geared motors, servo | Medium |
| 6 | Water tank level meter | 25–250 cm | ±1 cm | ESP32, preferably JSN-SR04T | Medium |
| 7 | Container fill gauge (pet food, grain, bin) | 5–80 cm | ±2 cm | OLED or notification via ESP32 | Easy |
| 8 | Parking occupancy indicator | Car present or not, 20–250 cm | ±20 cm | RGB LED per space, LCD | Easy |
| 9 | Smart bin (lid opens by itself) | 5–30 cm | ±5 cm | SG90 servo | Easy |
| 10 | Touchless sanitiser or soap dispenser | 3–15 cm | ±2 cm | Mini pump, MOSFET or relay | Medium |
| 11 | Automatic door or barrier | 30–150 cm | ±10 cm | Servo or stepper motor, limit switch | Medium |
| 12 | Directional people counter | Doorway width, 60–100 cm | ±10 cm | Second HC-SR04, display | Hard |
| 13 | Distance tripwire alarm | 20–300 cm | ±10 cm | Buzzer, ESP32 and Telegram | Medium |
| 14 | Smart cane | 20–200 cm | ±10 cm | Vibration motor, battery | Medium |
| 15 | Ultrasonic theremin | 5–50 cm | ±0.5 cm (for smooth sound) | Passive buzzer or small speaker | Easy |
When reading the table, pay special attention to the "required accuracy" column; it's usually what makes projects with the same sensor harder. For a parking occupancy indicator it's enough to know whether the car is there, and even a 20 cm error doesn't matter. For a height meter or a water tank, though, 1 cm counts; here a median filter, temperature compensation and a solid mounting become essential. The theremin brings a different challenge: the measurement doesn't have to be very accurate, but each reading must be close to the previous one, or the sound wobbles. That's why you tune the measuring code of each project to the accuracy you need.
Wiring differences: Arduino Uno, ESP32 and Raspberry Pi Pico
The HC-SR04 runs on 5 V and outputs a 5 V pulse on its ECHO pin. The Arduino Uno also runs on 5 V, so you connect all four wires directly. The ESP32 and the Raspberry Pi Pico, however, use 3.3 V logic and their pins aren't 5 V tolerant; you still power the sensor from 5 V, but you add a voltage divider on the ECHO line. There's no problem on the TRIG side, because the sensor reads a 3.3 V trigger pulse as HIGH.
| HC-SR04 pin | Arduino Uno | ESP32 | Raspberry Pi Pico |
|---|---|---|---|
| VCC | 5V | VIN (5 V from USB) | VBUS (5 V from USB) |
| TRIG | D9 | GPIO 5 | GP14 |
| ECHO | D10, direct | GPIO 18, via 1 kΩ / 2 kΩ divider | GP15, via 1 kΩ / 2 kΩ divider |
| GND | GND | GND | GND |
| Logic level | 5 V, compatible | 3.3 V, not 5 V tolerant | 3.3 V, not 5 V tolerant |
The basis of every project: filtered distance measurement (Arduino Uno)
Most projects start with the same measuring function. The code below takes five readings, discards those without an echo, sorts the rest and picks the middle one. Unlike an average, a median filter doesn't let a single bad reading (for example an echo from a side wall) ruin the result. The speed of sound is also calculated from the ambient temperature.
1// HC-SR04 ortak ölçüm: 5 ölçümün ortancası + sıcaklık düzeltmesi / median of 5 readings + temperature compensation
2const int TRIG_PIN = 9;
3const int ECHO_PIN = 10;
4const float AIR_TEMP_C = 20.0; // ortam sıcaklığı, °C / ambient temperature, °C
5const float SOUND_CM_US = (331.3 + 0.606 * AIR_TEMP_C) / 10000.0; // ses hızı, cm/µs / speed of sound, cm/µs
6
7float readOnceCm() {
8 digitalWrite(TRIG_PIN, LOW);
9 delayMicroseconds(2);
10 digitalWrite(TRIG_PIN, HIGH); // 10 µs tetik darbesi / 10 µs trigger pulse
11 delayMicroseconds(10);
12 digitalWrite(TRIG_PIN, LOW);
13 unsigned long us = pulseIn(ECHO_PIN, HIGH, 30000UL); // en fazla 30 ms bekle (~5 m) / wait at most 30 ms
14 if (us == 0) return -1; // yankı yok / no echo
15 return us * SOUND_CM_US / 2.0; // gidiş-dönüşün yarısı / half of the round trip
16}
17
18float readDistanceCm() {
19 float v[5];
20 int n = 0;
21 for (int i = 0; i < 5; i++) {
22 float d = readOnceCm();
23 if (d > 0) v[n++] = d;
24 delay(60); // eski yankılar sönsün / let old echoes die out
25 }
26 if (n == 0) return -1;
27 for (int i = 1; i < n; i++) { // küçükten büyüğe sırala / sort ascending
28 float key = v[i];
29 int j = i - 1;
30 while (j >= 0 && v[j] > key) { v[j + 1] = v[j]; j--; }
31 v[j + 1] = key;
32 }
33 return v[n / 2]; // ortanca değer / median
34}
35
36void setup() {
37 Serial.begin(9600);
38 pinMode(TRIG_PIN, OUTPUT);
39 pinMode(ECHO_PIN, INPUT);
40}
41
42void loop() {
43 float d = readDistanceCm();
44 if (d < 0) {
45 Serial.println("Menzil dışı / out of range");
46 } else {
47 Serial.print(d, 1);
48 Serial.println(" cm");
49 }
50}The 30000 µs timeout given to pulseIn corresponds to about 5 m; if no echo arrives, instead of waiting forever the code returns -1 and prints "out of range". The 60 ms between the five readings prevents a late echo from the previous pulse being mistaken for a new measurement; that's why the function spends about 300 ms per result. In projects that need a fast response, such as a parking sensor or a theremin, you can reduce the number of samples to three. For more advanced filters, have a look at the sensor data filtering article.
Distance and motion projects (1–5)
The parking sensor splits the distance into zones and beeps faster as the car gets closer; the full version with an LED bar and OLED is in the Arduino parking sensor article. The digital tape measure shows the result of the basic sketch on an I2C LCD or an OLED display; add a button to freeze the reading and you have a pocket measure. For the height meter, the sensor is fixed to the top of a door frame or the ceiling, facing down. At start-up the distance to the empty floor is measured and saved; when someone stands underneath, height = floor distance − measured distance. If the sensor is at 210 cm and reads 35 cm, the height is 175 cm. Because hair and head shape scatter the sound, asking the person to stand straight and placing a flat piece of cardboard on their head noticeably improves accuracy.
The Arduino radar mounts the sensor on an SG90 servo, sweeps between 15° and 165° and sends the distance at each angle over the serial port; a Processing program on the computer draws them on a green radar screen. The setup is in the Arduino radar project article. The obstacle-avoiding robot takes the same servo-and-sensor pair onto a vehicle: if something is closer than 25 cm in front, it stops, looks right and left and turns towards whichever side is clearer. The motor driver wiring and code are in the obstacle-avoiding robot guide. In robots, speed matters more than accuracy, so three readings are enough for the median.
Level and fill projects (6–8)
In level projects the sensor looks down from above and measures the empty space. In a water tank level meter, the fill level is found with fill = (empty distance − measured distance) ÷ (empty distance − full distance) × 100; in a cylindrical tank, the volume can also be converted to litres with π × r² × water height. The ESP32 version that notifies your phone over Wi-Fi is explained in the ESP32 water tank level meter article. The container fill gauge applies the same formula to a pet food container, a grain silo or a bin; sending a notification when the bin passes 80 percent is a typical use. In a parking occupancy indicator, a sensor is placed on the ceiling above each space: a reading shorter than 120 cm means "car present" and the LED turns red. A setup example is in the Arduino parking system article.
Touchless trigger projects (9–11): a smart bin with the ESP32
In this group, an action starts when the distance drops below a threshold. In the smart bin, a servo motor opens the lid when a hand comes within 25 cm and closes it 3 seconds after the last detection; you'll find the Arduino version in the smart bin article. The code below does the same with an ESP32. To drive the servo, install the ESP32Servo library from the Library Manager; power the servo from the VIN (5 V) pin and take its signal from GPIO 13.
1// ESP32 akıllı çöp kutusu: el yaklaşınca kapak açılır / ESP32 smart bin: the lid opens when a hand comes close
2#include <ESP32Servo.h>
3
4const int TRIG_PIN = 5;
5const int ECHO_PIN = 18; // 1 kΩ + 2 kΩ bölücüyle / through a 1 kΩ + 2 kΩ divider
6const int SERVO_PIN = 13;
7const float OPEN_CM = 25.0; // bundan yakın el kapağı açar / a hand closer than this opens the lid
8const unsigned long HOLD_MS = 3000; // son algılamadan sonra açık kalma süresi / stays open after the last detection
9
10Servo lid;
11unsigned long lastSeen = 0;
12bool isOpen = false;
13
14float readCm() {
15 digitalWrite(TRIG_PIN, LOW);
16 delayMicroseconds(2);
17 digitalWrite(TRIG_PIN, HIGH);
18 delayMicroseconds(10);
19 digitalWrite(TRIG_PIN, LOW);
20 unsigned long us = pulseIn(ECHO_PIN, HIGH, 25000UL);
21 return us == 0 ? 999.0 : us / 58.0; // yankı yoksa "uzak" say / no echo counts as far away
22}
23
24void setup() {
25 Serial.begin(115200);
26 pinMode(TRIG_PIN, OUTPUT);
27 pinMode(ECHO_PIN, INPUT);
28 lid.setPeriodHertz(50); // standart servo, 50 Hz / standard servo, 50 Hz
29 lid.attach(SERVO_PIN, 500, 2400); // darbe aralığı, µs / pulse range, µs
30 lid.write(0); // kapalı konum / closed position
31}
32
33void loop() {
34 float d = readCm();
35 if (d < OPEN_CM) {
36 lastSeen = millis();
37 if (!isOpen) {
38 lid.write(100); // kapağı aç / open the lid
39 isOpen = true;
40 Serial.println("Açıldı / opened");
41 }
42 }
43 if (isOpen && millis() - lastSeen > HOLD_MS) {
44 lid.write(0);
45 isOpen = false;
46 Serial.println("Kapandı / closed");
47 }
48 delay(60); // HC-SR04 ölçüm döngüsü / HC-SR04 measuring cycle
49}The code keeps measuring while the lid is open; if the hand is still there, lastSeen is updated and the lid doesn't close. The touchless sanitiser works on the same logic, but instead of a servo a mini pump runs for half a second; drive the pump through a MOSFET or a relay, not straight from the pin. At short range (3–15 cm) the HC-SR04's beam may also see the counter under your hand, so tilt the sensor slightly forward. In the automatic door or barrier project the threshold rises to around 100 cm; to keep the door from trapping anyone, measuring while it closes and stopping when an obstacle appears is an important safety step.
Counting and security projects (12–14): a two-sensor people counter
A single sensor knows someone passed through the door but can't tell the direction. In a directional people counter, two sensors are placed on the door frame at the same height, 15–20 cm apart: A outside, B inside. If A is blocked first and then B, someone came in; if B is blocked first and then A, someone went out. If both sensors send sound at the same time, one hears the other's echo; that's why the code measures the sensors in turn, with 30 ms between them. On the Uno the second sensor connects to D11 (TRIG) and D12 (ECHO).
1// İki HC-SR04 ile yönlü kişi sayacı / bidirectional people counter with two HC-SR04 sensors
2const int TRIG_A = 9, ECHO_A = 10; // dış sensör / outer sensor
3const int TRIG_B = 11, ECHO_B = 12; // iç sensör / inner sensor
4const float DOOR_CM = 80.0; // kapı boşken okunan mesafe / distance with the doorway empty
5const float MARGIN_CM = 15.0; // bu kadar kısalırsa biri var / this much shorter means someone is there
6const unsigned long PASS_MS = 1500; // bir geçiş en fazla 1,5 sn sürer / a pass takes at most 1.5 s
7
8int inside = 0;
9char first = 0; // önce tetiklenen sensör: 'A', 'B' ya da 0 / sensor triggered first
10unsigned long firstTime = 0;
11
12bool blocked(int trig, int echo) {
13 digitalWrite(trig, LOW);
14 delayMicroseconds(2);
15 digitalWrite(trig, HIGH);
16 delayMicroseconds(10);
17 digitalWrite(trig, LOW);
18 unsigned long us = pulseIn(echo, HIGH, 25000UL);
19 if (us == 0) return false; // yankı yok = boş / no echo = empty
20 return us / 58.0 < DOOR_CM - MARGIN_CM;
21}
22
23void readBoth(bool &a, bool &b) {
24 a = blocked(TRIG_A, ECHO_A);
25 delay(30); // sensörler birbirinin yankısını duymasın / avoid crosstalk
26 b = blocked(TRIG_B, ECHO_B);
27 delay(30);
28}
29
30void waitClear() { // kapı boşalana kadar bekle / wait until the doorway is clear
31 bool a, b;
32 do { readBoth(a, b); } while (a || b);
33}
34
35void setup() {
36 Serial.begin(9600);
37 pinMode(TRIG_A, OUTPUT); pinMode(ECHO_A, INPUT);
38 pinMode(TRIG_B, OUTPUT); pinMode(ECHO_B, INPUT);
39}
40
41void loop() {
42 bool a, b;
43 readBoth(a, b);
44
45 if (first == 0) {
46 if (a && !b) { first = 'A'; firstTime = millis(); }
47 else if (b && !a) { first = 'B'; firstTime = millis(); }
48 } else if (millis() - firstTime > PASS_MS) {
49 first = 0; // yarım kalan geçişi unut / forget an unfinished pass
50 } else if (first == 'A' && b) {
51 inside++;
52 first = 0;
53 Serial.print("Giriş / in, içeride / inside: ");
54 Serial.println(inside);
55 waitClear();
56 } else if (first == 'B' && a) {
57 if (inside > 0) inside--;
58 first = 0;
59 Serial.print("Çıkış / out, içeride / inside: ");
60 Serial.println(inside);
61 waitClear();
62 }
63}Measure DOOR_CM in your own doorway while it's empty and enter it; MARGIN_CM sets how much a person has to shorten that distance. If a pass isn't completed within 1.5 seconds (someone comes to the door and turns back), it isn't counted. This setup works well for single-person doorways; if two people walk through side by side, they're counted as one. The distance tripwire alarm learns the distance of the empty corridor and, if the reading gets more than 30 cm shorter, sounds a buzzer or has a Telegram bot send a message. The smart cane turns distance into a vibration motor signal: the closer the obstacle, the faster it vibrates; details are in the smart cane project article.
Music project (15): an ultrasonic theremin with the Raspberry Pi Pico
The theremin is an electronic instrument you play by the distance of your hand, without touching it. In this version, moving your hand to 5 cm from the sensor plays 2000 Hz, and moving it away to 50 cm plays 200 Hz; in between, the pitch changes linearly. On the Pico, MicroPython's time_pulse_us function is the equivalent of Arduino's pulseIn. Connect the passive buzzer's positive lead to GP16 and its negative to GND; an active buzzer can't change frequency, so it's useless here. You can see the difference in the what is a buzzer article.
1# Pico ultrasonik theremin: mesafe ses frekansına dönüşür / Pico ultrasonic theremin: distance becomes pitch
2from machine import Pin, PWM, time_pulse_us
3import time
4
5trig = Pin(14, Pin.OUT, value=0) # GP14 -> TRIG
6echo = Pin(15, Pin.IN) # GP15 <- ECHO, 1 kΩ / 2 kΩ bölücüyle / through a 1k / 2k divider
7buzzer = PWM(Pin(16)) # GP16 -> pasif buzzer / passive buzzer
8
9NEAR_CM, FAR_CM = 5, 50 # çalma aralığı / playing range
10LOW_HZ, HIGH_HZ = 200, 2000 # ses aralığı / pitch range
11
12def read_cm():
13 trig.value(1)
14 time.sleep_us(10) # 10 µs tetik / 10 µs trigger
15 trig.value(0)
16 us = time_pulse_us(echo, 1, 30000) # yankı yoksa negatif döner / negative if there is no echo
17 return us / 58 if us > 0 else None
18
19smooth = None
20while True:
21 d = read_cm()
22 if d is None or d > FAR_CM:
23 buzzer.duty_u16(0) # el yok: sus / no hand: silence
24 smooth = None
25 else:
26 d = max(d, NEAR_CM)
27 smooth = d if smooth is None else smooth * 0.7 + d * 0.3 # titremeyi azalt / reduce jitter
28 f = HIGH_HZ - (smooth - NEAR_CM) * (HIGH_HZ - LOW_HZ) / (FAR_CM - NEAR_CM)
29 buzzer.freq(int(f))
30 buzzer.duty_u16(32768) # %50 doluluk / 50% duty
31 time.sleep_ms(60) # HC-SR04 ölçüm döngüsü / measuring cycleThe smooth variable in the code is a simple exponential average: the new reading is added with 30 percent weight and the previous value with 70 percent, so the sound glides smoothly despite small tremors of your hand. When your hand leaves the playing area, the buzzer goes silent. For a more musical result, you can round the calculated frequency to the nearest note frequency and play on a scale.
When the HC-SR04 isn't enough: when to switch to the JSN-SR04T or VL53L0X?
The HC-SR04 is great indoors on hard, flat surfaces, but in some projects you hit its limits. The table below sums up which sensor makes more sense in which situation; for a detailed comparison of all distance sensors, see the types of distance sensors article.
| Sensor | Measuring range | Beam | Outdoors and water | When to choose it? |
|---|---|---|---|---|
| HC-SR04 | 2–400 cm | About 15° | Not resistant | Indoors, general purpose, cheapest |
| HC-SR04P / RCWL-1601 | 2–400 cm | About 15° | Not resistant | 3.3 V operation without a divider on ESP32 and Pico |
| JSN-SR04T | About 25–450 cm | Wide, about 45° or more | Waterproof probe | Water tank, well, car bumper, garden |
| VL53L0X (laser ToF) | 3 cm – 2 m (~1.2 m in default mode) | About 25° | Range shrinks in sunlight | Tight spaces, soft targets like fabric and foam, small robots |
In short: if the target is water or the sensor will stay outdoors, switch to the JSN-SR04T. If the target is a sound-absorbing surface like fabric, curtains, foam or human hair, or if the wide sound cone sees side walls and produces false readings, the light-based VL53L0X gives steadier results. Glass and sunlight, on the other hand, are the weak spots of laser sensors; for a people counter in front of a shop window, an ultrasonic sensor is more reliable.
Common mistakes in ultrasonic sensor projects
- Always 0 or out of range: TRIG and ECHO are swapped, VCC isn't 5 V, or the divider on the ESP32 is wired backwards; make sure the 2 kΩ resistor is on the GND side.
- Values jump around randomly: Less than 60 ms between readings, or the target is slanted or soft; use a median filter and point the sensor straight at the target.
- Two sensors interfere with each other: They're measuring at the same time; measure them in turn with a pause in between, as in the people counter.
- Readings go haywire when the servo or motor runs: The supply voltage dips; give the servo a separate 5 V supply, join the GNDs and add a 100 µF capacitor on the supply.
- A nearby obstacle isn't detected: The target is closer than 2 cm or (on the JSN-SR04T) inside the 25 cm dead zone; move the sensor back.
- The code freezes: No timeout was given to pulseIn, or the code makes the beeps with delay(); use a timeout and do the timing with millis().
The HC-SR04 is the cheapest way to build dozens of different projects with a single sensor; once you've nailed the filtered measuring code, all that's left is deciding what to turn the distance into. If you want to build one of these projects step by step, in the BlueGrays app you'll find distance measurement with the HC-SR04, a parking sensor, an LCD distance meter, a height meter, an obstacle-avoiding robot and an ESP32 parking sensor, with circuit diagrams and code.
Frequently asked questions
What projects can you make with an HC-SR04?
With an HC-SR04 you can make a parking sensor, a digital tape measure, a height meter, an Arduino radar, an obstacle-avoiding robot, a water tank level meter, a smart bin, a people counter and a theremin. They all share the same basis: the sensor measures distance and the code turns that distance into sound, light, motion or a notification.
How far can an ultrasonic sensor measure?
The HC-SR04's datasheet range is 2 cm to 4 m. In practice you get reliable readings up to 2.5–3 m on a hard, flat surface; further away and on soft surfaces the echo gets weak. For longer range, the JSN-SR04T (4.5–6 m) or laser-based LiDAR sensors are preferred.
Can the HC-SR04 be used in a water tank?
It works for short tests, but it isn't recommended for permanent use; the humidity and condensation inside the tank damage its exposed circuit board and transducers. For water tanks and wells, the JSN-SR04T with its waterproof probe is the right choice.
Why does my HC-SR04 read 0 or wrong values?
The most common causes are swapped TRIG and ECHO pins, a supply that isn't 5 V, less than 60 ms between readings, and sound-absorbing or slanted surfaces. Giving pulseIn a timeout, using a median filter and keeping the sensor perpendicular to the target solve most of these problems.
Can the HC-SR04 connect directly to an ESP32?
You can power the sensor from the ESP32's VIN (5 V) pin, but the ECHO pin outputs a 5 V pulse, so it shouldn't go straight to a GPIO. Put a voltage divider made of 1 kΩ and 2 kΩ resistors on the ECHO line, or use the HC-SR04P version, which runs on 3.3 V.
Ultrasonic or infrared distance sensor: which is better?
An ultrasonic sensor isn't affected by colour or light, sees water surfaces and glass well, and is cheap for long range. Infrared and laser sensors have a narrower beam and are faster, and they're better on soft surfaces like fabric, but they're affected by sunlight and transparent surfaces. The choice depends on the type of target and the environment.
Projects to build after reading this
See all projects
HC-SR04 Distance Measurement (Serial Display)
The HC-SR04 sensor works just like a bat finding its way in the dark: it sends out a sound you cannot hear, listens for the echo and measures how far away the object in front of it is.

Parking Sensor with HC-SR04
A mini version of a car's parking sensor: the closer something gets, the faster the beeps.

Measuring Distance Using LCD Display
A tool that measures distance without a ruler: move your hand back and forth in front of the sensor and watch the number change.

Height Measurement Project
A height meter that hangs from a door frame and tells you, in centimetres, how tall the person standing under it is.

Obstacle Avoidance Robot
How about building a smart vehicle that finds its own way? The Obstacle Avoidance Robot constantly scans its surroundings thanks to the ultrasonic sensor in front of it.

ESP32 HC-SR04 Ultrasonic Distance Sensor
The HC-SR04 ultrasonic sensor measures distance by timing how long its sound pulse takes to bounce off an object and return (time of flight). In this project the ESP32 sends a 10-microsecond pulse to the TRIG pin and reads the echo time from the ECHO pin with pulseIn(). The distance is shown in cm on a 16x2 I2C LCD. The HC-SR04 runs on 5V, so the ECHO pin needs a voltage divider, or the ESP32's 3.3V GPIO gets damaged.

ESP32 Parking Sensor (HC-SR04 + 5-LED Bar + Buzzer + OLED)
The ESP32 version of a car parking sensor! The HC-SR04 ultrasonic sensor measures the distance to the object in front. As it gets closer, a 5-LED bar fills up (green → yellow → red) and the buzzer beeps faster. Very close (under 10 cm), a continuous alarm sounds and all LEDs light up. The SSD1306 OLED display shows the live distance in cm in large text, plus a status message.

ESP32 Prayer Rakat Counter (HC-SR04 + SSD1306 OLED + 2 Buttons)
Do you sometimes lose track of which rakat you are on during prayer? This project is a rakat counter that sits next to your prayer mat and counts your prostrations when you bring your hand close. The HC-SR04 ultrasonic distance sensor detects your hand, the SSD1306 OLED display shows the count, and two buttons let you choose 2, 3 or 4 rakats and reset. A 2.5-second debounce and a "hand-away" check make sure no prostration is counted twice.
More articles
BlueGrays app
Build this circuit step by step on your phone
Wiring diagram, code and parts list on one screen. 500+ Arduino, ESP32, ESP8266, Pico, mBot and micro:bit projects ready to build.
Scan with your phone
Point your camera at the code and your phone's app store opens.
or open the store

