Thanks Castaway for posting your work.
Nice!!!
In those moments where the light in your room reaches a “borderline” amount of light, the digital pin will most likely start fluctuating between “on” and “off” and this is probably what you’re seeing right now.
So … first of all I’d use an analog pin, if possible speed wise. With the analog pin we’d have better control over the values read.
Another option, come to think of it, is to slow down the effect of a read value.
What I mean with that, is that a detected value should at least be working for a couple seconds before changing it’s state.
So in words: if we start detecting and we see that it’s dark in the room (LEDs should be ON), and we go through the AdjustBrightness function and we have not yet reached our “count”, then leave brightness as is. If during the “count” we see again a detection of “dark room”, restart the counting. If we exceed our count threshold and the LDR still says “light room”, then and only then switch state (LEDs OFF), and repeat the same cycle.
I hope I explained what I was thinking right haha …
Let me try this in code (untested):
...
int BrightnessCounter 0;
#define MaxBrightnessCount 1000;
...
void AdjustBrightness() {
int LDRValue = 0; // result of reading the digital pin
LDRValue = digitalRead(LDRpin);// read the value from the LDR
// if we detect the same brightness as before, reset counter
if( ((LDRValue==1) && (BRIGHTNESS==0)) || ((LDRValue!=1) && (BRIGHTNESS==70)) ) {
BrightnessCounter = 0;
}
// However, if we exceeded the counter max, then set new brightness
else if(BrightnessCounter>=MaxBrightnessCount) {
if(LDRValue==1) {
BRIGHTNESS = 0; // Light, so set LED brightness to 0%
} else {
BRIGHTNESS = 70; // Dark,so set LED brightness to 70%
}
}
BrightnessCounter++; // increase counter
}
I’ve defined a new variable (BrightnessCounter) and a “constant” (MaxBrightnessCount).
If we see that the current brightness is still valid and the same: Reset counter.
If this is not the case, AND we exceeded the MaxBrightnessCount value, then determine the proper Brightness again.
You might need to test and play with the MaxBrightnessCount … but this is what I;d start playing with.
Since I don’t have a setup with an LDR, I can’t really test this.
Please let us know how this worked out …