Hardware Reference
In-Depth Information
8
Finally, you can't just connect or
disconnect every time the connect
button is high. You want to send
a message only when the button
changes from low to high, indicat-
ing that the player just pressed it.
This method checks for a low-to-high
transition by comparing the state of
the button with its previous state. It's
called from the main loop.
// this method reads the button to see if it's just changed
// from low to high, and debounces the button in case of
// electrical noise:
boolean buttonRead(int thisButton) {
boolean result = false;
// temporary state of the button:
int currentState = digitalRead(thisButton);
// final state of the button:
int buttonState = lastButtonState;
// get the current time to time the debounce interval:
long lastDebounceTime = millis();
This method also debounces the
button, which means that it listens for
a few extra milliseconds to see whether
the button changes after the initial
read. Sometimes a pushbutton can
give several false readings for a few
milliseconds, as the electrical contacts
settle against one another. The cheaper
the switch, the more common this is.
If you find that your pushbutton gives
multiple readings each time you push
it, increase debounceInterval by a few
milliseconds.
while ((millis() - lastDebounceTime) < debounceInterval) {
// read the state of the switch into a local variable:
currentState = digitalRead(thisButton);
// If the pushbutton changed due to noise:
if (currentState != buttonState) {
// reset the debouncing timer
lastDebounceTime = millis();
}
// whatever the reading is at, it's been there for longer
// than the debounce delay, so take it as the actual current state:
buttonState = currentState;
}
// if the button's changed and it's high:
if(buttonState != lastButtonState && buttonState == HIGH) {
result = true;
}
// save the current state for next time:
lastButtonState = buttonState;
return result;
}
 
Search WWH ::




Custom Search