官术网_书友最值得收藏!

GPIO callback functions

Let's review some uses of functions with the GPIO example. Functions can be used in order to handle specific events related to the GPIO pins of the Raspberry Pi. For example, the gpiozero library provides the capability of calling a function either when a button is pressed or released:

from gpiozero import Button 

def button_pressed():
print("button pressed")

def button_released():
print("button released")

#button is interfaced to GPIO 2
button = Button(2)
button.when_pressed = button_pressed
button.when_released = button_released

while True:
pass

In this example, we make use of the attributes when_pressed and when_released of the library's GPIO class. When the button is pressed, the function button_pressed is executed. Likewise, when the button is released, the function button_released is executed. We make use of the while loop to avoid exiting the program and keep listening for button events. The pass keyword is used to avoid an error and nothing happens when a pass keyword is executed.

This capability of being able to execute different functions for different events is useful in applications like home automation. For example, it could be used to turn on lights when it is dark and vice versa.

主站蜘蛛池模板: 宜兴市| 太原市| 陈巴尔虎旗| 蓝山县| 修武县| 南安市| 阿拉善盟| 景谷| 温泉县| 湘潭市| 吉林市| 和田市| 洞口县| 呼和浩特市| 贡嘎县| 苍溪县| 诸暨市| 广河县| 泗水县| 同德县| 新河县| 连平县| 固原市| 财经| 平和县| 花垣县| 万源市| 大姚县| 夏河县| 宁陕县| 杭锦后旗| 禹城市| 永安市| 大邑县| 秀山| 漳平市| 义乌市| 和硕县| 龙里县| 桂阳县| 长泰县|