Friday, May 29, 2015

Timer Time: Using Internal ATTiny13A Chip’s Timer “CTC” Mode

Clear Timer on Compare (CTC) as its name suggests, will clear the flag if counter has same value with compare value. 
Thus, TCNT0 still count fram zero to 255, but if we set OCR0A on 64, timer will clear the flag at 64, restart counter to zero and count up again.
If we set OCR0A to 255, then it’ll behave like normal timer in 'Normal’ Mode.
If OCR0A value’s lower, then the delay time is faster/shorter.
Here's the code. OCF0A is compare flag, the bit-3 on TIFR0 register.
Notice that we have to set TCCR0A register to enable CTC mode; in Normal mode we don’t have to do that.

.include "../"
.def a=r16
.org 0000

    sbi ddrb,0          ; pin b0 output
    ldi a, 0b01000010   ; CTC mode
    out TCCR0A,a
    ldi a,0b00000101    ; prescaler 1024
    out TCCR0B,a
    ldi a,255           ; compare value (emulating normal mode, set to lower value for shorter d)
    out OCR0A,a
    sbi pinb,0          ; flip the B0 bit
    rcall timer
    rjmp main

    in a,TIFR0          ; wait 
    andi a, 0b00000100  ; (1<<OCF0A) is OCF0A 
    breq loop
    ldi a, 0b00000100   ; set OCF0A to 1 again after flagged
    out TIFR0,a