All parts

Ultrasonic distance sensor (HC-SR04)

Measures in centimetres how far away the thing in front is, like a bat: parking sensors, robots, measuring.

The test program

Test this part on its own before you build the rest: if it works alone, the rest is built on something you know works.

10 LED red, off
20 IF DISTANCE() < 20 THEN LED red, on
30 WAIT 100
40 GOTO 10

What you should see: Put your hand less than 20 cm from the sensor: the red light comes on.

▶ Try it in the IDE

What to buy

  • Ultrasonic distance sensor (HC-SR04)The classic HC-SR04's ECHO pin is 5V and can damage a 3.3V board. Either get the HC-SR04P (3.3V) or add a level shifter.

How to wire it to an ESP32-S3

  1. Trig → a free GPIO
  2. Echo → a free GPIOECHO is 5V on a classic HC-SR04 — level-shift or use an HC-SR04P
  3. VCC → ESP32-S3: 5V
  4. GND → ESP32-S3: GNDCommon ground: this link is mandatory.

If it does not work

The program runs but nothing happens
TRIG and ECHO are swapped, or the sensor does not get the right voltage. TRIG and ECHO to the pins in the diagram; the classic HC-SR04 runs at 5 V with ECHO brought down to 3.3 V, the HC-SR04P runs at 3.3 V.

What you can adjust

  • The distance, in centimetres, at which the program reacts.

Which boards it works on

  • ESP32-S3 Freenove: yes
  • Nordic nRF54LM20 DK: yes
  • Arduino UNO R4 WiFi: yes