Timer/Counter Subsystem

A Dr. Taylor Tutorial

Timer/Counter Subsystem

This will detail Timer/Counter0, but the others are similar.

Overview

Relevant I/O Registers

COM01 COM00 Description
0 0 Normal port operation, OC0 disconnected
0 1 Toggle 0C0 on compare match (TCNT0 = OCR0)
1 0 Clear OC0 on compare match
1 1 Set OC0 on compare match
CS02 CS01 CS00 Description
0 0 0 No clock source (Timer/Counter stopped)
0 0 1 clk
0 1 0 clk/8
0 1 1 clk/64
1 0 0 clk/256
1 0 1 clk/1024
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.

Sample Code

Using Timer/Counter0 to Create a Delay with Polling

.def temp = r16
     ldi   temp, 1<<CS02 | 1<<CS00
     out   TCCR0, temp
     ldi   temp, 0x00
     out   TCNT0, temp
     ldi   temp, 1<<TOV0
     out   TIFR, temp
; ...
.equ CS00 = 0
.equ CS01 = 1
.equ CS02 = 2
; ...
; Function that provides a 5ms delay routine
delay5ms:
.def temp = r16
     push  temp
     ldi   temp, 0xff-78
     out   TCNT0, temp
     ldi   temp, 1<<CS02|1<<CS00
     out   TCCR0, temp
     ldi   temp, 1<<TOV0
     out   TIFR, temp
d5Poll:
     in    temp, TIFR      ; Cannot do sbis on TIFR
     sbrs  temp, TOV0
     rjmp  d5Poll

     pop   temp
     ret

Note:

Using Timer/Counter0 to Create a Timed Event with Interrupts

.include "m32def.inc"

.def temp = r16

.org 0x00
     rjmp  initStack
.org OVF0addr
     rjmp  ovr0ISR
.org 0x2a
initStack:
     ; Normal stuff here.
     
start:
     rcall initTimer0
     sei                    ; Enable global interrupts

; Initialize timer/counter0 to interrupt every 5ms.
initTimer0:
     push  temp

     ldi   temp, 0xff-78     ; make overflow occur in 78 clk ticks.
     out   TCNT0, temp
     ldi   temp, 1<<CS02|1<<CS00
     out   TCCR0, temp
     in    temp, TIFR
     sbr   temp, 1<<TOV0     ; Could have use ori
     out   TIFR, temp
     in    temp, TIMSK
     ori   temp, 1<<TOIE0    ; Enables timer/counter0 interrupt
     out   TIMSK, temp

     pop   temp
     ret

; ISR for timer/counter0 interrupt
; Schedules next interrupt to happen 5ms from now.
ovr0ISR:
     push  temp
     in    temp, SREG
     push  temp

     ldi   temp, 0xff-78     ; make overflow occur in 78 clk ticks.
     out   TCNT0, temp

     pop   temp
     out   SREG, temp
     pop   temp
     reti

Tutorials for Other Courses

Additional Links

Site Mirror

This is a mirror to be used when http://myweb.msoe.edu/taylor/, (EDU instead of US) is not available.