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.

Clock Source

First you need to set the source that clocks the timer. There are three options:

  1. Internal (16MHz System clock)
  2. External input
  3. 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.

Table 1. Timer/Counter clock source options

Figure 1. Timer/Counter control register 1 B (TCCR1B) clock select bits

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.

TCCR1B|=((1<<CS11)|(1<<CS10));// Clock/64

Operating mode

You then need to set the timer/counter operating mode. There are essentially three main operating modes:

  1. Normal: In this mode the counter simply counts up the maximum value (65535 for the 16 bit counter) and then resets to zero
  2. Count to Compare (CTC): Counts from 0 to value set in the output compare register OCRnA register then resets to 0
  3. 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.

Table 1 Waveform Generation Modes

Figure 2. Timer/Counter 1 Control Register 1 A and B (TCCR1A, TCCR1B) waveform generation mode bits

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;

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s