8. Controlling a servo
This section explains how to control a hobby
RC servo
[http://www.pololu.com/catalog/category/23]
from an Arduino Uno
or Arduino Leonardo that is connected to the Zumo Shield. The Arduino IDE includes a
Servo
[http://arduino.cc/en/
Reference/Servo]
library that generates the pulses needed to control an RC servo. However, this servo library conflicts
with the ZumoMotors library in that both rely on Timer 1. Instead, you will need to do something special to get servo
control working.
To control a servo with an Arduino Uno, see
Section 8.a
. To control a servo with an Arduino Leonardo, see
Section
8.b
.
8.a. Controlling a servo with an Arduino Uno
The example Arduino Uno code below shows how to control a single servo using Timer 2. Because it uses Timer 2
instead of Timer 1, this code does not interfere with the ZumoMotors library, but it will interfere with the ZumoBuzzer
library, so you will not be able to use this and the buzzer at the same time. You can integrate this code with other code
that drives the motors.
/** Arduino Uno Timer 2 Servo Example
This example code for the Arduino Uno shows how to use Timer 2 on
the ATmega328P to control a single servo. This can be useful for
people who cannot use the Arduino IDE's Servo library. For
example, the ZumoMotors library uses the same timer as the Servo
library (Timer 1), so the two libraries conflict.
The SERVO_PIN macro below specifies what pin to output the
servo on. This pin needs to be connected to the signal input
line of the servo. The Arduino's GND needs to be connected to
the ground pin of the servo. The servo's ground and power pins
need to be connected to an appropriate power supply.
*/
// This line specifies what pin we will use for sending the
// signal to the servo. You can change this.
#define SERVO_PIN 11
// This is the time since the last rising edge in units of 0.5us.
uint16_t volatile servoTime = 0;
// This is the pulse width we want in units of 0.5us.
uint16_t volatile servoHighTime = 3000;
// This is true if the servo pin is currently high.
boolean volatile servoHigh = false;
void setup()
{
servoInit();
}
void loop()
{
servoSetPosition(1000); // Send 1000us pulses.
delay(1000);
servoSetPosition(2000); // Send 2000us pulses.
delay(1000);
}
// This ISR runs after Timer 2 reaches OCR2A and resets.
// In this ISR, we set OCR2A in order to schedule when the next
// interrupt will happen.
// Generally we will set OCR2A to 255 so that we have an
// interrupt every 128 us, but the first two interrupt intervals
// after the rising edge will be smaller so we can achieve
// the desired pulse width.
ISR(TIMER2_COMPA_vect)
{
// The time that passed since the last interrupt is OCR2A + 1
// because the timer value will equal OCR2A before going to 0.
ser= OCR2A + 1;
Pololu Zumo Shield for Arduino User's Guide
© 2001–2013 Pololu Corporation
8. Controlling a servo
Page 36 of 38