Tim Thompson wrote: > > Does anyone have sample code to setup the PWM on a 20mhz 16F877 to do 3khz 50% > duty-cycle PWM output, for driving a pizeo driver-less element? > I'm new to the PWM area and pic's in general, so any help would be greatly > apreciated. > > - > Tim Thompson Here is some code I posted a while back which may help you understand the PWM module. Assume PIC runs at 20MHz 3000Hz wanted at 50% duty cycle These PWM enable steps are taken from the 16F87X data sheet 1. Set the PWM period (3000Hz = 0.000333S) by writing to the PR2 register. PWM Period = [PR2 + 1]*4*Tosc*TMR2 PreScale value Use 16 for TMR2 prescale. You can try other values but make sure it works with this calculation and the duty cycle calcs as well. (Results must be 0 - 255) Tosc = 1/20000000 = 5*10-8 Rearranging the equation gives... PR2 = (Period/(4 * Tosc * TMR2 Prescale)) - 1 Therefore... PR2 = (0.000333/(4 * 5 * 10-8 * 16)) - 1 = 103 bsf STATUS,RP0 movlw d'103' ; when TMR2 = 103 = end of Period movwf PR2 bcf STATUS,RP0 2. Set the PWM Duty Cycle by writing to the CCPR1L register and CCP1CON<5:4> bits. CCPR1L contains the upper 8 bits of the 10 bit Duty Cycle value CCP1CON<5:4> contain the lower 2 bits PWM Duty Cycle = (CCPR1L:CCP1CON<5:4>)*Tosc*TMR2 Prescale Value CCPR1L:CCP1Con<5:4> = PWM Duty Cycle / (Tosc * TMR2 Prescale) PWM Duty Cycle = 50% of Period PWM Duty Cycle = 50% of 0.000333 = 0.000166 CCPR1L:CCP1Con<5:4> = 0.000166 / (5 * 10-8 * 16) CCPR1L:CCP1Con<5:4> = 207 207 in 10 bit binary = 0011001111 CCPR1L = 00110011 CCP1Con<5:4> = 11 Write the 10 bit value movlw b'00110011' ; set bits 9 - 2 movwf CCPR1L bsf CCP1CON,CCP1X ; set bit 1 = 1 bsf CCP1CON,CCP1Y ; set bit 0 = 1 3. Make the CCP1 pin an output by clearing the TRISC<2> bit bsf STATUS,RP0 movlw b'11111011' andwf TRISC bcf STATUS,RP0 4. Set The TMR2 prescale value and enable TMR2 by writing to T2CON. We decided previously to set the prescale value to 4. TMR2 prescale are bits 1 and 0 in T2CON TMR2 enable is bit 2 movlw b'00000111' ; TMR2 = on, prescale = 1:16 movwf T2CON 5. Configure the CCP1 module for PWM movf CCP1CON,W andlw b'00110000' ; mask all but previously set Duty Cycle bits iorlw b'00001111' ; and enable PWM mode movwf CCP1CON A 3000 Hz square wave with a 50% duty cycle should now be coming out of RC2. -- Best regards Tony mICros http://www.bubblesoftonline.com mailto:sales@picnpoke.com -- http://www.piclist.com#nomail Going offline? Don't AutoReply us! email listserv@mitvma.mit.edu with SET PICList DIGEST in the body