8-Bit AVR® MCU Timer Example

This page illustrates several methods of configuring the timers on an 8-bit AVR® MCU. An overview of the timers on an AVR are provided before the step-by-step example is presented.

Requirements to Run the Hands-on Examples

Hardware Requirements

  • ATmega328PB Xplained Mini board
  • Micro-USB Cable
Tool About Purchase
ATmega328PB-XplainedMini-50px.png
ATmega328PB Xplained Mini
Evaluation Kit

The ATmega328PB Xplained Mini evaluation kit is a hardware platform for evaluating the Atmel ATmega328PB microcontroller. An external Debugger kit is NOT needed to run these labs. The ATmega328PB has a fully integrated embedded debugger on-board.

This hands-on exercise demonstrates how to set up the different timers.

Software Tools

Tool About Installers
Installation
Instructions
Windows Linux Mac OSX
swtool-28px.png
Atmel® Studio
Integrated Development Environment

Additional Files

Files

Overview of Timers on 8-bit AVR MCUs

ATmega328PB microcontroller has five Timer/Counters:

Timer 0 TC0 8-bit Timer/counter with PWM
Timer 1 TC1 16-bit Timer/counter with PWM and Asynchronous Operation.
Timer 2 TC2 8-bit Timer/counter with PWM and Asynchronous Operation.
Timer 3 TC3 16-bit Timer/counter with PWM and Asynchronous Operation.
Timer 4 TC4 16-bit Timer/counter with PWM and Asynchronous Operation.

Definitions:

