//sine wave pwm with centre aligned up down count mode
//sine wave frequency =50 HZ
//triangular wave freq. = 5000 HZ.
#include<xc.h>
#include<p33FJ64MC802.h>
#include<pwm.h>
#define MOTOR_DUTY 60 //motor duty in %
void motor_init()
{
//setup PWM ports
PWM1CON1 = 0; //clear all bits (use defaults)
PWM1CON1bits.PMOD1 = 0; //PWM1L PWM1H are in complementry mode
PWM1CON1bits.PEN1L = 1; //PWM1L1 pin is enabled for PWM output
PWM1CON1bits.PEN1H = 1; //PWM1H1 pin is enabled for PWM output
P1TCON = 0; //clear all bits (use defaults)
P1TCONbits.PTMOD = 0b10; //up down count mode
P1TCONbits.PTCKPS = 0b01; // 1:4 prescaler
P1TPER = 0x5C; // some how managed by mathematical calculation for 1:4 prescalar (decimal value =92) to get 5K HZ PWM
P1TMR = 0; //ENABLE PWM1
IFS3bits.PWM1IF = 0; // disable flag
IEC3bits.PWM1IE = 1; // enable Flag
P1TCONbits.PTEN = 1; //PWM time base is on
}
/////////////// globally defined cnt and sine wave look up table values (20ms/0.2ms)=100 values
int cnt =0;
static int Sine[] = {32768,
34825,
36874,
38908,
40916,
42893,
44830,
46719,
48553,
50325,
52028,
53654,
55198,
56654,
58015,
59277,
60434,
61482,
62416,
63234,
63931,
64506,
64955,
65277,
65470,
65535,
65470,
65277,
64955,
64506,
63931,
63234,
62416,
61482,
60434,
59277,
58015,
56654,
55198,
53654,
52028,
50325,
48553,
46719,
44830,
42893,
40916,
38908,
36874,
34825,
32768,
30710,
28661,
26627,
24619,
22642,
20705,
18816,
16982,
15210,
13507,
11881,
10337,
8881,
7520,
6258,
5101,
4053,
3119,
2301,
1604,
1029,
580,
258,
65,
0,
65,
258,
580,
1029,
1604,
2301,
3119,
4053,
5101,
6258,
7520,
8881,
10337,
11881,
13507,
15210,
16982,
18816,
20705,
22642,
24619,
26627,
28661,
30710};
int main()
{
motor_init();
return 0;
}
//ISR == interrupt service routine
void __attribute__((interrupt, no_auto_psv))_MPWM1Interrupt()
{
IFS3bits.PWM1IF= 0;
IEC3bits.PWM1IE = 0;
for(cnt=0;cnt<100;cnt++)
{
P1DC1 = Sine[cnt];
}
IFS3bits.PWM1IF =0;
//RETFIE;
}