Move a Servo Arm
Part of the Outputs section of Coddy's Arduino journey. Lesson 20 of 24.
A servo is a small motor with an arm that turns to an angle you choose, from 0 to 180 degrees, and holds it there. It has three wires: power (5V), ground, and a signal wire on any pin.
The board tells the servo the angle with a pulse about every 20 ms. The Servo library sends those pulses for you. A library is code someone else wrote that your sketch can use; #include brings it in:
#include <Servo.h>
Servo arm; // a servo called arm
void setup() {
arm.attach(9); // its signal wire is on pin 9
}
void loop() {
arm.write(90); // turn the arm to 90 degrees
}Servo arm; makes a servo object, a variable that comes with its own functions. You call them with a dot: arm.attach() and arm.write().
Without attach() the library does not know the pin and sends no pulses, so the arm never moves.
Challenge
EasyThe servo signal is on pin 9. Point the arm, one second each, again and again:
- 0 degrees
- 90 degrees
- 180 degrees
Press Run, then Check.
Try it yourself
#include <Servo.h>
Servo arm;
void setup() {
// tell arm its signal is on pin 9
}
void loop() {
// 0 degrees, 90 degrees, 180 degrees, one second each
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Outputs
Practice on your own: Arduino playground