Using an LED as a Light Sensor on Arduino

April 4, 2012

Thanks to the magic of electrical properties you can use an LED as a light sensor. It is easy to search and find the details of how and why, so I’m just going to include some code here.

Ok, ok… If you plug the LED into one of the Arduino digital pins backwards (i.e. Cathode to the digital pin, Anode to ground) you can then charge it using the LED’s capacitive abilities, and then measure the amount of time that it takes to discharge. The discharge time is inversely related to the amount of light the LED is receiving.


class AmbientLightSensor {
  public:
    AmbientLightSensor(int ledPin) : mLedPin(ledPin) {}
    int measure();
  protected:
    int mLedPin;
    void charge();
    void discharge();
    int measureUsingDigitalPin();
};
void AmbientLightSensor::charge() {
  // Apply reverse voltage, charge up the pin and led capacitance
  pinMode(mLedPin, OUTPUT);
  digitalWrite(mLedPin, HIGH);
}
void AmbientLightSensor::discharge() {
  pinMode(mLedPin, INPUT);
  digitalWrite(mLedPin, LOW); 
}
int AmbientLightSensor::measure() {
  charge();
  delay(1); // charge it up
  discharge();
  return measureUsingDigitalPin();
}
int AmbientLightSensor::measureUsingDigitalPin() {
  long startTime = millis();
  // Time how long it takes the diode to bleed back down to a logic zero
  while ((millis() - startTime) < 100) { // max time we allow is 2000 ms
    if ( digitalRead(mLedPin)==0) break;
  }
  return millis() - startTime;
}
int led1 = 6; 
int led2 = 13; // led to indicate darkness is hooked up to digital pin 13
AmbientLightSensor led(led1); // LED is hooked up to digital pin 6

void setup()
{
  pinMode(led2,OUTPUT);
  pinMode(led1-1,INPUT);
  digitalWrite(led1-1,HIGH);
  pinMode(led1+1,INPUT);
  digitalWrite(led1+1,HIGH);
Serial.begin(9600);
}
 
void loop()
{
  int ledVal; ledVal = led.measure();
  if (ledVal > 2){ // ledVal will be 0 or 1 most likely while the laser is shinning on it
    if (ledVal < 100){  // This actually is probably not needed.
      Serial.println(ledVal, DEC);
      digitalWrite(led2, HIGH);
    }
  } else {
    digitalWrite(led2, LOW);
  }
}

Tags: , , , ,

Newark Designs

Hi, I'm arbitrary text. Who are you?

My Twits

  • Kroger brand Sausage Patties have MSG in them. I am literally angry with rage. - 15 hours ago
  • Guess I'm not drinking this any time soon. fb.me/1759zKwVL - 1 day ago
  • Someone just posted on my G+ feed: "Here's a math question for all you parents out there. My 8-yr old son is... fb.me/23UD0igs1 - 1 day ago
  • I signed up for Google Music's All Access service. In the last hour I've found four albums that I've been wanting... fb.me/Af0QcLX0 - 1 day ago
  • I need to hurry up and see Star Trek before everyone on here RUINS it for me haha. I'm doing pretty good so far,... fb.me/A13MtTW1 - 1 day ago

User Login