I am programming AVR ATTiny2313, and I want to toggle an LED once per second. I do that using the 8-bit timer, here is the code:
.NOLIST
.INCLUDE "tn2313def.inc"
.LIST
;
; ------ Register ---------------------
.def rmp = R16 ; multi purpose register
; ------ Program start ----------------
.cseg
.org 000000
Start:
; Stack init
ldi rmp,LOW(RAMEND)
out spl,rmp
; Reduce clock frequency
ldi rmp,1<<CLKPCE
out CLKPR,rmp ; Allow clock frequency modifications
ldi rmp,(1<<CLKPS2) | (1<<CLKPS0)
out CLKPR,rmp ; Prescaler /= 32
; PB0 as output
sbi DDRB,DDB2
; Start timer, toggle PB0 on compare match, CTC at 120
ldi rmp,120
out OCR0A,rmp ; Set CTC compare match value
ldi rmp,(1<<COM0A0) | (1<<WGM01)
out TCCR0A,rmp ; Toggle OC0A, CTC mode
ldi rmp,(1<<CS02) | (1<<CS00)
out TCCR0B,rmp ; Timer prescaler /= 1024
; Sleep mode
ldi rmp,1<<SE ; Sleep mode idle
out MCUCR,rmp ; to universal control port
Wakeup:
sleep ; send controller to sleep
nop
rjmp Wakeup ; send controller to sleep again
The problem is this code toggles the LED state at pin PB0 once per ~500ms (while I want 1/sec). Now please tell me where my calculations are wrong...
Page 95 of ATTiny2313 datasheet gives the following formula for waveform frequency of OC0A: (chip_clock_speed)/(2*timer_prescaler(1+OCR0A)).
In my case chip_clock_speed=250000, timer_prescaler=1024, OCR0A=120, which yields 1 if you put these values into the formula. Why is PB0 not being toggled once pre second?