The AtMega2560 has 2 8bit and 4 16bit timer counters. The process for initialising the 8 and 16bit timer counters is similar. Here I describe the process for the 16bit timer1.
First you need to set the source that clocks the timer. There are three options:
- Internal (16MHz System clock)
- External input
- A prescaled clock.
The clock source is chosen by setting bits 0-2 in the TCCR1B register according to table 1. see section 17.11.5 (pg. 161) of the ATmega 2560 data for a full description of the clock select options.
For example to set the Timer/Counter 1 clock source to the /64 output of the prescaler the CS11 and CS10 bits in the TCCR1B register must be set.
You then need to set the timer/counter operating mode. There are essentially three main operating modes:
- Normal: In this mode the counter simply counts up the maximum value (65535 for the 16 bit counter) and then resets to zero
- Count to Compare (CTC): Counts from 0 to value set in the output compare register OCRnA register then resets to 0
- Pulse Width Modulation (PWM): Typically used for providing a digitally controlled analogue output e.g. LED brightness control, motor control, or for waveform generation.
The operating modes are shown in table 1 and the desired operating mode is controlled by setting the highlighted bits in the TCCRnA and TCCRnB registers shown in figure 2. For a full description of the registers see section 17.11.1 (pg. 158) of the ATmega 2560 data sheet.
For example the following code sets the CTC mode such that the counter counts from 0 to 250 and then resets to 0.
TCCR1B|=(1<<WGM12); // Set in CTC mode OCR1A=250; // Set Output compare to 250;