8.b. Controlling a servo with an Arduino Leonardo or A-Star 32U4 Prime
It is possible to modify the Servo library that comes with the Arduino IDE to use Timer 3 instead of
Timer 1 on the Arduino Leonardo or A-Star 32U4 Prime. The modified Servo library does not interfere
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
// The servo pin is currently high.
// Check to see if is time for a falling edge.
// Note: We could == instead of >=.
if
(servoTime >= highTimeCopy)
{
// The pin has been high enough, so do a falling edge.
digitalWrite(SERVO_PIN, LOW);
servoHigh =
false
;
interruptCount = 0;
}
}
else
{
// The servo pin is currently low.
if
(servoTime >= 40000)
{
// We've hit the end of the period (20 ms),
// so do a rising edge.
highTimeCopy = servoHighTime;
digitalWrite(SERVO_PIN, HIGH);
servoHigh =
true
;
servoTime = 0;
interruptCount = 0;
OCR2A = ((highTimeCopy % 256) + 256)/2 - 1;
}
}
}
void
servoInit()
{
digitalWrite(SERVO_PIN, LOW);
pinMode(SERVO_PIN, OUTPUT);
// Turn on CTC mode.
Timer 2 will count up to OCR2A, then
// reset to 0 and cause an interrupt.
TCCR2A = (1 << WGM21);
// Set a 1:8 prescaler.
This gives us 0.5us resolution.
TCCR2B = (1 << CS21);
// Put the timer in a good default state.
TCNT2 = 0;
OCR2A = 255;
TIMSK2 |= (1 << OCIE2A);
// Enable timer compare interrupt.
sei();
// Enable interrupts.
}
void
servoSetPosition(uint16_t highTimeMicroseconds)
{
TIMSK2 &= ~(1 << OCIE2A);
// disable timer compare interrupt
servoHighTime = highTimeMicroseconds * 2;
TIMSK2 |= (1 << OCIE2A);
// enable timer compare interrupt
}
Pololu Zumo Shield for Arduino User’s Guide
© 2001–2019 Pololu Corporation
8. Controlling a servo
Page 51 of 52