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!