ESP32 UNO - Ultrasonic Sensor - Relay

How do you switch a lamp when someone walks up? Connect an HC-SR04 and a relay to the ESP32 Uno form board, and the relay clicks on as soon as an object is near. Move away, and it clicks off. The same wiring can control lights, motors or a solenoid lock.

By the end, you can:

  1. Wire an ultrasonic sensor and a relay to the ESP32 Uno
  2. Make the 5V ECHO signal safe for a 3.3V pin
  3. Measure distance in centimeters with pulseIn()
  4. Turn a relay on and off at a distance limit you choose
ESP32 Uno ultrasonic sensor relay

Components You Need

1×ESP32 Uno-form Board
1×USB Cable Type-A to Type-C (for USB-A PC)
1×USB Cable Type-C to Type-C (for USB-C PC)
1×Ultrasonic Sensor
1×Relay
1×Jumper Wires
1×Recommended: 5V to 3.3V Level Converter for the ECHO signal
1×Optionally, Solenoid Lock
1×Optionally, 12V Power Adapter
1×Optionally, DC Power Jack

Or you can buy the following kits:

1×DIYables Sensor Kit (18 sensors/displays)
Disclosure: Some of the links provided in this section are Amazon affiliate links. We may receive a commission for any purchases made through these links at no additional cost to you.
Additionally, some of these links are for products from our own brand, DIYables .

How the Relay and the Sensor Work Together

By the end of this part, you know what each module does in this project.

Part Role in This Project
Ultrasonic sensor Measures the distance to the object in front of it
Relay Switches the load, on when near and off when far
ESP32 Uno Reads the sensor and decides when to set the relay pin HIGH
Load (lamp, motor, lock) Connects to the relay COM and NO contacts

The sensor sends a burst of sound and waits for the echo. The ESP32 Uno turns the echo time into centimeters. Below 50 cm, it drives the relay pin HIGH.

To learn each part alone first, use these guides:

ESP32 Uno Pinout

Every Uno header pin on the ESP32 Uno form board is tied to one GPIO number, and your sketch uses that number. Match the labels in the diagram before you place any wire.

ESP32 Uno pinout diagram

How to Connect

By the end of this part, the sensor and the relay are wired and ready.

The wiring diagram between ESP32 Uno Ultrasonic Sensor Relay

This image is created using Fritzing. Click to enlarge image

※ NOTE THAT:

The wiring diagram may not show the correct pin. On the ESP32 Uno, Relay IN goes to D5 (GPIO16), not A5 as the picture may show. We will update the diagram soon. Until then, follow the wiring table and the code on this page, not the picture.

※ NOTE THAT:

The wiring diagram may not show the correct wiring for the ESP32 Uno. The HC-SR04 ECHO pin sends a 5V signal, and ESP32 Uno pins are 3.3V only. The picture shows ECHO wired straight to the board. On the ESP32 Uno, put a voltage divider or a level converter on ECHO, as this page shows. We will update the diagram soon. Until then, follow the wiring table and the text on this page, not the picture.

Component Pin ESP32 Uno Pin
Ultrasonic Sensor VCC 5V
Ultrasonic Sensor TRIG D7 (GPIO14)
Ultrasonic Sensor ECHO (through level converter) D6 (GPIO27)
Ultrasonic Sensor GND GND
Relay DC+ (VCC) 5V
Relay DC- (GND) GND
Relay IN D5 (GPIO16)

Good to know: ESP32 Uno pins use 3.3V logic. The TRIG pulse is fine for the sensor, but the ECHO pulse is not safe for the board.

WARNING

A classic HC-SR04 needs 5V power, so its ECHO pin swings to 5V. Pins on the ESP32 Uno are NOT 5V tolerant. Add a level converter in the ECHO line, or build a divider with two resistors (1 kΩ in series with ECHO, then 2 kΩ down to GND). A 3.3V sensor such as the HC-SR04P needs no extra part.

WARNING

The load side of the relay may carry mains or high voltage. Tighten the COM and NO (or NC) screws, keep no bare wire exposed, and route the load wires away from the board and the sensor.

ESP32 Uno Code

The sketch pulses TRIG, times the ECHO pin, converts the time to centimeters and sets the relay. It prints the distance twice a second.

