Quote:
Code:
button_now = get_button(); // get the button state (pressed or not pressed)
if (button_now && ! button_previous) // detect rising edge only
runMotor = ! runMotor; // if rising edge, toggle the direction boolean
button_previous = button_now; // save the button state for comparison in the next iteration
if (runMotor)
motor.set(1)
|
In the past, with that logic, we ran into "bounce" problems with the buttons. As the buttons transition between states (pressed/unpressed), they throw off a lot of state transitions.
In other words, if you actually counted the number of transitions with a single button press, you can get 5 or more transitions. In essence, the 1/2 way point of a button is "undefined", and can be either pressed or not pressed, and it can change between reads.
If it is simply starting a motor when pressed, and stopping a motor when released, you probably won't notice it (the motor controller cycles between off/on really fast). If it is something else (like a toggle), you could end up in an unexpected state.
In order to avoid the problem, you have to set a timer. You reset the timer when a valid transition is detected. If the next detected transition is within 250 milliseconds (1/4 second), you ignore it. Remember to debounce the release too so you don't get an accidental "press" when the button is "released".