How it works...

As in the previous recipe, we set up the GPIO pin as required, but this time as an input, and we also enable the internal pull-up resistor (see Pull-up and pull-down resistor circuits in the There's more... section of this recipe for more information) using the following code:

GPIO.setup(BTN,GPIO.IN,pull_up_down=GPIO.PUD_UP) 

After the GPIO pin is set up, we create a loop that will continuously check the state of BTN using GPIO.input(). If the value returned is false, the pin has been connected to 0V (ground) through the switch, and we will use flite to count out loud for us each time the button is pressed.

Since we have called the main function from within a try/finally condition, it will still call GPIO.cleanup() even if we close the program using Ctrl + Z.

We use a short delay in the loop; this ensures that any noise from the contacts on the switch is ignored. This is because when we press the button, there isn't always perfect contact as we press or release it, and it may produce several triggers if we press it again too quickly. This is known as software debouncing; we ignore the bounce in the signal here.