Creating my own PWM

Hello All

Well I new here...

Just got my arduino (uno-redboard) and I want to create my own PWM.

I connect a low pass filter to output pin8 resistor=10KOhm and capacitor 4.7uF.

I used the following code:
//This is PWM test
void setup() {
// set the digital pin as output:
pinMode(2, OUTPUT);
Serial.begin(9600);

}

void loop()
{

digitalWrite(2, HIGH);
delayMicroseconds(500);
// delay(50);
digitalWrite(2, LOW);
// delay(50);
delayMicroseconds(500);
float VoltageIn = analogRead(A0) * (5.0 / 1023.0);
Serial.println(VoltageIn , DEC);
}

and for some reason I measure 0.2V (verfied with a volt meter) can someone please help?

Thanks!

That code outputs a signal on pin 2...

Yes, I have also tried that on pin2

thanks

"Serial.println(VoltageIn , DEC);" takes a long time to execute.

How will that affect the PWM?

You were expecting what?

You have a high output for 500uS, then a low for 500uS, then low for ~110uS while the analogRead of the low output happens, then low some more while the float math happens, then low some more while Serial.print runs, and finally low some more while loop completes and jumps back for the digitalWrite to finally go high again.

analogRead returns a reading of the decaying capacitor multiplied by 4.88mV, so you might get something other than 0.

Plug in your RC values here here and get some idea of the responsiveness of the output:
http://sim.okawa-denshi.jp/en/CRtool.php

Thanks!!

I removed the serial read, and used a voltmeter to meassure the ouput, I got close results, Which I guess are dur to Voltage lost in the capacitor.

gilmaor:
Thanks!!

I removed the serial read, and used a voltmeter to meassure the ouput, I got close results, Which I guess are dur to Voltage lost in the capacitor.

The analogRead() also takes time. You should compensate for it.

Lose the Serial print and it'll be more reasonable, but basically this isn't
a great way to generate PWM as you are using delay / delayMicroseconds.

You can improve matters by going over to the blinkWithoutDelay style of
coding (using micros() rather than millis()), but things like Serial will
cause issues as they wait...

This is why hardware PWM is provided in the first place, since the software
solutions are awkward and tricky.

Using timer interrupts allows the best software solution, and you might want
to see how the Servo library uses this approach.