c code to generate a pwm
EIGHT PWM OUTPUTS USING PORT P1 AND TIMER T0
(From Circuit Cellar #140)
Suppose that timer T0 is working in 16-bit mode and requests an interrupt
when it overflows (passes from 0xFFFF to 0x0000). The interrupt service
routine recharges the timer T0 with 0xFE00 so that a new interrupt takes
place after 512 machine cycles. The low part of the TL0 is not recharged
to obtain more precision.
PR_INTE_T0_PWM SEGMENT CODE
DT_PWM SEGMENT DATA
PUBLIC V
PUBLIC COUNTER
RSEG DT_PWM
COUNTER: DS 1 ;unsigned char COUNTER
V: DS 8 ;unsigned char V[8]
CSEG AT 0000BH ;T0 interrupt vector
LJMP INTE_T0
RSEG PR_INTE_T0_PWM
INTE_T0:
PUSH ACC
PUSH PSW
MOV PSW,#08H ;use register bank 1
MOV TH0,#0FEH ;interrupt after 512 cycles
INC COUNTER
MOV R0,#LOW (V) ;R0 point to V[0]
MOV R1,#00H
MOV R2,#08H ;repeat eight times
LABEL_01:
MOV A,@R0 ;ACC = VALUE
CJNE A,COUNTER,LABEL_02 ;CY = 0 if VALUE >= COUNTER
SETB C ;CY = 1 if VALUE = COUNTER
LABEL_02:
CPL C ;CY = 1 while VALUE > COUNTER
MOV A,R1
RRC A ;rotate right through carry bit
MOV R1,A ;move CY to R1.7
INC R0
DJNZ R2,LABEL_01
MOV P1,R1 ;refresh PWM outputs
POP PSW
POP ACC
RETI