just learning this - pin 9 set to AO but my voltage reads are not linear. For example, I see 0.2V at 5. To get 1.0V out I need to set the value at 21. It should be 51, no? 255 gives me 5V, but the non-linearity is concerning. Anyone else run into this ??
The output is not an analog voltage. It is a pulse-width-modulated 5V. Perhaps the meter is not averaging the pulses correctly.
pin 9 set to AO
Do you mean that you have connected pin 9 to A0 and are outputting a PWM signal on pin 9 and using analogRead() on pin A0 ?
You can't measure the duty cycle of a PWM signal with a voltage meter. Some meters will give the sort of results you expect, others will get more confused. I have no idea which result you'd get out of the Arduino ADC - my instinct is that you'd get garbage values.
You can get a (somewhat crude) analog voltage out of a PWM pin with an RC filter (search it on forums, something like "arduino rc filter analog" - there are people who've done a much better job explaining it here than I would). This analog voltage would be more amenable to measurement. There are also IC's that will output real analog voltages (digipots and DACs), and some more advanced microcontrollers have a DAC on-board (I think the Due does?). Assuming an analog voltage is what you want...
Most multimeters use dual-slope integrating ADCs with a long sample time, those average very
effectively since they integrate.
analogWrite is directly setting the duty cycle, there's no question about its linearity.
Try it with this circuit (or similar):
Thanks All. My Sparkfun board has PWM printed on pins 0 through 7. I can see now that I don't get a true analog signal without a filter. Thanks again.
Just to clarify and repeat...
"...has PWM printed on pins 0 through 7"
PWM is not analog in and of itself... it's a variable duty-cycle digital pulse train - which the time constant of the RC filter 'smoothes' into a pseudo analog voltage level.
Depending on the frequency and load on the pin, you may need to tweak the component values ot get the smoothest analog waveform.
twoice:
Thanks All. My Sparkfun board has PWM printed on pins 0 through 7. I can see now that I don't get a true analog signal without a filter. Thanks again.
Yeah - it's ok for LEDs, but if what you are driving has any sort of inductance then anything can happen.