Author Topic: AVR: Clock Speed Calculation  (Read 637 times)

0 Members and 1 Guest are viewing this topic.

Offline lumdefTopic starter

  • Newbie
  • Posts: 2
  • Country: lu
AVR: Clock Speed Calculation
« on: October 24, 2023, 09:40:04 am »
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:

Code: [Select]
.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?
 

Offline lumdefTopic starter

  • Newbie
  • Posts: 2
  • Country: lu
Re: AVR: Clock Speed Calculation
« Reply #1 on: October 24, 2023, 01:14:18 pm »
Alright, seems like my understanding of frequency was wrong. If one wants to toggle an LED once per second, then the period of the waveform must be 2 seconds, not 1.
 

Offline MikeK

  • Super Contributor
  • ***
  • Posts: 1314
  • Country: us
Re: AVR: Clock Speed Calculation
« Reply #2 on: October 24, 2023, 03:18:42 pm »
Depends what you mean by "toggle".  If "toggle once per second" means that the LED changes state every second then, yes, the period is 2 seconds  The LED is off for 1 second and on for one second.  The waveform takes a total of 2 seconds.
 


Share me

Digg  Facebook  SlashDot  Delicious  Technorati  Twitter  Google  Yahoo
Smf