Arduino’s eye, or about a photoresistor, not Tolkien’s mythology

Arduino’s eye – sounds like a quote from J.R.R. Tolkien, while it’s about connecting photoresistor to Arduino. With this article I would to begin short course dealing with basics of electronics.

Photoresistor is a element whose resistance is dependent of amount of light falling on it. What only remains is to measure this resistance. In which way?

For a playful use we will ignore accuracy, assuming simplified model.

How it looks?

Simple circuit built on breadboard
Simple circuit built on breadboard (click on the picture to see notes on Flickr)

Circuit diagram looks like the following:

Circuit diagram
Circuit diagram

What is depicted here is so called voltage divider. You can read on Wikipedia, how it works.

Briefly speaking, voltage on the junction point between two resistors will be varying according to resistance of the photoresistor. And this is what we will be measuring with our program.

This is its code:

// pin, from which we read the voltage
int photoPin = 0;
//the reading
int val = 0;

//initial configuration
void setup()
  pinMode(photoPin, INPUT); // setting the pin as input

void loop()
  //reading and standarizing to range 0-7
  val = analogRead(photoPin)/128;
  for (int i=0;i<=val;i++) {

Program (as hardly every on Arduino) consists of the section preparing the device to work (setup) and main loop (loop) evoked as long as the power is available…

In main loop the voltage is measured, then the reading is converted in range 0-7 (because Arduino reads voltage as a number from 0 to 1023, so dividing it by 128 and rounding down gives digit from 0 to 7) and appropiate number of diodes is lighted up. Short break, and loop again…

The result:

Arduino IDE during execution of our program
Arduino IDE during execution of our program

While the program is running, I’m covering the photoresistor with my hand, changing its resistance, and thus the voltage being read by Arduino from pin 0. The number of dots is proportional to the reading.

Part list:

Coming soon – how to physically show varying reading.