- Python Programming with Raspberry Pi
- Sai Yamanoor Srihari Yamanoor
- 192字
- 2021-07-02 23:48:48
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.
- 后稀缺:自動化與未來工作
- Hands-On Intelligent Agents with OpenAI Gym
- 繪制進程圖:可視化D++語言(第1冊)
- 大學計算機信息技術導論
- STM32G4入門與電機控制實戰:基于X-CUBE-MCSDK的無刷直流電機與永磁同步電機控制實現
- 自主研拋機器人技術
- CompTIA Network+ Certification Guide
- 網絡化分布式系統預測控制
- Linux服務與安全管理
- 工業機器人應用案例集錦
- 工業機器人實操進階手冊
- 寒江獨釣:Windows內核安全編程
- 智能小車機器人制作大全(第2版)
- 7天精通Photoshop CS5平面視覺設計
- Arduino創意機器人入門:基于Mind+