Simple Arduino sensor data feed
A button is not the simplest kind of sensor to read. While the concept is simple, there's an interesting subtlety to reading a button. The problem is that buttons bounce: they make some intermittent contact before they make a final, solid connection.
There's a simplistic way to debounce that involves a Busy Waiting design. We'll avoid this and show a somewhat more sophisticated debounce algorithm. As with the LED blinking, we'll rely on the millis()
function to see how long the button has stayed in a given state.
To debounce, we'll need to save the current state of the button. When the button is pressed, the signal on the input pin will become HIGH
and we can save the time at which this leading edge event occurred. When the button is released, the signal will go back to LOW
. We can subtract the two times to compute the duration. We can use this to determine if this was a proper press, just a bounce, or even a long press-and-hold event.
The function looks like...