Register Nomenclature
BOTTOM The counter reaches the BOTTOM when it becomes zero (0x00 for 8-bit counters and 0x0000 for 16bit counters
MAX The counter reaches its maximum value when it becomes 0x0F (15 decimal) for 8-bit counters and 0x00FF (255 decimal) for 16-bit counters
TOP The counter reaches the TOP when its value becomes equal to the highest value possible. The TOP value can be assigned fixed value MAX or the value stored in the OCRxA register. This assignment is dependent upon the mode of operation

Timer 0 - 8-bit Timer/Counter with PWM

Timer/Counter0 (TC0) is a general purpose 8-bit Timer/Counter module, with two independent Output Compare Units, and PWM support.

TC0 Registers

The Timer/Counter 0 register (TCNT0) and Output Compare TC0x registers (OCR0x) are 8-bit registers. Interrupt request signals are all visible in the Timer Interrupt Flag Register 0 (TIFR0). All interrupts are individually masked with the Timer Interrupt Mask Register 0 (TIMSK0).

TCCR0B.PNG

TC0 Timer/Counter Clock Sources

TC0 can be clocked by an internal or an external clock source. The clock source is selected by writing to the Clock Select (CS02:0) bits in the Timer/Counter Control Register (TCCR0B).

Bits 2:0 – CS0n: Clock Select [n = 0..2]

The three Clock Select bits select the clock source to be used by the Timer/Counter.

CS02 CS01 CS00 Description
0 0 0 No Clock source (Timer stopped)
0 0 1 clkio/1 (No prescaling)
0 1 0 clkio/8 (From prescaler)
0 1 1 clkio/64 (From prescaler)
1 0 0 clkio/256 (From prescaler)
1 0 1 clkio/1012 (From prescaler)
1 1 0 External clock source on T0 pin (clock on falling edge)
1 1 1 External clock source on T0 pin (clock on rising edge)

TC0 Counter Unit

Depending on the mode of operation used, T0 is cleared, incremented, or decremented at each timer clock (clkT0). clkT0 can be generated from an external or internal clock source, selected by the Clock Select bits (CS0[2:0]).

The counting sequence is determined by the setting of the WGM01 and WGM00 bits located in the T0 Control Register A (TCCR0A) and the WGM02 bit located in the Timer/Counter Control Register B (TCCR0B).

Bits 1:0 – WGM0n: Waveform Generation Mode [n = 1:0]

Combined with the WGM02 bit found in the TCCR0B Register, these bits control the counting sequence of the counter, the source for maximum (TOP) counter value, and what type of waveform generation to be used. Modes of operation supported by the Timer/Counter unit are: Normal mode (counter), Clear Timer on Compare Match (CTC) Mode, and two types of Pulse Width Modulation (PWM) modes.

Table 1-2 Waveform Generation Mode Bit Description

Mode WGM2:0 Mode of Operation TOP OCR0x Update TOV flag set on
0 0 0 0 Normal 0xFF Immediate MAX
1 0 0 1 PWM Phase Correct 0xFF TOP BOTTOM
2 0 1 0 CTC OCRA Immediate MAX
3 0 1 1 Fast PWM 0xFF BOTTOM MAX
4 1 0 0 Reserved ~ ~ ~
5 1 0 1 PWM Phase Correct OCRA TOP BOTTOM
6 1 1 0 Reserved ~ ~ ~
7 1 1 1 Fast PWM OCRA BOTTOM MAX

Note:
1. MAX = 0xFF
2. BOTTOM = 0x00

Modes of Operation for TC0

The mode of operation determines the behavior of TC0 and the Output Compare pins. It is defined by the combination of the Waveform Generation mode bits and Compare Output mode bits in the Timer/Counter control Registers A and B (TCCR0B.WGMn2, TCCR0A.WGM01, TCCR0A.WGM00, and TCCR0A.COM0x[1:0]).

Available modes of operation for TC0 are:

  • Normal Mode
  • Clear Timer on Compare Match (CTC) Mode
  • Fast PWM Mode
  • Phase Correct PWM Mode

Clear Timer on Compare Match Mode

In Clear Timer on Compare mode (WGM0[2:0]=0x2), the OCR0A Register is used to manipulate the counter resolution: the counter is cleared to ZERO when the counter value (TCNT0) matches the OCR0A. The OCR0A defines the top value for the counter, hence also its resolution.

The counter value (TCNT0) increases until a compare match occurs between TCNT0 and OCR0A, and then counter (TCNT0) is cleared. An interrupt can be generated each time the counter value reaches the TOP value by setting the OCF0A Flag. If the interrupt is enabled, the interrupt handler routine can be used for updating the TOP value.

The waveform frequency is defined by the following equation:

freqz0.PNG

N represents the prescaler factor (1, 8, 64, 256, or 1024).

TC1, TC3, & TC4 - 16-bit Timer/Counters with PWM

The 16-bit Timer/Counter units allow accurate program execution timing (event management), wave generation, and signal timing measurement.

Registers (TC1, TC3, TC4)

  • The Timer/Counter (TCNTn), Output Compare Registers (OCRA/B), and Input Capture Register (ICRn) are all 16-bit registers.
  • The Timer/Counter Control Registers (TCCRnA/B) are 8-bit registers and have no CPU access restrictions.
  • Interrupt requests (abbreviated to Int.Req. in the block diagram) signals are all visible in the Timer Interrupt Flag Register (TIFRn). All interrupts are individually masked with the Timer Interrupt Mask Register (TIMSKn).

Timer/Counter Clock Sources (TC1, TC3, TC4)

The Timer/Counter can be clocked by an internal or an external clock source. The clock source is selected by the Clock Select logic which is controlled by the Clock Select bits in the timer/Counter control Register B (TCCRnB.CS[2:0]).

TCCR1B.PNG

Bits 2:0 – CS[2:0]: Clock Select [n = 0..2]
The three Clock Select bits select the clock source to be used by the Timer/Counter.

CS02 CS01 CS00 Description
0 0 0 No Clock source ( Timer stopped
0 0 1 clkio/1 (No prescaling)
0 1 0 clkio/8 (From prescaler)
0 1 1 clkio/64 (From prescaler)
1 0 0 clkio/256 (From prescaler)
1 0 1 clkio/1012 (From prescaler)
1 1 0 External clock source on T0 pin (clock on falling edge)
1 1 1 External clock source on T0 pin (clock on rising edge)

Counter Unit (TC1, TC3, TC4)

TC1, TC3, and TC4 are programmable 16-bit bi-directional counters.

Each 16-bit counter is mapped into two 8-bit I/O memory locations: Counter High (TCNTnH) containing the upper eight bits of the counter, and Counter Low (TCNTnL) containing the lower eight bits.

Depending on the selected mode of operation, the counter is cleared, incremented, or decremented at each timer clock (clkTn). The clock clkTn can be generated from an external or internal clock source, as selected by the Clock Select bits in the Timer/Counter Control Register B (TCCRnB.CS[2:0]).

The counting sequence is determined by the setting of the Waveform Generation mode bits in the Timer/Counter Control Registers A and B (TCCRnB.WGM[3:2] and TCCRnA.WGM[1:0]).

Modes of Operation (TC1, TC3, TC4)

The mode of operation is determined by the combination of the Waveform Generation mode (WGM[3:0]) and Compare Output mode (TCCRnA.COMx[1:0]) bits.

Available modes of operation are:

  • Normal Mode
  • Clear Timer on Compare Match (CTC) Mode
  • Fast PWM Mode
  • Phase Correct PWM Mode
  • Phase and Frequency Correct PWM Mode

Fast PWM Mode

The Fast Pulse Width Modulation or Fast PWM modes (modes 5, 6, 7, 14, and 15, WGM[3:0]= 0x5, 0x6, 0x7, 0xE, 0xF) provide a high frequency PWM waveform generation option. The Fast PWM differs from the other PWM options by its single-slope operation. The counter counts from BOTTOM to TOP then restarts from BOTTOM.

In Fast PWM mode the counter is incremented until the counter value matches either one of the fixed values 0x00FF, 0x01FF, or 0x03FF (WGM[3:0] = 0x5, 0x6, or 0x7), the value in ICRn (WGM[3:0]=0xE), or the value in OCRnA (WGM[3:0]=0xF). The counter is then cleared at the following timer clock cycle.

The PWM frequency for the output can be calculated by the following equation:

freqz1.PNG

Note:
• The “n” in the register and bit names indicates the device number (n = 0 for Timer/Counter 0), and the “x” indicates Output Compare unit (A/B).
• N represents the prescale divider (1, 8, 64, 256, or 1024).

TC2 - 8-bit Timer/Counter2 with PWM and Asynchronous Operation

Timer/Counter2 (TC2) is a general purpose, dual channel, 8-bit Timer/Counter module.

TC2 Registers

The Timer/Counter (TCNT2) and Output Compare Register (OCR2A and OCR2B) are 8-bit registers. Interrupt request signals are all visible in the Timer Interrupt Flag Register (TIFR2). All interrupts are individually masked with the Timer Interrupt Mask Register (TIMSK2).

TCCR2B.PNG

TC2 Clock Sources

TC2 can be clocked by an internal synchronous or an external asynchronous clock source:
The three Clock Select bits (CS2:CS0) select the clock source to be used by the Timer/Counter.

CS02 CS01 CS00 Description
0 0 0 No Clock source (Timer stopped)
0 0 1 clkio/1 (No prescaling)
0 1 0 clkio/8 (From prescaler)
0 1 1 clkio/64 (From prescaler)
1 0 0 clkio/256 (From prescaler)
1 0 1 clkio/1012 (From prescaler)
1 1 0 External clock source on T0 pin ( clock on falling edge)
1 1 1 External clock source on T0 pin ( clock on rising edge)

TC2 Counter Unit

Depending on the mode of operation used, the counter is cleared, incremented, or decremented at each timer clock (clkT2). clkT2 can be generated from an external or internal clock source, selected by the Clock Select bits (CS2[2:0]).
The counting sequence is determined by the setting of the WGM21 and WGM20 bits located in the Timer/Counter Control Register (TCCR2A) and the WGM22 bit located in the Timer/Counter Control Register B (TCCR2B).

TC2 Modes of Operation

The mode of operation, i.e., the behavior of the Timer/Counter and the Output Compare pins, is defined by the combination of the Waveform Generation mode (WGM2[2:0]) and Compare Output mode (COM2x[1:0]) bits.
Available modes of operation are:

  • Normal Mode
  • Clear Timer on Compare Match (CTC) Mode
  • Fast PWM Mode
  • Phase Correct PWM Mode

Normal Mode

In the Normal mode (WGM22:0 = 0) the counting direction is always up (incrementing), without having the counter cleared. The counter will roll over to 0c00 when it passes its maximum 8-bit value (TOP = 0xFF).

In normal operation, the Timer/Counter Overflow Flag (TOV2) will be set in the same timer clock cycle as the TCNT2 becomes zero. The TOV2 Flag, in this case, behaves like a ninth bit, except that it is only set, not cleared. However, combined with the timer overflow interrupt that automatically clears the TOV2 flag, the timer resolution can be increased by software. There are no special cases to consider in the Normal mode, a new counter value can be written any time.

Regardless of which mode is used the programmer needs to remember two things:

  1. The timer has to be started by selecting the clock source.
  2. If interrupts are used they must be enabled.

 Step-by-Step

Project Creation

1

Open Atmel Studio 7

2

Select File > New > Project

3

In the New Project window select GCC C executable Project and give the project name to “Timer0Config”. Set the location of the project files. (This example uses "C:\HFO\TimersConfigurations"). Click OK.

new-project.jpg

4

In the search bar of the Device Selection window type "328p" then select the device Atmega328PB, click OK.

select-device.jpg

Programming the board

5

Select Build > Build Solution from the top menu to compile the code. You will see a "BUILD SUCCEEDED" message in the output window of Studio 7.

6

Select Tools > Device Programming , make sure the settings are as in the picture below and click Apply.

program.jpg

7

Select Memories > Program Wait until the "Verifying Flash…OK" message to appear.
.

Project Modifications

avr/io.h and avr/interrupt.h must be "#included" in main.c for this project to compile and run.

  • io.h provides for the definition of all of the AVR peripherals.
  • interrupt.h is required for all applications using interrupts.

8

Modification 1 - Blinking a LED using TC0

In this example Timer 0 blinks the LED connected to PB5 every 32 ms.

a

Modify the main function by adding the following code:

b

Create the function init_TC0 () in main.c. Add the following code:

The preceding code does the following:

  • Configures Timer 0 in CTC mode by setting the corresponding WGM bit in TCCR0A register;
  • Sets the TOP value in the OCR0A register calculated using the equation 1 to blink the LED at 30 kHz;
  • Enables the Timer Interrupt;
  • Sets the pre-scaler to 1024 by configuring the CS00 and CS02 bits in TCCR0B register;

c

Add the interrupt service routine to main.c:

The use of the constant MyTimerConstant and the variable counter is optional. If used, changing the value of MyTimer Constant will alter the time it takes the LED to blink.

9

Modification 2 - Using TC1 in PWM mode to dim the LED

This example uses TC1 to generate a PWM signal which is fed through an I/O pin to drive an LED. Changing the PWM duty-cycle will result in a change in the brightness of the LED.

a

Modify main() by adding the following code.

For configuring the direction bit of pin PB1, write the DDB1 bit to logic 1 in the DDRB register. On the ATmega328PB Xplained Mini Board, LED is connected to PB5 and PWM is generated on PB1. To view the LED dimming, connect a wire from PB5 to PB1 on the ATmega328PB Xplained Mini Board, as shown below.

b

Create the init_TC1_pwm () function before the main loop with the following code:

init_TC!_PWM() performs the following"

  • Sets the bits COMA1=1 and COMA0=0 (non-inverting mode from datasheet table Compare Output Mode, Fast PWM in the TCCR1A register;
  • Configures Bits 1:0 – WGM[1:0]:Waveform Generation Mode accordingly for Fast PWM, 8-bit mode;
  • Verifies the configuration for the clock source and prescaler to be used by the Timer/Counter, which decides the frequency of the PWM. Internal clock source divided by 256 is configured by writing to the CS10 and CS12 bits in TCCR1B register;
  • Enables the Timer Interrupt;

c

Add the ISR function after the main loop to execute dimming LED event:

The register OC1RA decides the duty cycle of PWM. To dim the LED gradually decrease the duty cycle.

10

Blinking an LED using TC2

For this example, Timer 2 (TC2) is configured to blink the LED connected to PB5 at a period of 3 seconds.

a

Modify the main function by adding the following code:

  • Configures the direction bit of pin PB5, write the DDB5 bit to logic 1 in the DDRB register;
  • Sets the prescaler to 1024 by configuring the CS20, CS21 and CS22 bits in TCCR2B register;
  • Clears Overflow flag - TOV2 is cleared by writing a logic one to the flag.
  • Enables global interrupts by calling sei();

b

Enable the Overflow Timer Interrupt;

Add the ISR function after the main loop to execute blinking LED event:

Set the PORTB register to blink the LED

MyTimer2Constant is optional. This constant can be changed to alter the time it takes the LED to blink.

© 2024 Microchip Technology, Inc.
Notice: ARM and Cortex are the registered trademarks of ARM Limited in the EU and other countries.
Information contained on this site regarding device applications and the like is provided only for your convenience and may be superseded by updates. It is your responsibility to ensure that your application meets with your specifications. MICROCHIP MAKES NO REPRESENTATIONS OR WARRANTIES OF ANY KIND WHETHER EXPRESS OR IMPLIED, WRITTEN OR ORAL, STATUTORY OR OTHERWISE, RELATED TO THE INFORMATION, INCLUDING BUT NOT LIMITED TO ITS CONDITION, QUALITY, PERFORMANCE, MERCHANTABILITY OR FITNESS FOR PURPOSE. Microchip disclaims all liability arising from this information and its use. Use of Microchip devices in life support and/or safety applications is entirely at the buyer's risk, and the buyer agrees to defend, indemnify and hold harmless Microchip from any and all damages, claims, suits, or expenses resulting from such use. No licenses are conveyed, implicitly or otherwise, under any Microchip intellectual property rights.