Menu

Getting wrong frequency with Timer1 (on ATTiny2313)

Help
alex_t
2017-07-22
2017-07-22
  • alex_t

    alex_t - 2017-07-22

    Hello,

    I have just started another project and I need a bit of help. This time I need to generate square waves at a few frequencies (1 Hz and 100 Hz to name a few). A button will be used to change between the frequencies. The hardware is very simple, just an ATTiny2313 MCU with an 8 MHz external crystal (with 2 x 22pF caps on its legs) and a led connected via a 1K resistor to pin 9 of the chip. Software wise, I thought of using 16-bit Timer1 and generate the pulses via software.

    First, I tried to toggle a LED at 1 Hz by modifying an example from the manual (code below). The problem is that the LED seems to stay on for 2 seconds and off for 2 seconds so the frequency is about 0.5 Hz instead of 1 Hz. Any idea what I'm doing wrong?

    #option explicit
    #chip tiny2313, 8
    #config OSC = EXT
    
    #define LED PORTD.5
    Dir LED OUT
    
    Inittimer1 OSC, PS_256
    Starttimer 1
    Settimer 1, 34286  ;preload timer with 65536 - ( 8MHz / 256 / 1 Hz)
    
    On Interrupt Timer1Overflow Call Flash_LED
    
    Do
        'Wait for interrupt
    loop
    
    Sub Flash_LED
       Settimer 1, 34286   'Preload timer
       LED = !LED
    End Sub
    

    Thanks!

     
  • kent_twt4

    kent_twt4 - 2017-07-22

    Simply put, the frequency is equal to 1/2 the period of the waveform. To put it another way, with a 50% duty cycle you would expect the timer to be high 1/2 the time and low the other half. So assuming the above equation is correct then it should be 8Mhz / (2* 256 * 1).

    Check out the data sheet if you want to automate that procedure using the Clear Timer on Compare (CTC) mode. It will give a 50% duty cycle without using interrupts. Six to one, half a dozen to the other, both will work fine.

     
  • alex_t

    alex_t - 2017-07-22

    Thanks for the input, it got me going in the right direction. I really need to be a bit more thorough when learning. Cheers!

     

Log in to post a comment.

Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.