# Sinusoidal PWM code for PIC18F452?

#### Ahmed Waleed

Joined Mar 4, 2008
22
Dear All,
Where can I find a code for sinusoidal PWM for PIC18F452 with frequency 60 Hz?
and it must be all digital, no analog signals used (I mean i don't want to use ADC to compare sin wave with triangle wave) I want it fully digital, is it possible to find such a code?!

if someone has done it, maybe it helps me so much.

#### mik3

Joined Feb 4, 2008
4,846
Use the sin(x) function of a PIC and plug values of (x) with as much resolution you want to get sinusoidal digital values.

#### russ_hensel

Joined Jan 11, 2009
825
Or for a more pure pwm approach google <magic sine wave>

#### Ahmed Waleed

Joined Mar 4, 2008
22
Or for a more pure pwm approach google <magic sine wave>
this is a very good calculation method, thnx

#### Ahmed Waleed

Joined Mar 4, 2008
22
Use the sin(x) function of a PIC and plug values of (x) with as much resolution you want to get sinusoidal digital values.
you mean I use an array using C and put the values of the sin function in it, or there is a possibility to make a function sin(x) and vary the variable X on whole the period (2∏).

#### mik3

Joined Feb 4, 2008
4,846
There a function sin(x) which calculates the sine value of any angle in radians.

#### jpanhalt

Joined Jan 18, 2008
7,699
There a function sin(x) which calculates the sine value of any angle in radians.
How do you get a variable duty cycle from that?

John

#### thatoneguy

Joined Feb 19, 2009
6,349
How do you get a variable duty cycle from that?

John
I believe he was along these lines:

Multiply sin(x) with 1/2 max resolution of PWM, add result to 1/2 max resolution. Use result for duty cycle.

sin(180)=-1 - 0% duty cycle, sin (0) = 0 = 50% duty cycle, sin(90) =1 = 100% duty cycle. Change 0-360 degrees to 0-6.28 for radians.

Put result through lowpass filter, followed by decoupling cap to center on zero.