The sketch that you used in lesson 8, will work, but you will find that you will not be able to find a light bright enough to light all the LEDs. This is because of the fixed resistor, so we need to compensate for the fact that no matter how low the resistance of the photocell falls, there will always be the 1 kΩ of the fixed resistor offsetting it.

The slightly modified lesson 8 sketch is listed below:

/*
Adafruit Arduino - Lesson 9. Light sensing
*/

int lightPin = 0;
int latchPin = 5;
int clockPin = 6;
int dataPin = 4;

int leds = 0;

void setup() 
{
  pinMode(latchPin, OUTPUT);
  pinMode(dataPin, OUTPUT);  
  pinMode(clockPin, OUTPUT);
}

void loop() 
{
  int reading  = analogRead(lightPin);
  int numLEDSLit = reading / 57;  //1023 / 9 / 2
  if (numLEDSLit > 8) numLEDSLit = 8;
  leds = 0;   // no LEDs lit to start
  for (int i = 0; i < numLEDSLit; i++)
  {
    leds = leds + (1 << i);  // sets the i'th bit
  }
  updateShiftRegister();
}

void updateShiftRegister()
{
   digitalWrite(latchPin, LOW);
   shiftOut(dataPin, clockPin, LSBFIRST, leds);
   digitalWrite(latchPin, HIGH);
}

The first thing to note is that we have changed the name of the analog pin to be 'lightPin' rather than 'potPin' since we no longer have a pot connected.

The only other substantial change to the sketch is the line that calculate how many of the LEDs to light:

int numLEDSLit = reading / 57;  // all LEDs lit at 1k

This time we divide the raw reading by 57 rather than 114 from lesson 8. In other words we divide it by half as much as we did with the pot, to split it into nine zones, from no LEDs lit, to all eight lit. This extra factor is to account for the fixed 1 kΩ resistor. This means that when the photocell has a resistance of 1 kΩ (the same as the fixed resistor) the raw reading will be 1023 / 2 = 511. This will equate to all the LEDs being lit and then a bit (numLEDSLit will be 9).

This guide was first published on Dec 11, 2012. It was last updated on Dec 11, 2012.

This page (Arduino Code) was last updated on Oct 16, 2012.

Text editor powered by tinymce.