there is a function millis () available on the arduino that returns the number of milliseconds as an unsigned long integer since the chip started up. this will overflow in just under 50 days, so if you remember to reset your device every 6 weeks you can keep track of your own time.
here is an
untested version of the debounce routine coded without waits. your other functions would have to be rewritten in a similar manner.
- Code: Select all
int switchState;
int lastSwitchState = LOW;
unsigned char debounce = 0;
unsigned long debounceTime;
int button_pressed() {
switchState = digitalRead(switchPin);
if (debounce) {
if (debounceTime < millis ()) { // debounce time expired?
debounce = 0;
lastSwitchState = switchState;
if (switchState == HIGH) return 1;
}
}
else {
if (switchState == HIGH && lastSwitchState == LOW) { // button was pressed
debounce = 1;
debounceTime = millis () + 11; // delay will be >10 and <11 ms.
}
}
return 0;
}
this code will fail spectacularly between 49 and 50 days. or between 99 and 100 days. put another way "...you'll regret it. Maybe not today. Maybe not tomorrow. But, shoon, and for the resht of your life."
this can be corrected if you are certain that none of your code will run longer than your minimum delay by changing the test (debounceTime < millis()) to (debounceTime == millis()). might be a safe bet, but if not the code will likely fail spectacularly in far less than 49 days.
but, y'know... millis() >= debounceTime, (not the same as debounceTime < millis(), in case milliseconds have overflowed), might be the best bet.
also, please note that an arduino millisecond is actually 1.024 ms, so don't try building a clock with this thing.
and, in addition, the delay for delay(i) will be anywhere between i-1 and i milliseconds.