# Generating servo signal in atmega2560

I'm new to AtmelStudio. I need to know how to generate a servo control signal using timer modules of atmega2560. I'm using an Arduino Mega board. (please refer the last paragraphs of this page for more info about servo control signals).

I'm not sure about how to do exact timing. The clock selection part is a bit confusing for me always.

How should I configure the timer module (TCCR registers) and how to do the timing? It's better if there's a working code example.

(I've tried using timer 0 under fast PWM mode. It gives pulses accordingly but I don't how to calculate proper timing pre-scalers. I've doubts about the primary clock used. Is it the 16MHz crystal on the Arduino board or is there some other inbuilt clock source inside the atmega2560 so that we have to explicitly mention which clock to use??)

• There are fuse settings which you can 'flash' which determine which clock source your microcontroller uses (you're right in guessing there is an internal oscillator which can be used in place of the 16MHz crystal). For starters, you can download the arduino IDE and then open up the source files for the servo library. – NickHalden Jan 3 '13 at 18:54
• Fuses on Arduino are rarely touched. It may kill the bootloader. As @NickHalden mentions, why not use the standard servo libraries? – jippie Jan 3 '13 at 21:40
• @NickHalden yeah, I've used Arduino IDE and I'm OK with it. I need to move to AtmelStudio so that you can do some real coding. But I'm trying everything just with the help of atmega2560 datasheet. I'll be really nice if i can find some good tutorial with some working and complete examples, at least just for driving a servo.. – Anubis Jan 4 '13 at 5:32
• @jippie please refer above comment..(not allowed to refer two people in a single comment :D) – Anubis Jan 4 '13 at 5:37

Since the question asks for working AVR code for servo control, this article, though written for the ATmega32 microcontroller, would be an excellent resource.

On an Arduino board, the primary clock typically used for the Timer/Counters 0..n is the crystal on the board, typically 16 MHz, though some Arduinos / clone boards use 8 MHz or 20 MHz crystals as well. Section 18 of the datasheet addresses selection of clock source / prescaler from either external or internal clocks.

You do have the option of using the ATmega2560 "calibrated internal oscillator", essentially an inbuilt RC timer, but that lacks precision / stability, as might be needed for the servo signal, depending on the application. To use the internal oscillator, set CKSEL3:0 to 0010. From Section 10.3.1 of the datasheet:

The device is shipped with internal RC oscillator at 8.0MHz and with the fuse CKDIV8 programmed, resulting in 1.0MHz system clock. The startup time is set to maximum and time-out period enabled. (CKSEL = "0010", SUT = "10", CKDIV8 = "0").