Arduino UNO R4 - Ultrasonic Sensor - Servo Motor
In this tutorial, we'll learn how to use an ultrasonic sensor to control a servo motor with an Arduino Uno R4 based on object distance. When an object is close, the servo motor will rotate to 90 degrees. When the object moves away, the servo will return to 0 degrees. This project is great for beginners to explore ultrasonic distance sensing and servo motor control with Arduino Uno R4.
Hardware Preparation
Or you can buy the following sensor 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 Servo Motor and Ultrasonic Sensor
If you are unfamiliar with servo motors and ultrasonic sensors (their pinout, functioning, and programming instructions), please refer to the tutorials below:
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 - Ultrasonic Sensor Controls Servo Motor
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 servo motor and ultrasonic sensor to the Arduino Uno R4 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 and paste the above code into the Arduino IDE.
- Press the Upload button in the Arduino IDE to transfer the code to the Arduino UNO R4.
- Wave your hand in front of the sensor.
- Observe how the servo motor moves in response.
※ NOTE THAT:
The code provided is meant for learning. The ultrasonic sensor is easily affected by noise. To use the ultrasonic sensor effectively, you should remove noise. For guidance on how to do this, visit how to filter noise for ultrasonic sensor.