Arduino Nano - Ultrasonic Sensor - Servo Motor
This tutorial instructs you how to use Arduino Nano and ultrasonic sensor to control servo motor. In detail:
- If an object is close to the ultrasonic sensor, Arduino Nano rotates the servo motor to 90 degrees.
- If an object is far from the ultrasonic sensor, Arduino Nano rotates the servo motor back to 0 degrees.
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 (including pinouts, how they work, and how to program them), the following tutorials can help:
Wiring Diagram
This image is created using Fritzing. Click to enlarge image
Please note that the wiring diagram shown above is only suitable for a servo motor with low torque. In case the motor vibrates instead of rotating, an external power source must be utilized to provide more power for the servo motor. The below demonstrates the wiring diagram with an external power source for servo motor.
This image is created using Fritzing. Click to enlarge image
Please do not forget to connect GND of the external power to GND of Arduino Nano.
Arduino Nano Code - Ultrasonic Sensor Controls Servo Motor
Detailed Instructions
- Connect your Arduino Nano to a computer using a USB cable.
- Open the Arduino IDE, select the correct board and port.
- Copy the code and open it in the Arduino IDE.
- Click the Upload button in the Arduino IDE to compile and upload the code to the Arduino Nano.
- Wave your hand in front of the sensor.
- Check out the change in the servo motor.
※ NOTE THAT:
The code above is for educational purposes. The ultrasonic sensor is very susceptible to noise. If you intend to use the ultrasonic sensor in a practical setting, you should filter out the noise from the ultrasonic sensor. For more information on how to do this, please refer to how to filter noise for ultrasonic sensor.