Monthly Archives: October 2015

LDR debouncing

Hey all,

Back for some more fiddling with Light Depended Resistors. I’ve been writing a little piece of Arduino code to debounce an LDR (or more than one). I’ve noticed that LDR’s tend to behave irregular. No idea why, but I guess that’s the way it is. To get a good reading you need a couple readings and average them out. In the code snippet below I added an RBG LED on PWM pins 11, 10 and 9 and an LDR with a pullup resistor on A0.

What this code does:
– Take, in this case 19, readings and put them in an array with a pause of 1/4s between them (you can adjust that with the delay function in the first for-loop)
– Take out the highest and lowest value to correct for weird readings on the analog port
– Average everything out and adjust PWM accordingly.

Bear in mind that the adjusting of the PWM pins has some caveats:
– Map() the analog values which come out of the port to 0-255, because that’s what analogWrite can handle
– Because LED’s, especially blue/white ones can be really bright I added a correction factor of 150. In other words, if we measure 200, the PWM pin actually sends 50 as output value. Of course you can use the outcome just as it as, a value from 0-1023 for other purposes
– After that I added a constrain() to ensure the values make sense for PWM. I added three different constrains for each color because the human eye perceives different base colors in different ways.

As you can see at the bottom I constrain everything with a minimum value of 0. If you set this to 1 our LED will always be on.