====== Reading Buttons with GPIO ======
One of the better things to do with a GPIO bus is read inputs. The Raspberry PI can only read digital inputs directly, i.e. on or off. Conveniently, that’s also the modes of a momentary switch.
There aren’t any new gpio functions here. The biggest difference is that we’re setting one of our pins (pin 22 in this case) to be an input.
===== The Code =====
Momentary button input is a tricky beast. The button will be pushed for a variable amount of time. The program will poll the state of the button very rapidly. To make each button push count only once, we need to keep track of the state of the button on each poll, and only take action when:
- The state has changed.
- The pin is high.
I have also introduced some slight delays. When the state of the button changes, we’re pausing for a tenth of a second to make sure that we get a chance for the light to change state. At the end of each loop we’re pausing for a 100th of a second just because polling more frequently doesn’t really do any good.