/* * This ESP32 Uno code was developed by newbiely.com * * This ESP32 Uno code is made available for public use without any restriction * * For comprehensive instructions and wiring diagrams, please visit: * https://newbiely.com/tutorials/esp32-uno/esp32-uno-ultrasonic-sensor-relay */ #define TRIG_PIN 14 // D7 (GPIO14) sends the trigger pulse to the sensor #define ECHO_PIN 27 // D6 (GPIO27) reads the echo pulse from the sensor #define RELAY_PIN 16 // D5 (GPIO16) drives the relay IN pin #define DISTANCE_THRESHOLD 50 // relay turns on below this distance, in centimeters float duration_us, distance_cm; void setup() { Serial.begin (9600); // start the Serial Monitor link pinMode(TRIG_PIN, OUTPUT); // the trigger pin sends signals out pinMode(ECHO_PIN, INPUT); // the echo pin receives signals pinMode(RELAY_PIN, OUTPUT); // the relay pin switches the relay } void loop() { // send a 10-microsecond HIGH pulse on the TRIG pin digitalWrite(TRIG_PIN, HIGH); delayMicroseconds(10); digitalWrite(TRIG_PIN, LOW); // time how long the ECHO pin stays HIGH duration_us = pulseIn(ECHO_PIN, HIGH); // convert that time to a distance in centimeters distance_cm = 0.017 * duration_us; if(distance_cm < DISTANCE_THRESHOLD) digitalWrite(RELAY_PIN, HIGH); // object is close, so switch the relay on else digitalWrite(RELAY_PIN, LOW); // object is far, so switch the relay off // show the measured distance on the Serial Monitor Serial.print("distance: "); Serial.print(distance_cm); Serial.println(" cm"); delay(500); }
Code Part What It Does
TRIG_PIN, ECHO_PIN, RELAY_PIN Hold the GPIO numbers 14, 27 and 16
DISTANCE_THRESHOLD Distance limit in cm, set to 50
digitalWrite(TRIG_PIN, HIGH) for 10 us Starts one measurement
pulseIn(ECHO_PIN, HIGH) Measures the echo time in microseconds
0.017 * duration_us Turns the time into centimeters
if / else on distance_cm Sets the relay pin HIGH or LOW

The relay follows your hand, and the Serial Monitor shows every reading.

Upload and Test

  1. First time with this board? Set it up with ESP32 Uno - Getting Started before you continue.
  2. Build the circuit by following the wiring table above.
  3. Plug in the USB Type-C cable between the ESP32 Uno and your computer.
  4. Select the board in Arduino IDE: pick ESP32 Dev Module and the COM port of the board (CH340).
  5. Copy the code above into a new sketch.
  6. Click Upload to send the code to the board.
Arduino IDE Upload Code
  1. Open the Serial Monitor and choose 9600 baud.
  2. Hold your hand in front of the sensor, then pull it away.
  3. Listen for the relay click and check the distance in the Serial Monitor.
  4. Pro tip: test with a small lamp or an LED on the relay output first, and add the real load only after the switching works.
∞
Newbiely | Arduino IDE 2.3.8
──
☐
✕
File
Edit
Sketch
Tools
Help
ESP32 Dev Module
Newbiely.ino
···
8 Serial.println("Hello World!");
Output
Serial Monitor
Message (Enter to send message to 'ESP32 Dev Module' on 'COM15')
New Line
9600 baud
distance: 143.26 cm distance: 87.05 cm distance: 46.38 cm distance: 18.92 cm distance: 71.49 cm
Ln 11, Col 1
ESP32 Dev Module on COM15
2

Video Tutorial

See the ESP32 Uno build in action in the video below.

Code Explanation

Every line in the sketch has a comment. The main idea: measure, compare with DISTANCE_THRESHOLD, then set the relay pin HIGH or LOW. Edit the threshold to change how close an object must be.

※ NOTE THAT:

This sketch is for learning. Ultrasonic readings are noisy, and one bad reading can make the relay click by mistake. For stable values, filter the noise as shown here.

ESP32 Uno vs UNO R4 for This Project

By the end of this part, you know what changes when you move this project from the UNO R4 to the ESP32 Uno.

Item Arduino UNO R4 ESP32 Uno
Logic voltage 5V 3.3V
TRIG pin D7 (pin 7) D7 (GPIO14)
ECHO pin D6 (pin 6) D6 (GPIO27)
Relay IN pin A5 (pin A5) D5 (GPIO16)
ECHO level Direct connection Level converter or divider needed
Arduino IDE board Arduino UNO R4 WiFi ESP32 Dev Module

