马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有账号?立即注册
×
文章泉源:http://raspberry.dns8844.cn/documentation
原文网址
使用 Python 控制 GPIO
使用 GPIO Zero 库可以轻松地用 Python 控制 GPIO 装备。该库在 gpiozero.readthedocs.io 上有全面的文档分析。
有关 GPIO 硬件的信息,请参阅 GPIO 硬件。
LED 控制
以下示例代码可控制毗连到 GPIO17 的 LED:
- from gpiozero import LED
- from time import sleep
- led = LED(17)
- while True:
- led.on()
- sleep(1)
- led.off()
- sleep(1)
复制代码 在 Thonny 等 IDE 中运行此代码,LED 将反复闪灼。
LED 方法包罗 on()、 off()、 toggle() 和 blink() 。
读取按键状态
要读取毗连到 GPIO2 的按钮的状态:
- from gpiozero import Button
- from time import sleep
- button = Button(2)
- while True:
- if button.is_pressed:
- print("Pressed")
- else:
- print("Released")
- sleep(1)
复制代码 按钮功能包罗属性 is_pressed 和 is_held ;回调 when_pressed、 when_released 和 when_held ;以及方法 wait_for_press() 和 wait_for_release 。
使用按钮控制LED
以下示例代码读取毗连到 GPIO2 的按钮的状态,并在按下按钮时点亮毗连到 GPIO17 的 LED:
- from gpiozero import LED, Button
- led = LED(17)
- button = Button(2)
- while True:
- if button.is_pressed:
- led.on()
- else:
- led.off()
复制代码 大概:
- from gpiozero import LED, Button
- led = LED(17)
- button = Button(2)
- while True:
- button.wait_for_press()
- led.on()
- button.wait_for_release()
- led.off()
复制代码 大概:
- from gpiozero import LED, Button
- led = LED(17)
- button = Button(2)
复制代码 上一篇 – 树莓派超全系列文档–(10)RaspberryOS上使用 Python
下一篇 – 树莓派超全系列文档–(12)怎样使用raspi-config工具其一
|