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.Nick Gammon– Nick Gammon ♦2017年08月30日 08:47:17 +00:00Commented 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– Ultra672017年08月30日 08:56:11 +00:00Commented Aug 30, 2017 at 8:56
-
2then your low pass filter isn't enoughratchet freak– ratchet freak2017年08月30日 11:08:57 +00:00Commented 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– lemontwist2017年08月30日 16:02:11 +00:00Commented Aug 30, 2017 at 16:02
2 Answers 2
it is how PWM works. digital pins can do only 1 and 0.
-
So it's not possible to do a sine wave?Ultra67– Ultra672017年08月30日 09:43:00 +00:00Commented 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.Filip Franik– Filip Franik2017年08月30日 10:07:09 +00:00Commented Aug 30, 2017 at 10:07
-
1I 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/…Filip Franik– Filip Franik2017年08月30日 10:18:05 +00:00Commented Aug 30, 2017 at 10:18
Can anyone tell me where I made a mistake ?
put a lpf on the pwm output.