Servo motors are an important part of many robotics projects. A servo can move to arbitrary positions within some range of motion, usually 180 degrees. You might think of them like mechanical elbows.
Most Arduino boards can only supply enough power to move very tiny servos (like the 9g variety for steering small RC vehicles) – and no more than one unless you are careful to move them one at a time. This is helpful for prototyping and debugging isolated parts of a larger robot before moving them off to a different circuit with external power.
Arduino includes a library for controlling common servos. Usage is very simple:
- Instantiate a
Servo
object. - Assign the pin number that will send control signals to the servo.
- Call methods on the
Servo
object to set its position.
#include <Servo.h>
// Instantiate a Servo as a variable named myServo.
Servo myServo;
void setup()
{
// Assign pin 9 to the servo.
myServo.attach(9);
}
void loop()
{
// Move to the 90 degree (middle) position.
myServo.write(90);
}
For a slightly more complex example, this code will move the servo back and forth in short increments.
#include <Servo.h>
Servo myServo;
void setup()
{
myServo.attach(9);
}
void loop()
{
myServo.write(165);
delay(250);
myServo.write(150);
delay(250);
myServo.write(15);
delay(250);
// Change the angle for multiple steps in a loop
for (int angle = 90; angle <= 150; angle += 15)
{
myServo.write(angle);
delay(250);
}
}
And here is a demonstration video:
Control servo with buttons
Now that we've introduced both servos and buttons, let's see how they can be combined. Debouncing won't be necessary because the servo is already not very responsive.
Here is the full code:
#include <Servo.h>
const int servoPin = 9;
const int leftButtonPin = 2;
const int rightButtonPin = 4;
const int minAngle = 15;
const int midAngle = 90;
const int maxAngle = 165;
Servo servo;
void setup()
{
pinMode(leftButtonPin, INPUT);
pinMode(rightButtonPin, INPUT);
servo.attach(servoPin);
}
void loop()
{
int leftButtonState = digitalRead(leftButtonPin);
int rightButtonState = digitalRead(rightButtonPin);
if (rightButtonState == HIGH)
{
servo.write(maxAngle);
}
else if (leftButtonState == HIGH)
{
servo.write(minAngle);
}
else
{
servo.write(midAngle);
}
delay(100);
}