RC Servo Motor Control

Here I will present a servo control code I wrote for the BrontoBot to run on most AtMega AVRs.

Truth be told, I’ve been using a servo code written by my friend Paal since 2008. It was a good code, so I didn’t really need to make my own. But, it had two weaknesses:
– Required a 16-bit timer
– Could only run servos connected to the same port

It follows that I wanted to write a servo code that used any port and any pin, any timer and even leaves the timer ISRs open to be used for other things. This would allow me to simplify the electronics layout for the BrontoBot.

Timers on AtMega16U4

The AtMega16U4 comes with four timers:
– 8-bit timer (TIMER0)
– 2x 16-bit timers (TIMER1 & TIMER3)
– 10-bit timer (TIMER4)

The 10-bit timer is special for the usb-core models, and can run up to 64Mhz.

Using the code

The servo code consists of a set, get and init function. It is limited to a maximum of 8 servos per timer. The servo_set function takes an unsigned char as input, where 0 gives a 1ms pulse and 255 gives approx 2ms.


Each servo can be set up on any pin of any port, by editing the following part of the servo.c file:

This example configuration sets up three servos, on port D, C and B. They all start at the servos middle position. The code also calls a function pointer every 40ms, which can be used for anything. In the bronto bot, this is used for movement timing. Point like this:

The code is set up to use a 16MHz crystal, so to use it for other frequencies the prescalers must be changed.


Here is the full servo.c file, set up with four servos:


And here the servo.h file:

GitHub Link



  1. Jerold Dompe

    thanks 🙂

    1. larsivar

      You’re welcome!

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">