Fixing erratic LDR values

ldr

After working with a few different sensors hooked up the Arduino, I was experiencing some strange issues where as the value of the LDR would constantly jump up and down within a specific range. I am not sure if this is the quality of the sensor, but it was doing it for all of the LDRs that I have.

I decided that it needed some artificial smoothing in the code to get a useful value. See sample code below for smoothing out LDR values. We need to change the value from an erratic analog value to a digital percentage as an integer.

As you can see, the function takes two parameters samples and sampleInterval The samples is how many times it should query the LDR for the value and the second parameter is how long it should wait before each query.

Depending on the size of the LDR and quality, the min and max smooth value may need to be adjusted (550 and 1023) depending on the range you get back from your LDR.

The function will return an Integer between 0 and 100 depending on the amount of light.