Lars
Lars

Reputation: 13

AVR Assembly pure software PWM not giving constant frequency

Can someone spot why this code fail to output a constant pulse? At least my Fluke can't trigger on the high pulse, seems like it comes and goes a bit random..

This is my first asm program, so keep in mind it could be naive bugs in the code

;INITIAL
.include "tn10def.inc"      ; Include file for Attiny10
.org $0000
     rjmp RESET             ; ISR reset vector (also start of prog)
.org $0008
     rjmp WDT               ; Watchdog reset vector 


.def t          = r16       ; temp register
.def PWM_c1     = r24       ; PWM counter register 1
.def PWM_c2     = r25       ; PWM counter register 2
.def PWM_c3     = r17       ; PWM counter register 3

RESET:
;INIT_STACK:
    ldi t, low(RAMEND)      ; init high and low bytes for stack pointer
    out spl, t
    ldi t, high(RAMEND)
    out sph, t
;INIT_SLEEP:
    ldi t, (0<<SM2)|(1<<SM1)|(0<<SM0)|(1<<SE)
    out SMCR, t             ; set power down mode at sleep command
;INIT_ISR
    sei                 ; enable global interrupts
;INIT_POWERSAVER
    ldi t, (1<<ADC1D)|(1<<ADC0D)
    out DIDR0, t            
;INIT_CLOCK
    ldi t, 0xD8             ; write signature
    out CCP, t
    ldi t, (1<<CLKPS3)|(0<<CLKPS2)|(0<<CLKPS1)|(0<<CLKPS0) 
    out CLKPSR, t           ; prescale by 256

MAIN_LOOP:
    rcall PWM_INIT
    rcall POWER_DOWN        ; WDT power down    
    rjmp MAIN_LOOP

PWM_INIT:
    ldi PWM_c3, 255         ; total number of pulses
PWM_START:
    sbi PORTB, led          ; set out high
    ldi PWM_c1, 0
    ldi PWM_c2, 0
PWM_LOOP:
    inc PWM_c1
    cpi PWM_c1, 16          ; target count (PWM high)
    breq PWM_OUT_LOW
    cpi PWM_c1, 208
    brne PWM_LOOP           ; first loop counts to 208
    inc PWM_c2
    cpi PWM_c2, 5
    brne PWM_LOOP           ; second loop counts to 5
    dec PWM_c3
    brne PWM_START          ; counts down number of pulses
    ret
PWM_OUT_LOW:
    cbi PORTB, led          
    rjmp PWM_LOOP   

Upvotes: 1

Views: 720

Answers (1)

Owl_Prophet
Owl_Prophet

Reputation: 388

Well, the running of a processor is not completely constant, even for simple code like this. What you probably want to to is use timers onboard your chip, and change signal on an overflow interrupt. Timers onboard are made to be very consistent.

Upvotes: 1

Related Questions