As in previous post, mraa library is used for handling the GPIO. For this example, the button will be used to turn on and off an LED connected to the Galileo. This example is going to be very similar to the previous one. The only difference being that the state of the LED is controlled by a button instead of the program running on Galileo itself.
The hardware connection:
The LED is connected to the pin D5 and the button is connected to D6.
As usual, mraa and time is imported. Then we set the pin D5 as output for driving the LED and pin D6 is set as input for reading the button state. This step is important to configure the function of the GPIO. If you forget this step, the internal port setting on Galileo would not change to reflect the intended behavior for that particular pin. Setting the port pin as input allows us to sense the voltage level applied at that particular pin. This is done using the “dir()” method on the GPIO pin.
To read the digital voltage level at the given pin, we use the read method:
This method returns a numerical value 1 if the voltage read at the pin is logical high or else it would return 0. This method can be used to read the button state.
Now that we know how buttons can be interfaced, Now is the time to look into the practical way with which the mechanical buttons can be interfaced.
Mechanical button such as supplied with the Grove kit have a property what is known as “button debouching“. Mechanical button being Mechanical, when you click the button, it does not immediately turn on or off. It would “bounce” for some time until it settles to it’s final state. This would reflect in our digital system such as Galileo rapidly changing voltage level. If we recorded this changing voltage level, we would not be able to properly determine the switch state since we might end up recording the “bouncy” signal which is not actually the final state. To over come this problem, the obvious solution would be to wait for some time till the switch settles.
The function “getButtonPress()” is implemented to detect the click. This function waits for the pin to go high:
while 1: if (btn.read() != 0): # No button press detected continue
After the pin goes high it waits for some time and let the button settle (“de-bounce”). Once it settles, the button state is checked again to confirm that the button click was intended and not accidental. Once the button click is detected, the function returns to the main and within main, depending on the state of “ledState” flag, the LED is turned on or off.