The wiring diagram looks alike, but the relay IN wire goes to D5 here, not A5. A5 is GPIO39 on the ESP32 Uno, and that pin can only read signals. Also, the ECHO wire needs a level converter.

Go Wireless: Switch the Relay from Your Phone

By the end of this part, you have an idea to control the relay without a cable.

The ESP32 Uno has WiFi and Bluetooth, so the relay can also follow a button on your phone. Use the distance to switch it automatically, and use the app to override it by hand.

Try These Next

  • Add two thresholds (on below 45 cm, off above 55 cm) so the relay does not chatter
  • Keep the relay on for a few seconds after the object leaves
  • Power a solenoid lock from the relay for a hands-free door latch

Troubleshooting

Problem Possible Cause Solution
No COM port in Arduino IDE CH340 driver missing or charge-only USB cable Install the CH340 driver and use a data USB cable
Upload fails with Failed to connect or Waiting for download Board did not enter download mode Hold the BOOT button when the upload starts
Relay never clicks Relay module not powered or IN wire on the wrong pin Connect relay DC+ to 5V and DC- to GND, and put IN on D5
Reading stays at 0 cm Echo never arrives, or the ECHO jumper is loose Re-seat the ECHO wire on D6 through the converter, and confirm VCC has 5V
Distance values jump around Noise or a soft object in front of the sensor Aim at a flat hard surface and filter the readings
Relay chatters Object sits right at the limit Average several readings or add a gap between on and off limits
Board resets or a pin stops working The 5V ECHO signal went straight into a 3.3V pin Add a level converter or divider
Garbled text in Serial Monitor Baud rate mismatch Pick 9600 in the baud drop-down

FAQ

How does an ultrasonic sensor control a relay?

The sensor measures distance from the echo time. The code compares the distance with a limit. When the object is closer, the code sets the relay pin HIGH, and the relay closes its contacts.

Is it safe to connect the HC-SR04 ECHO pin directly to the ESP32 Uno?

No. The sensor outputs 5V on ECHO, and the board pins are 3.3V only. Use a level converter or a 1 kΩ and 2 kΩ divider.

Will the sensor run on the 3.3V pin?

The standard HC-SR04 wants 5V and often misreads at 3.3V. The HC-SR04P accepts 3.3V to 5V and has a safe ECHO output at 3.3V.

Can the 3.3V pin signal drive a 5V relay module?

Most modules with a transistor or optocoupler input switch fine at 3.3V. Feed the module 5V. If it stays silent, use a relay made for 3.3V logic or add a transistor driver.

How do I change the distance that turns the relay on?

Edit DISTANCE_THRESHOLD. Set it to 20 and the relay turns on only when an object is closer than 20 cm.

Why does the code use 14, 27 and 16 and not 7, 6 and 5?

Uno header labels are for wiring. Code uses GPIO numbers. D7 is GPIO14, D6 is GPIO27 and D5 is GPIO16.

Does the UNO R4 code work on the ESP32 Uno?

Almost. pulseIn(), digitalWrite() and delayMicroseconds() behave the same. Change the three pin numbers, add a level converter for ECHO, and move the relay IN wire to D5.

Can I control the relay from a web page with the ESP32 Uno?

Yes. The ESP32 Uno has WiFi and Bluetooth. See the web and Bluetooth app tutorials in the Go Wireless section.

What if my project needs more pins than the Uno headers give?

The ESP32 Uno has a few extra holes near the power header: GPIO32 and GPIO33 (I/O, PWM, analog on ADC1, so they also work while WiFi is on) and GPIO15 (I/O, PWM, analog on ADC2). Solder pin headers to use them and write the GPIO number in code. GPIO32 is a good output pin for the relay IN wire. Two warnings: GPIO15 and GPIO0 (the IO0 pin at the unused Uno NC position) are boot strapping pins, so a wrong connection can stop the board from booting or uploading code, and you should use GPIO32 and GPIO33 first. Never use the six holes under the digital header (SD0 to SD3, CMD, CLK = GPIO6 to GPIO11), because they are wired to the flash chip and using them crashes the board.

※ OUR MESSAGES

  • As freelancers, We are AVAILABLE for HIRE. See how to outsource your project to us
  • Please feel free to share the link of this tutorial. However, Please do not use our content on any other websites. We invested a lot of effort and time to create the content, please respect our work!