As a coding novice, I’m having some difficulty with what I expect is a simple task. I want to switch an output pin high when an input goes high. But only if that input remains high for over say 500 ms. My IF command currently just tests for HIGH (IOW over 2.5 V), but obviously I don’t want a brief noise pulse to be acceptable.
Save the time from millis() and set a boolean to true when the input goes HIGH. Set the boolean to false when the input goes LOW. Each time through loop(), if the boolean is true compare the current value of millis() with the start time previously saved. If more than 500 milliseconds has elapsed then turn on the output.
I like to write the code for this problem in two separate chunks - like this
void loop() {
buttonState = digitalRead(buttonPin);
if (buttonState == HIGH) { // assumes LOW when pressed and HIGH when not-pressed
lastTimeButtonWasHigh = millis();
}
if (millis() - lastTimeButtonWasHigh >= requiredTime) {
// input has been LOW throughout the required time
// do whatever needs to be done
}
}
Excellent, thanks both. I haven’t used millis() before so this is a good learning exercise. Will try that method later this morning when back at my PC.
EDIT: Just studying UKHeliBob's sticky 'Using millis() for timing', which I should have found earlier.