View Full Version : Approximated Sine wave with Atmega8

12-02-2010, 10:45 AM
I have a doubt about creating an approx sine wave of 50hz with AVR micro,,, Here is the skeleton code please correct me if im wrong..
In the below code im trying to use a 8 bit PWM output, changing the duty cycle according to the value of sine. The Else statement alone will loop for 20 times till x value becomes 2. Hence dealy of 1 ms eact time will be a total delay of 20ms to complete one cycle of sine wave which will produce o frequency of 50Hz. Since the dudty cycle changes with sine i assume that the power output across a resistor connected between OCR output pin and ground will vary according to 50Hz sine wave.



OCR1A=255*sin(3.142*x); 8 Bit PWM
delay(1); //Delay in milli seconds

} //End of main while

12-03-2010, 09:33 AM
First of all calculation of sine using sine() function take long time and flash space (to link the floating point emulator). So better is to create a table of sine value and store it in flash memory and use avr-gcc pgmspace utility to read the table. I have already done these kind of experiments. You can check out this page for more info.


To generate a sine table you can develop a console app using any programming language (C/C++/VB etc) on PC which writes sine.h file

To generate exact 50Hz wave. You can use TIMER0 to interrupt every 1/(256*50) second. And on each interrupt put the value from the sine table to the ORCx register.

1/(256*50) because I have the full sine wave broken (digitized or quantized) in 256 parts. and 50 because you need 50 such wave in a second. I have enough time I will write a program and give you.

Using the interrupt mechanism will free your CPU. the sine wave generation will take care of itself and you don't have to write any code (expect initialization) in main() to care about the sine wave generator.

Also what is your CPU speed?

12-03-2010, 11:00 AM
Mine is just 8M Speed.. Thank You for your reply..

12-03-2010, 11:02 AM

This might help