I just can't quite get my brain around this photocell debouncer. All I need is a boolean that is true if it's light, and false if it's dark. Light and dark being set by MySettings.Photocell_Level. I don't want the boolean to oscillate when the light level is close to the threshold, though, so I thought I'd add a 5 second debouncer to it. I've struggled too long on this one...
This is a mess, but:
void Photocell(){
boolean newLightLevel;
boolean prevLightLevel;
long lightDebounceTime;
int senseVal = analogRead(photocellPin); //get the pin reading
Serial.print("photocell reading: ");
Serial.println(senseVal);
if (senseVal > 62) newLightLevel = true; //light level is higher than threshold MySettings.Photocell_Level
else newLightLevel = false; //it's darker than threshold
if (newLightLevel != prevLightLevel) { // lighting has changed
lightDebounceTime = millis(); // reset the debouncing timer
prevLightLevel = newLightLevel; //the previous light is now the current reading
}
if (millis() - lightDebounceTime > 5000) { //It's stayed either light or dark for 5 seconds
Serial.print("Level changed to :");
lightLevel = newLightLevel; //True for light, False for dark
}
if(lightLevel) Serial.println("LIGHT");
else Serial.println("DARK");
}
By all means, if there's a better way to go about this, please do tell!
light1 is of type float;
Light sensors don't bounce, so its called smoothing;
light1 = light1 * 0.9 + float(analogRead(light1Pin)) * 0.1;
Adjust the 0.9 & 0.1 to suit but together they should add up to 1.
Perhaps you should just set different thresholds for OFF and ON:
void Photocell()
{
boolean prevLightLevel = lightLevel;
int senseVal = analogRead(photocellPin); //get the pin reading
if (senseVal > 62)
lightLevel = true; //light level is higher than light threshold MySettings.Photocell_Level
else
if (senseval < 54)
lightLevel = false; //it's darker than dark threshold
if (lightLevel != prevLightLevel)
{ // lighting has changed
if(lightLevel)
Serial.println("LIGHT");
else
Serial.println("DARK");
prevLightLevel = lightLevel;
}
}
johnwasser:
Perhaps you should just set different thresholds for OFF and ON:
void Photocell()
{
boolean prevLightLevel = lightLevel;
int senseVal = analogRead(photocellPin); //get the pin reading
if (senseVal > 62)
lightLevel = true; //light level is higher than light threshold MySettings.Photocell_Level
else
if (senseval < 54)
lightLevel = false; //it's darker than dark threshold
if (lightLevel != prevLightLevel)
{ // lighting has changed
if(lightLevel)
Serial.println("LIGHT");
else
Serial.println("DARK");
prevLightLevel = lightLevel;
}
}
thanks, something like this worked good.
Just in case you decide to later use a digital photo-sensor, like a photo-transistor with a comparator, all you need is the button debouncing code if the output is bouncy.