Writing a Program

To make a message appear each time the button is pressed, we are going to write a short Python program, so exit the Python Console by typing:
Download: file
>>> exit()
This should take you back to the Linux prompt.

Enter the following command to create a new files called switch.py
Download: file
# nano switch.py
Now paste the code below into the editor window.
Download: file
import Adafruit_BBIO.GPIO as GPIO
import time

GPIO.setup("P8_12", GPIO.IN)

old_switch_state = 0

while True:
    new_switch_state = GPIO.input("P8_12")
    if new_switch_state == 1 and old_switch_state == 0 :
        print('Do not press this button again!')
        time.sleep(0.1)
    old_switch_state = new_switch_state
Save and exit the editor using CTRL-x and the Y to confirm.

To start the program, enter the command:
Download: file
# python switch.py
Each time you press the button, you should see a message.
Download: file
# python switch.py 
Do not press this button again!
Do not press this button again!
When you want to stop the program, use CTRL-c.

We only want the message to appear when the button is pressed. To prevent the message appearing continuously as long as the button is held down the variable old_switch_state is used and the message only displayed when the switch goes from not being pressed to being pressed.

The time.sleep command is a simple way to avoid switch bounce, which would cause the message to appear twice if the switch contacts did not close cleanly when the button is pressed.
This guide was first published on Jul 30, 2013. It was last updated on Jul 30, 2013.
This page (Writing a Program) was last updated on Jul 04, 2020.