« servo lab | Main | range finder + night rider »

LED as light sensors

Been messing around with the code found on this site. The reading I get from val seems to fluctuate a lot, and it's really difficult to find the resistance needed to stabilize it. The best resistance for the lighting on my desk seems about 2k ohms (two 1k in series). The mitsubishi reading is quite interesting.

led-sensor.JPG
red LED is sensor, green is output

Here's the code if you want to read it. It's just exact same code as on the french site, plus my commentary on what I think is happening...

int pinA = 2; // + of sensing LED
int pinB = 3; // - of sensing LED
int outPin = 4; // output indicator
int val = 0;

void setup() {

// not sure what this does, setting some bits/bytes? but dunno why
// WON'T WORK WITHOUT THIS
_SFR_IO8(0x30) |= 4;

// set initial mode
pinMode(pinA, OUTPUT);
pinMode(pinB, OUTPUT);
pinMode(outPin, OUTPUT);

// set initial value
digitalWrite(pinA, HIGH);
digitalWrite(pinB, LOW);

Serial.begin(9600); // connect to the serial port
}

void loop() {

// reset value
val = 0;

// charge up the diode
digitalWrite(pinA, HIGH);
digitalWrite(pinB, LOW);
delay (80);

// reverse
digitalWrite(pinA, LOW);
digitalWrite(pinB, HIGH);

// drain the pin
pinMode(pinB, INPUT);
while (digitalRead (pinB) != 0)
val++;

// reset pin B mode
pinMode(pinB, OUTPUT);

// determine if we want to light the indicator LED or not
if ( val > 1900 ) // 1900 is some random value i picked - different lighting+resistor combo requires different value
digitalWrite(outPin,LOW); // has light
else
digitalWrite(outPin,HIGH); // no light

// debug code
Serial.println(val);

}