Now that you know how to do get digital input, let’s try some analog input with a photocell.
5V ——> photocell ——> 10K resistor ——> GND
A photocell is a variable resistor, which means that the more light that shines on it, the less resistance it has. So, more light = less electricity gets to the 10K resistor/GND side of things.
Right now the setup doesn’t help you very much, you need to measure things! You’ll want to eavesdrop between the photocell and the 10K resistor - plug a wire from their row into pin ‘A0’.
Run the code, take a look at the Serial Monitor (Tools > Serial Monitor
, or use the magnifying glass icon). What values come up as you move the photocell in and out of the light?
You can see that the values are fluctuating somewhere between 0 and 1024 (it’ll probably be a much narrower range). This is an analog input, an input that is more nuanced than just HIGH
and LOW
. In order to get analog readings, you need to connect them to one of the analog ports - A0
through A5
. Most sensors you use will be analog inputs.
Now that we can read the results of an analog input, let’s try out an analog output.
Now add another circuit for an LED, coming out of pin 9.
pin 9 ——> 470 ohm resistor ——> LED ——> GND
Up top:
In setup:
Now run it.
Now change analogWrite(ledPin, 1);
to analogWrite(ledPin, 10);
, and then analogWrite(ledPin, 100);
. What happens?
Read more about analogWrite.
The maximum output value for analogWrite
is 255
, while the maximum input for analogRead
is 1024. How can you connect the photocell and your LED for maximum effect?