{
// Move to next position
servo1.write(position);
// Short pause to allow it to move
delay(20);
}
// Tell servo to go to 0 degrees, stepping by one degree
for(position = 180; position >= 0; position
= 1)
{
// Move to next position
servo1.write(position);
// Short pause to allow it to move
delay(20);
}
}
Code to Note
#include <Servo.h>
#include
is a special “preprocessor” command that inserts a library (or
any other file) into your sketch. You can type this command yourself, or
choose an installed library from the “sketch / import library” menu.
Servo servo1;
When you use a library, you create what is called an object of that library
and name it. This object is a Servo library object, and it is named servo1. If
you were using multiple servos you would name each one in this way.
servo1.attach(9);
The Servo library adds new commands that let you control a servo. To
prepare the RedBoard to control a servo, you must first create a Servo
“object” for each servo (here we’ve named it “servo1”), and then “attach” it
to a digital pin (here we’re using pin 9). Think of this as the servo’s way of
calling a pinMode() function.
servo1.write(180);
The servos in this kit don’t spin all the way around, but they can be
commanded to move to a specific position. We use the Servo library’s
write()
command to move a servo a specified number of degrees (0 to
180). Remember that the servo requires time to move, so give it a short
delay()
if necessary.
What You Should See
You should see your servo motor move to various locations at several
speeds. If the motor doesn’t move, check your connections and make sure
you have verified and uploaded the code, or see the Troubleshooting
section.
Page 47 of 63