How to: LED as a Light Sensor

LEDs LEDs LEDs, is there anything they can’t do?  Besides adding that special crunchiness to smooth peanut butter, they also make awesome light level sensors.  Here’s one way to do it that doesn’t require an analog input, just connect the LED across two digital pins like this:

We’re going to treat the LED as a small light dependent capacitor, we charge it up and then time how long it takes to discharge, super simple! Here’s the pseudo code we will implement:

  1. Light up LED (Positive to Anode & Negative to Cathode)
  2. Charge Capacitance (Negative to Anode & Positive to Cathode)
  3. Switch Cathode to Input and Disable Internal Pullup Resistor
  4. Capture the Start Time
  5. Wait until Cathode Input Becomes Low
  6. Capture the Stop Time and Compute the Difference

Putting this into action on the Arduino platform and experimenting with light levels revealed that it takes about 6 ms in bright light for the LEDs capacitance to discharge.  And up to 5 seconds in complete darkness.  If that’s too slow for your application, you can use an analogue pin to measure the voltage drop for a short interval of time and integrate the result.  Here’s the bit of Arduino code used for detecting the light level and pushing it out over serial:

//Set LED Connections to Outputs
pinMode(5, OUTPUT);   // LED A
pinMode(6, OUTPUT);   // LED B

//Light up LED
digitalWrite(5, LOW) ;
digitalWrite(6, HIGH) ;
delay (100);

// Charge up Capacitance of LED
digitalWrite(6, LOW) ;
digitalWrite(5, HIGH) ;
delay (10);

// Switch Cathode to Input
pinMode(5, INPUT);
// And Disable Pullup
digitalWrite(5, LOW); 

// Capture Start Time
Start = millis();

// Wait Around Until it Discharges
while ( digitalRead (5) == 1) { } 

// Capture Stop Time
Stop = millis();

// Push the Difference up Serial
Serial.print ( Stop - Start );

Utilizing the alternative analogue method, reading the falling voltage and plotting gives the following capacitive discharge chart:

One Response to “How to: LED as a Light Sensor

Leave a Reply

Your email address will not be published. Required fields are marked *