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 ...

Get Raspberry Pi 3 Cookbook for Python Programmers - Third Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.