#define THRESHOLD 10 // how many times we want to see it changed until we believe it.
int debounce_counter; // used for debouncing
int pulse_counter; // counts the pulses between counter_clr signals
int motor_pulses; // the resulting variable
int state;
void InitState() {
// this initializes the state
state = PULSE; // assume steady state
debounce_counter = 0;
pulse_counter = 0;
motor_pulses = 0;
}
void CheckState() {
if (PULSE == state) {
// forget what we were counting. No change took place
debounce_counter = 0;
return;
}
if (debounce_counter++ < THRESHOLD) {
// There has been a change. But it didn't persist long enough
return;
}
// The change persisted for a while. Record the change of state, reset the counter
debounce_counter = 0;
if (state = !state) {
// We detected transition 0->1, do nothing
return;
}
// transition 1->0. Record new pulse
pulse_counter++;
if (!pulse_clr) {
// No pulse_clr signal yet
return;
}
// set the resulting variable, reset the pulse counter
motor_pulses = pulse_counter;
pulse_counter = 0;
pulse_clr = 0;
}