8.3 PWM Control

Although one can use software to produce the pulse signal required by R/C servos, it is much better to use dedicated hardware to do so.

For example, Parallax BASIC Stamps use the software approach. While it is easy to specify the pulses, it is difficult to send the pulses and perform other tasks at the same time. You can control multiple R/C servos at the same time with a BASIC Stamp because the pulses for each R/C servo need to be spaced out by 20ms.

In the ATMega128 (and some other AVR variants), the built-in PWM component of the timers can be used to generate the necessary pulses for R/C servo control. Timer 1 and Timer 3 each has 3 channels of PWM, providing a total of 6 channels of PWM waveforms.

To utilize a timer and its associated PWM ability to control R/C servos, the timer must be configured as follows:

This means we want to have as many counts as possible in 20ms. Because timer1 and timer3 both have 16-bit timer counters, the largest count value is 65536. $\frac{20\mathrm{ms}}{65536}$ is approximately 0.3$\mu$s. Assuming the master clock is 16MHz, this means we need a prescale constant of $0.3\mu\mathrm{s} \times 16000000$, which is approximately 4.88.

The closest prescale constant is 8. Each counter increment then takes $\frac{8}{16000000\mathrm{Hz}}$, which is 0.5$\mu$s. The resolution of the pulse is then $\frac{1\mathrm{ms}}{0.5\mu\mathrm{s}}$, which is 2000 steps over 1ms. This provides sufficient precision over 180 degrees of rotation.

The period of the pulses should be 20ms. The count value for 20ms is $\frac{20\mathrm{ms}}{0.5\mu\mathrm{s}}$, which is 40,000. Register ICR can be initialized to 40,000 to control the period of the pulses.

The timer should also specify fast PWM operation for each output compare (OC) output pin.

Copyright © 2006-02-15 by Tak Auyeung