Microcontrollers cannot produce varrying voltages. They produce a high (5V) and a low (0V).
But you can "fake" analog output by using pulsewidth modulation. Just like animation creates the illusion of movement, pulsewidth modulation, manipulates the
intervals bewtween on (the pulsewidth) and off in such a way that it fools the eye and appears to be between on and off.
Where can I find some PWM?
- Dimmers
- Speed control
- Noise making
The circuit above works for any variable resistor.
It's a voltage divider.
In the image above, there are two voltage dividers,
one on analog in 0 and one on analog in 1.
The fixed resistor in each circuit should have the same order
of magnitude as the variable resistor's range.
For example, if you're using a flex sensor with a range of 50 - 100 kilohms,
you might use a 47Kohm or a 100Kohm fixed resistor.
If you're using a force sensing resistor that goes from inifinity ohms to 10 ohms,
but most of its range is between 10Kohms and 10 ohms, you might use a 10Kohm fixed resistor.
Exercise I—Analog In and Out
The easiest way to see PWM in action is to attach an LED to one of the PWM pins. You may be able to see the flashing rather than
a dimming effect. After you have wired and programmed, you will add a
low-pass filter circuit.
Using a Potentiometer to dim a LED
Create a circuit and program it so that you can turn on two LEDs, one based
digitally (on or off) and one based on the analog values of the potentiometer.
To turn on the analog LED on and off use this syntax:
analogWrite(ledPin, analogValue/4);
Put the analog led on pin 9. This is the PWM pin.
Low Pass Filter Circuit
These circuits use a combination of a capacitor and a resistor to average out the pulses so the time when the LED
is off between pulses is not so pronounced. The capacitor stores up a charge during a pulse and releases in between pulses.
The circuit doesn't smooth all the pulses. It allows pulses below a certain threshold to pass
through without smoothing them, and smoothes out those above the threshold frequency into an even pseudo-analog voltage.
The range of frequencies filtered out is determined by the ratio of the resistor's value to that of
the capacitor.