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);
}
}

