Button Loop Sample

This sample demonstrates reading onboard button press state.

To run the sample:

  1. Copy the sample code to a folder on the Raspberry Pi.

  2. Open terminal, and then go to the folder you copied the sample.

  3. Run the sample with the following command:

python3 Button_Loop.py

Sample Code

Button_Loop.py
#!/usr/bin/env python3

#This sample demonstrates reading onboard button press state.
#Install IoT HAT 3 library with "pip3 install turta-iothat3"

import time
from turta_iothat3 import Turta_Button

#Initialize
button = Turta_Button.ButtonInput()

try:
    while True:
        #Read button state
        button_state = button.read()

        #Print the reading
        print("Button State....: " + ("Pressed." if button_state else "Released."))

        #Wait
        time.sleep(0.5)

#Exit on CTRL+C
except KeyboardInterrupt:
    print('Bye.')

Result

When you run the sample, it reads and prints button press state. The example output should be like this:

Button State....: Released.
Button State....: Released.
Button State....: Released.
Button State....: Released.
Button State....: Released.
Button State....: Pressed.

To stop the Python script, just press CTRL + C.

Last updated