Arduino Basics: Lil’ Lightie

Now that you know how to do get digital input, let’s try some analog input with a photocell.

Your code

// You'll install the switch on pin 2:
int switchPin = 2;

void setup() {
  // initialize serial communication at 9600 bits per second:
  Serial.begin(9600);
  pinMode(switchPin, INPUT_PULLUP);
}

void loop() {
  int switchValue = digitalRead(switchPin);
  Serial.println(switchValue);
}

Setup

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’.

The Code

// We're using the analog input
int photoPin = A0;

void setup() {
  Serial.begin(9600);
}

void loop() {
  int photoValue = analogRead(photoPin);
  Serial.println(photoValue);
}

Analog inputs

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.

Analog outputs

Now that we can read the results of an analog input, let’s try out an analog output.

Circuit changes

Now add another circuit for an LED, coming out of pin 9.

pin 9 ——> 470 ohm resistor ——> LED ——> GND

Code changes

Up top:

int ledPin = 9;

In setup:

pinMode(ledPin, OUTPUT);
analogWrite(ledPin, 1);

Result

Now run it.

Now change analogWrite(ledPin, 1); to analogWrite(ledPin, 10);, and then analogWrite(ledPin, 100);. What happens?

Read more about analogWrite.

Connecting the two

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?

Want to hear when I release new things?
My infrequent and sporadic newsletter can help with that.