I wrote code that tracks the duration of a button click. It has bounce protection and frequent clicks. (Freeze)
My code:
bool freeze_time, btn_read, debounce;
unsigned int freeze_timer, btn_timer;
#define BTN 6
void setup() {
Serial.begin(9600);
pinMode(BTN, INPUT);
}
void loop() {
/* Freeze Timer Protection */
if(freeze_time) {
if((millis() - freeze_timer) >= 2500) {
freeze_time = false;
btn_read = false;
}
}
/* Read Button State */
if(digitalRead(BTN) == HIGH) {
if(!btn_read) {
btn_timer = millis();
debounce = true;
btn_read = true;
}
}
/* BTN Read Process */
if(btn_read) {
/* Debounce Protection */
if(debounce) {
if((millis() - btn_timer) >= 1000) {
if(digitalRead(BTN) == HIGH) {
Serial.println("Debounce ok.");
btn_timer = millis();
debounce = false;
} else {
Serial.println("Debounce fail.");
freeze_time = true;
debounce = false;
}
}
}
/* BTN Read Process */
else if(!freeze_time) {
if((millis() - btn_timer) >= 1500) {
if(digitalRead(BTN) == HIGH) {
Serial.println("Ok. Button Pressed > 1500ms");
freeze_timer = millis();
freeze_time = true;
} else {
Serial.println("Ok. Button Pressed < 1500ms");
freeze_timer = millis();
freeze_time = true;
}
}
}
}
}
I checked it on real Arduino UNO and Tinkercad simulator. Initially, everything works well, but if I press the button indefinitely, the system will fail (every time you press the serial port, messages appear as if all flags were lost and the timers did not work. I filmed the behavior:
1) Initially: http://recordit.co/lVlR1z1CUq 2) System is broken: http://recordit.co/lhvzM100DI
What could be the problem and how to make it fault tolerant?