Arduino UNO R4 - Ultrasonic Sensor - Relay
This tutorial instructs you how to use the Arduino Uno R4 to work with an ultrasonic sensor and a relay. You’ll learn to:
- Detect whether something is close or far using the ultrasonic sensor sensor’s signals.
- Turn on the relay when an object is near.
- Turn off the relay when the object moves away.
With this setup, you can connect the relay to cool stuff like lights, motors, or other gadgets and control them using the Arduino and sensor combo!
Hardware Preparation
Or you can buy the following kits:
1 | × | DIYables Sensor Kit (30 sensors/displays) | |
1 | × | DIYables Sensor Kit (18 sensors/displays) |
Additionally, some of these links are for products from our own brand, DIYables .
Overview of Relay and Ultrasonic Sensor
If you're unfamiliar with how a relay and ultrasonic sensor work, including their pinout and programming, you can learn more in the following tutorials:
Wiring Diagram

This image is created using Fritzing. Click to enlarge image
See The best way to supply power to the Arduino Uno R4 and other components.
Arduino UNO R4 Code
Detailed Instructions
Follow these instructions step by step:
- If this is your first time using the Arduino Uno R4 WiFi/Minima, refer to the tutorial on setting up the environment for Arduino Uno R4 WiFi/Minima in the Arduino IDE.
- Wire the components according to the provided diagram.
- Connect the Arduino Uno R4 board to your computer using a USB cable.
- Launch the Arduino IDE on your computer.
- Select the appropriate Arduino Uno R4 board (e.g., Arduino Uno R4 WiFi) and COM port.
- Copy the code provided and paste it in the Arduino IDE.
- Press the Upload button in the Arduino IDE to transfer the code to your Arduino UNO R4.

- Put your hand in front of the sensor
- Watch the relay's state change
Code Explanation
Check the explanation in the comments of the source code, line by line!
※ NOTE THAT:
The code provided is meant for educational use. The ultrasonic sensor reacts strongly to noise. To effectively use the ultrasonic sensor, it's important to reduce this noise. You can learn how to do this at how to filter noise for ultrasonic sensor.