spillaccio
Newbie
Offline
Posts: 7
Thank You
-Given: 42
-Receive: 7
|
 |
« Reply #5 on: March 31, 2008, 10:52:19 22:52 » |
|
Hello. Try this sample code and see the math formulas for calculate your frequency.
'**************************************************************** '* Name : HPWM.BAS * '* Author : [select VIEW...EDITOR OPTIONS] * '* Notice : Copyright (c) 2008 [select VIEW...EDITOR OPTIONS] * '* : All Rights Reserved * '* Date : 24/03/2008 * '* Version : 1.0 * '* Notes : * '* : * '**************************************************************** '* TESTED ON PIC16F877A * '**************************************************************** define osc 20 TRISA=%00000000 TRISB=%00000000 TRISC=%00000000 ADCON1=7 '**************************************************************** 'Frequency ( f ) and period ( P ) are inversely proportional. f = 1/P, & P = 1/f. ' 'To calculate the value to be loaded into PR2: '(20MHz / (4 * TMR2 prescale value * 38KHz)) - 1= PR2. ' 'We'll use a prescale value of 1 for timer2. ' '4 * 1 * 250,000 = 1,000,000 '20,000,000 / 1,000,000 = 20 '20 - 1 = 19 ' 'We'll load 19 into PR2, and accept the minimal error. '****************************************************************** '****************************************************************** ' I randomly chose a duty cycle of 50% for this application. To setup the duty cycle, there are two registers that need to be configured. ' ' CCPRL1 contains the eight (most significant bits), and CCP1CON <4:5> (CCP1CON bits 4 and 5) contain the two (least significant bits). 'Since we will only have a maximum of 6-bits resolution, we only need to load the CCPR1 register. CCP1CON bits 4 & 5 will be loaded with 0's. ' 'To figure the value to load into CCPRL1 for 38KHz @ 20MHz with a 50% duty cycle: ' '(PR2 + 1) * TMR2 prescale * 50% Duty Cycle = value for CCPRL1, or '(19 + 1) * 1 * 0.50 = 26 * 0.50 = 5 '****************************************************************** ' IF YOU WANT TURN OFF THE PWM MODE SET CCP1CON = %00000000 '******************************************************************
PR2 = 19 ' Set PWM Period for exactly 250KHz CCPR1L = 5 ' Set PWM Duty-Cycle APPROX. to 50% "IF NECESSARY CHANGE VALUE TO 10" CCP1CON = %00001100 ' Mode select = PWM T2CON = %00000100 ' Timer2 ON + 1:1 prescale ratio TRISC.2 = 0 ' CCP1 to Output
MAIN: 'YOUR PROGRAM" GoTo MAIN
Spillaccio
|