# Sine wave PWM Arduino Micro

I'm trying to generate a sine wave on my Arduino micro. I used this code.

``````int Pin = 9;

void setup()
{
Serial.begin(9600);
pinMode(Pin, INPUT);
}

void loop()
{
float something = millis()/10000.0;
int value = 128.0 + 128 * sin( something * 2.0 * PI  );
analogWrite(Pin,value);
}
``````

I have a low pass filter at the output of the pin to smooth the wave. The problem is : I get a nice square wave with a duty cycle from 0 to 100%, but not a sine wave. Ideally, I'd like to set a frequency of 10 Hz. Can anyone tell me where I made a mistake ? Thanks a lot !!!

• Maybe a bit of a delay? You will be changing the duty cycle very rapidly. Aug 30 '17 at 8:47
• I tried it, the duty cycle of the square wave is changing according to the delay, but it's still not a sine wave. Aug 30 '17 at 8:56
• then your low pass filter isn't enough Aug 30 '17 at 11:08
• You can make a simple R-2R ladder DAC to create a sin wave. However it does require the use of many I/O pins, depending on the resolution you want in your sin wave. Aug 30 '17 at 16:02

it is how PWM works. digital pins can do only 1 and 0.

• So it's not possible to do a sine wave? Aug 30 '17 at 9:43
• Maybe use the PWM to charge a capacitor? You can balance charge and discharge with resistors to possibly get a pretty sinusoidal voltage on it. Aug 30 '17 at 10:07
• I found you a tutorial that should help you to create a circuit that changes a square wave to sinusoidal wave. All you need to do is to output from your arduino 0 for 50ms and 1 for 50ms (to get 10Hz) and adjust the capacitor sizes to get a sin wave. (Tutorial shows circuit working for 10kHz square wave) learningaboutelectronics.com/Articles/… Aug 30 '17 at 10:18

Can anyone tell me where I made a mistake ?

put a lpf on the pwm output.