Use the Servo library distributed with Arduino. Connect the servo power and ground to a suitable power supply (a single hobby servo can usually be powered from the Arduino 5V line). Recent versions of the library enable you to connect the servo signal leads to any Arduino digital pin.
Here is the example Sweep sketch distributed with Arduino; the image below shows the connections:
#include <Servo.h>
Servo myservo; // create servo object to control a servo
int angle = 0; // variable to store the servo position
void setup()
{
myservo.attach(9); // attaches the servo on pin 10 to the servo object
}
void loop()
{
for(angle = 0; angle < 180; angle += 1) // goes from 0 degrees to 180 degrees
{ // in steps of 1 degree
myservo.write(angle); // tell servo to go to position in variable 'angle'
delay(20); // waits 20ms between servo commands
}
for(angle = 180; angle >= 1; angle -= 1) // goes from 180 degrees to 0 degrees
{
myservo.write(pos); // tell servo to go to position in variable 'pos'
delay(20); // waits 20ms between servo commands
}
}
This example sweeps the servo between 0 and 180 degrees. You may need to tell the library to adjust the minimum and maximum positions so that you get the range of movement you want. Calling
Servo.attach with optional arguments for minimum and maximum positions will adjust the movement:myservo.attach(9,1000,2000 ); // use pin 9, set min to 1000us, max to 2000us
Because typical servos respond to pulses measured in microseconds and not degrees, the arguments following the pin number inform the Servo library how many microseconds to use when 0 degrees or 180 degrees are requested. Not all servos will move over a full 180-degree range, so you may need to experiment with yours to get the range you want.
The parameters for
servo.attach(pin, min, max) are the following:pin
min (optional)
max (optional)
Power requirements vary depending on the servo and how much torque is needed to rotate the shaft.
Note: You may need an external source of 5 or 6 volts when connecting multiple servos. Four AA cells work well if you want to use battery power. Remember that you must connect the ground of the external power source to Arduino ground.
Create your own robots, toys, remote controllers, alarms, detectors, and many other projects with the Arduino device. This simple microcontroller board lets artists and designers build a variety of amazing objects and prototypes that interact with the physical world. With this book, you can dive right in and experiment with more than a hundred tips and techniques, no matter what your skill level is. You'll find the examples and advice you need to begin, expand, and enhance your projects right away.




Help






