Following on from last week where we drove a motor in one direction with the help of a simple amplifier, this week we are going to have a go at driving a servo. Those of you who read older posts in my blog will know I have done this before when I wanted to know how electrically noisy they were.
The code here is fairly simple and again I am using the servo provided in the Oomlout kit, however an SG90 servo1 or similar would work just as well.
Servo motors are a specific kind of motor with a built in controller. The kind that most people use come from the Remote Control model sector. They have three pins. Power, ground and signal. The signal is a PWM2 square wave with the duration of the high varying between 1 ms and 2 ms.
A servo pulse of 1.5 ms width will typically set the servo to its “neutral” position (typically half of the specified full range), a pulse of 1.0 ms will set it to 0°, and a pulse of 2.0 ms to full range.
The SG90 has a range of about 180°.
Because controlling a servo is slightly more complicated than what we have done previously we will take advantage of a library that is bundled with the Arduino IDE. The library file we will use is called Servo.h
</pre>
// Sweep
// by BARRAGAN <http://barraganstudio.com>
#include <Servo.h>
Servo myservo; // create servo object to control a servo
// a maximum of eight servo objects can be created
int pos = 0; // variable to store the servo position
void setup()
{
myservo.attach(9); // attaches the servo on pin 9 to the servo object
}
void loop()
{
for(pos = 0; pos < 180; pos += 1) // goes from 0 degrees to 180 degrees
{ // in steps of 1 degree
myservo.write(pos); // tell servo to go to position in variable 'pos'
delay(15); // waits 15ms for the servo to reach the position
}
for(pos = 180; pos>=1; pos-=1) // goes from 180 degrees to 0 degrees
{
myservo.write(pos); // tell servo to go to position in variable 'pos'
delay(15); // waits 15ms for the servo to reach the position
}
}
<pre>
- SG90 Servo Datasheet
- pulse width modulated