Servo sweep
Sweep a hobby servo back and forth from 0° to 180° with the Servo library.
Motors · Beginner
In a real product: Robot joint (Robotics): A servo sweeps through its range.
A hobby servo is a small motor with a gearbox and a position sensor, which turns to the angle you ask for and holds it. They steer RC cars, move robot arms and open little doors.
What you'll learn
- The servo's control signal: a pulse every 20 ms whose width sets the angle
Servo.attach()andServo.write()- Moving slowly by stepping the angle a degree at a time
How it works
A servo has three wires: GND (brown or black), power (red, V+) and signal (orange or yellow). The signal goes to pin 9.
The Servo library sends a pulse 50 times a second. Its width tells the servo where to go: about 544 µs is 0°, 1470 µs is 90° and 2400 µs is 180°. servo.write(angle) sets the width, and the servo's own controller turns the motor until its position sensor matches.
The loop steps the angle one degree every 15 ms, so a full sweep takes under 3 seconds each way.
A real servo can draw too much current for the Uno's 5V when it moves fast or is loaded; power it from its own supply, with the grounds joined.
Try this
- Make it move to 0°, 90° and 180° and pause at each, like a three-position switch.
- Use
servo.writeMicroseconds()for finer steps. - Control the angle with a potentiometer or a joystick.
sketch.ino
// Sweep a servo on pin 9 from 0 to 180 degrees and back.
#include <Servo.h>
Servo servo;
void setup() {
servo.attach(9);
}
void loop() {
for (int angle = 0; angle <= 180; angle++) {
servo.write(angle);
delay(15);
}
for (int angle = 180; angle >= 0; angle--) {
servo.write(angle);
delay(15);
}
}