# Light Intensity Code

I think I've finally sorted and perfected a code for reading a simple LDR and calculating a lux value.

Here's the basic circuit: (sorry about the simpleness)

5v----10k--v--LDR----GND
(A5)___

All self explanatory, the v and (A5) below it is the connection between 10k and LDR to analogue pin 5 on the arduino.

The code is tuned to the circuit you're using, to be as precise as possible, so where it says 10.72 that is the 10k resistor in kOhms that I checked using a mulitmeter. Likewise I double checked the 5v, which was exactly 5v on my voltmeter. The very small long number (0.00488...) is 5/1023, again use the true voltage to get accurate results.

int LDR = 5; // select the input pin for the LDR

void setup() {
Serial.begin(9600);
pinMode(LDR, INPUT); // declare the LDR as an INPUT
}

void loop()
{
float volts0=photocellReading0*0.004887585532746823069403714565; // calculate the voltage
Serial.print(volts0); //raw voltage
Serial.println(" Volts.");
Serial.print((500/((10.72/(5-volts0))*volts0)), 2); //lux calculation
Serial.print(" Lux.");
Serial.println("");
delay(1000); //delay for a second
}

I have a very cheap lux meter and I've worked out the percentage difference between my arduino light meter and it as an average of 5.56% over 7 different lights (from dark to sunlight) so I pretty certain that, that's as close as I'm going to get to a true lux reading using a tiny LDR and my arduino.

Hope that helps someone
Ollie

``````float volts0=photocellReading0*0.004887585532746823069403714565;   // calculate the voltage
``````

That's a lot of decimal characters, and the arduino floats don't support near that many. From the arduino reference of floats:

Floats have only 6-7 decimal digits of precision. That means the total number of digits, not the number to the right of the decimal point. Unlike other platforms, where you can get more precision by using a double (e.g. up to 15 digits), on the Arduino, double is the same size as float.

Lefty

Ohh...

Is there anything I can use? "int" wont work, will it?

Ollie

Chalky:
Ohh...

Is there anything I can use? "int" wont work, will it?

Ollie

There are ways of using long variable types and scaling the equation, but you best let the software gurus look at it and see if it would give you an improvement over using floats. I think your basic limitation is the 10 bits of precision from the analog D/A conversion.

Lefty

I just tried 9 digits instead of however many and made no difference!
Maybe there is some way to use that value but by using 0.00488759 I get 1022.996971928963... (5/shortened value) anyway so not really any difference lol

Hi everyone ! i got a problem with tihs part of the code, i don't get a correct value in return. I'm using the brand new Tinkerkit LDR sensor wich doesn't have any information about the serial resistor. So i'm a little confused with this formula.

Serial.print((500/((10.72/(5-volts0))*volts0)), 2); //lux calculation