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

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.

主站蜘蛛池模板: 盘山县| 九龙县| 黑山县| 东源县| 寿光市| 孟津县| 常德市| 长治市| 大方县| 都昌县| 阿荣旗| 三穗县| 英山县| 察隅县| 丹江口市| 邛崃市| 正定县| 托克逊县| 清苑县| 太湖县| 罗田县| 岗巴县| 沙河市| 巢湖市| 遵义市| 威信县| 阳高县| 二连浩特市| 霍山县| 南靖县| 重庆市| 彩票| 鱼台县| 广州市| 日照市| 开化县| 凤阳县| 汾阳市| 黄大仙区| 迁西县| 清远市|