Note 1: code written for Mikroelektronika MikroBasic PRO for PIC Note 2: any other PIC with hardware PWM module can be setup as listed below.H-bridge hardware setup (see page 137 of the 16F690 datasheet)
How to calculate PWM frequency? (see page 131 of the 16F690 datasheet)
The formula is
PWM period = (PR2+1)*4*TMR2prescale value / Fosc
Where:
PR2 = 0 to 255 (0x00 to 0XFF)
TMR2prescale value = 1, 4 or 16
Fosc = PIC frequency in Hz (not MHz!).
Example:
PR2 = 0xFF (=255)
TMR2prescale value = 16
Fosc = 20,000,000Hz.
Result:
Fpwm = 1,220.703Hz
Want 20kHz? Change PR2 = 15 and the resulted Fpwm = 19,531.250Hz
Setup the PWM in the PIC for Full-bridge (4 pins already designated will be allocated to the H-bridge driving)Initialise PWMCCP1CON = 0X4E ' CCP ON mode, set in Forward (chosen as default)
' P-N channel H-bridge: P1A/C active "L", modulated P1B/D active "H"
CCPR1L = 0 ' Set DC = 0%
T2CON = 0x05 ' TMR2 ON, 1:4 prescaler
PR2 = 0xFA ' f=498.008Hz (!!!Using a 2MHz Fosc!!!)
TMR2 = 0 ' clear TMR2
Explanation CCP1CON (under the bit number is the choice):
bit------7-----6-----5-----4-----3-----2-----1-----0
Values:
--------0-----1 Forward Mode OR
--------1-----1 Reverse Mode
---------------------x-----x LSb of CCPR1L (linked to the Duty Cycle = DC)
----------------------------------1-----1-----0-----0 Setup for N channel H-bridge
----------------------------------1-----1-----1-----0 Setup for P-N channel H-bridge
Setup for direction and DC update:
REVERSECCPR1L = "value" ' Set DC = calculated value
SetBit(CCP1CON,7) ' Put the H-bridge in Reverse mode
FORWARDCCPR1L = "value" ' Set DC = calculated value
ClearBit(CCP1CON,7) ' Put the H-bridge in Forward mode
STOPCCPR1L = 0x00 ' Set DC = 0%
ClearBit(CCP1CON,7) ' Put the H-bridge in Forward mode
' you can omit this, as it makes no difference where the H-bridge is at 0%
NB: this post is made because I considered this subject may be useful for others (including me, I may not master completely the PWM
). Hope you'll appreciate and
provide comments as needed, or ask questions if any.NB2: yes, for those that will say they've seen this post someplace else, it is the same me that made that post.