1

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 !!!

4
  • Maybe a bit of a delay? You will be changing the duty cycle very rapidly.
    – Nick Gammon
    Aug 30, 2017 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.
    – Ultra67
    Aug 30, 2017 at 8:56
  • 2
    then your low pass filter isn't enough Aug 30, 2017 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.
    – lemontwist
    Aug 30, 2017 at 16:02

2 Answers 2

1

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

3
  • So it's not possible to do a sine wave?
    – Ultra67
    Aug 30, 2017 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, 2017 at 10:07
  • 1
    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, 2017 at 10:18
0

Can anyone tell me where I made a mistake ?

put a lpf on the pwm output.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.