ME Labs, Inc.
719-520-5323
 
Home:
  Developer Resources:

Programming Clues
    Sample Programs
   
    PICBASIC PRO™
Compiler Manual
    PICBASIC™ Compiler
Manual
    Serin2/Serout2 Modes
    ASCII Character Set
    Number Conversion
    Floating Point
Routines
    PBP Debug Monitor
    Articles and Tutorials

Hardware Clues
    Parts / Vendor List
    PICPROTO™ Boards
    LAB-X1 Docs
    LAB-X2 Docs
    LAB-X20 Docs
    LAB-X3 Docs
    LAB-X4 Docs
    LAB-XUSB Docs
    LAB-XT Docs
     
 

ME Labs, Inc. | 1-719-520-5323 | Example Program - 767PWM.pbp

PICBASIC PRO program to demonstrate the steps necessary to use hardware PWM channel 3 on the 16F767 (and similar devices).
01' Name        : 767PWM.pbp
02' Compiler    : PICBASIC PRO Compiler 2.6
03' Assembler   : PM or MPASM
04' Target PIC  : PIC16F767 or similar types
05' Hardware    :
06' Oscillator  : 4MHz crystal
07' Keywords    : HARDWARE PWM
08' Description : PICBASIC PRO program to demonstrate the steps necessary
09' to use hardware PWM channel 3 on the 16F767 (and similar devices).
10'
11 
12' Output is a 1Khz signal with duty cycle sweeping
13' from 20% to 80% once per second.
14 
15' PR2 = Timer2 period register, controls PWM period.
16' CCPR3L and CCP3CON<5:4>bits control the duty cycle,
17' and should be treated as a 10-bit word.
18 
19' Fosc = Clock Frequency (4MHz)
20' PS = Timer2 Prescale Value (T2CON<1:0>)
21' Freq = PWM output frequency
22' Duty% = Duty cycle (20% = 0.2)
23 
24' formulas:
25' PR2=(Fosc/(4*PS*Freq))-1
26' CCPR3L:CCP3CON<5:4>=(PR2+1)*4*Duty%
27 
28duty VAR WORD  ' Duty cycle value (CCPR3L:CCP3CON<5:4>)
29 
30   TRISB.5 = 0            ' Set PORTB.5 (CCP3) to output
31   CCP3CON = %00001100    ' Set CCP3 to PWM
32   T2CON = %00010101      ' Turn on Timer2, Prescale=4
33 
34' Use formula to determine PR2 value for a 1KHz signal,
35' 4MHz clock, and prescale=4. (4E6/(4*4*1E3))-1=249
36 
37   PR2 = 249              ' Set PR2 to get 1KHz out
38         
39' Use formula to determine CCPR3L:CCP3CON<5:4> value for
40' ends of range 20% to 80%.  (249+1)*4*0.2=200 (20% value)
41' (249+1)*4*0.8=800 (80% value)
42 
43   duty = 200             ' Set duty cycle to 20%
44 
45mainloop:      
46   CCP3CON.4 = duty.0     ' Store duty to registers as
47   CCP3CON.5 = duty.1     ' a 10-bit word
48   CCPR3L = DUTY >> 2
49   duty = duty + 10       ' Increase duty cycle
50 
51' Since the total sweep of duty is 600 (800-200) and
52' we are adding 10 for each loop, that results in 60
53' steps min to max. 1 second divided by 60 = 16.67mS           
54 
55   Pause 17                        ' Pause 1/60 of second
56   IF (duty < 800) Then mainloop   ' Do it again unless 80% duty cycle
57   duty = 200                      ' Reset to 20% duty cycle
58   GoTo mainloop                   ' Do it forever
59 
60   End
61                

Download the program file.