Load up the following sketch onto your Arduino. You should find that the servo immediately begins to turn first in one direction and then back in the other.
The sketch is based on the standard 'sweep' sketch that you can find in the Arduino Examples under the folder 'servo'. You can if you prefer just run that sketch.
/* Adafruit Arduino - Lesson 14. Sweep */ #include <Servo.h> int servoPin = 9; Servo servo; int angle = 0; // servo position in degrees void setup() { servo.attach(servoPin); } void loop() { // scan from 0 to 180 degrees for(angle = 0; angle < 180; angle++) { servo.write(angle); delay(15); } // now scan back from 180 to 0 degrees for(angle = 180; angle > 0; angle--) { servo.write(angle); delay(15); } }
Servo motors are controlled by a series of pulses and to make it easy to use them, an Arduino library has been created so that you can just instruct the servo to turn to a particular angle.
The commands for using a servo are like built-in Arduino commands, but because you are not always going to be using a servo in your projects, they are kept in something called a library. If you are going to use commands in the servo library, you need to tell the Arduino IDE that you are using the library with this command:
#include <Servo.h>
As usual, we then use a variable 'servoPin' to define the pin that is to control the servo.
This line:
Servo servo;
defines a new variable 'servo' of type 'Servo'. The library has provided us with a new type, like 'int' or 'float' that represents a servo. You can actually define up to eight servos in this way, so if we had two servos, then we could write something like this:
Servo servo1; Servo servo2;
In the 'setup' function we need to link the 'servo' variable to the pin that will control the servo using this command:
servo.attach(servoPin);
The variable 'angle' is used to contain the current angle of the servo in degrees. In the 'loop' function, we use two 'for' loops to first increase the angle in one direction and then back in the other when it gets to 180 degrees.
The command:
servo.write(angle);
tells the servo to update its position to the angle supplied as a parameter.
Page last edited October 18, 2012
Text editor powered by tinymce.