Introduction
Servo motors are commonly used in robotics and automation projects because they can rotate to a specific angle with high accuracy. In this project, we will make a servo motor rotate automatically from 0° to 180° and then back from 180° to 0° continuously using Arduino. This motion is called a servo sweep.
This project helps beginners understand:
-
Servo motor control
-
For loop operation
-
PWM output from Arduino
Components Required
-
Arduino Uno
-
Servo motor (SG90 or similar)
Capacitor (100 µF)
-
Jumper wires
-
Breadboard
-
USB cable
Circuit and Connections
Servo Motor Wiring
-
Red wire → 5V
-
Brown/Black wire → GND
-
Yellow/Orange wire → Digital pin 9
⚠️ For large servos, use an external 5V power supply and connect common ground.
Working Principle
The Arduino sends control pulses to the servo motor through a digital pin. The servo motor rotates to a particular angle depending on the pulse width. In this program, Arduino gradually increases the angle from 0° to 180° in steps of 1 degree, waits briefly, and then decreases the angle back to 0°. This creates a smooth sweeping motion.
Arduino Code
#include <Servo.h>
Servo myservo; // create servo object to control a servo
int pos = 0; // variable to store the servo position
void setup() {
myservo.attach(9); // attaches the servo on pin 9 to the servo object
}
void loop() {
for (pos = 0; pos <= 180; pos += 1) {
myservo.write(pos);
delay(15);
}
for (pos = 180; pos >= 0; pos -= 1) {
myservo.write(pos);
delay(15);
}
}
Code Explanation
1. Include Servo Library
#include <Servo.h>
This library allows Arduino to control servo motors easily.
2. Create Servo Object
Servo myservo;
Creates a servo object named myservo.
3. Variable Declaration
int pos = 0;
Stores the current position (angle) of the servo motor.
4. Setup Function
myservo.attach(9);
Connects the servo motor signal wire to digital pin 9.
5. Loop Function
for (pos = 0; pos <= 180; pos += 1)
Moves the servo from 0° to 180° in steps of 1 degree.
myservo.write(pos);
Rotates the servo to the specified angle.
delay(15);
Gives time for the servo to reach the position.
for (pos = 180; pos >= 0; pos -= 1)
Moves the servo back from 180° to 0°.
Output
-
Servo motor rotates smoothly from 0° to 180°.
-
Then it rotates back from 180° to 0°.
-
This motion repeats continuously.
Applications
-
Radar scanning models
-
Robotic arm movement
-
Automatic gate systems
-
Camera pan systems
-
Educational demonstrations
Conclusion
This project demonstrates how to control a servo motor using Arduino and make it rotate automatically between two angles. It is a simple and effective project for beginners to understand servo control and looping concepts.
Safety Tips
-
Do not stall the servo at end positions
-
Use external power for high torque servos
-
Always connect common ground