Generating sine wave signal using PIC1xf series is a common project in internet but most of the source code is written in assembly language. Assembly language is good and efficient but it is not portable as C language.
I found a series of tutorials at tahmidmc blog.
The blog explains the sine wave pwm generation from head to toe.
Always start with tutorials for learning.
The key of sine wave is the sine wave duty cycle constants,
tahmidmc has created a useful program to generate sine wave constants.
It is a handy and easy to use but it requires installation which i do not like.
How TO Use the Software
There are two types of sinusoidal pwm, unipolar pwm and bipolar pwm.
For unipolar pwm, only need two pwm to form sinusoidal wave.
For bipolar pwm, need four pwm to form sinusoidal wave but the DC voltage needed only Vpeak, while unipolar pwm need DC voltage which is double of Vpeak.
At smart sine, for unipolar pwm, you need to add offset to get full sine wave.
A simple example, would be as follow:
Use the 32 samples for better viewing, purpose, but the sample entries can be changed to get desired sine wave frequency.
PWM frequency: 20kHz, sine wave frequency = 50Hz.
Sample = (PWM frequency) / (sine wave frequency)
= (20 000) / (50) = 400
Always tune the PWM frequency to get desired sine wave frequency as the sample entries can be changed.
Now for the PWM settings - ECCP1CON (8 bits)
P1M1:P1M0: Enhanced PWM Output Configuration bits
10 = Half-bridge output: P1A, P1B modulated with dead-band control; P1C, P1D assigned as port pins
DC1B1:DC1B0: PWM Duty Cycle Bit 1 and Bit 0
These bits are the two LSbs of the 10-bit PWM duty cycle. The eight MSbs of the duty cycle are found in CCPR1L.
CCP1M3:CCP1M0: Enhanced CCP Mode Select bits
1100 = PWM mode: P1A, P1C active-high; P1B, P1D active-high
1101 = PWM mode: P1A, P1C active-high; P1B, P1D active-low
1110 = PWM mode: P1A, P1C active-low; P1B, P1D active-high
1111 = PWM mode: P1A, P1C active-low; P1B, P1D active-low
For dual mode pin assignment,
To skip the datasheet details, it is good to read block diagram,
Half bridge PWM output
The PIC18f enhanced PWM has dead band control which is good for high side and low side switch control. Power transistor has faster switch on time but slower switch off, if both high and low side is switched at the same time, a very high current (shoot-through current) may flow through both power switches, shorting the bridge supply.
Dead band delay allow switch to fully turned off before switch on another power transistor.
ECCP1DEL: PWM DEAD-BAND DELAY REGISTER
PDC6:PDC0: PWM Delay Count bits
Delay time, in number of FOSC/4 (4 * TOSC) cycles, between the scheduled and actual time for a PWM signal to transition to active.
Another important module associated with PWM is timer2. Just for reference,
Now we have all the details need to write the code: