树莓派超全系列文档--(11)RaspberryOS上使用 Python控制GPIO

[复制链接]
发表于 2025-10-5 19:36:19 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

×
文章泉源:http://raspberry.dns8844.cn/documentation
原文网址
使用 Python 控制 GPIO

使用 GPIO Zero 库可以轻松地用 Python 控制 GPIO 装备。该库在 gpiozero.readthedocs.io 上有全面的文档分析。
有关 GPIO 硬件的信息,请参阅 GPIO 硬件。
LED 控制

以下示例代码可控制毗连到 GPIO17 的 LED:
  1. from gpiozero import LED
  2. from time import sleep
  3. led = LED(17)
  4. while True:
  5.     led.on()
  6.     sleep(1)
  7.     led.off()
  8.     sleep(1)
复制代码
在 Thonny 等 IDE 中运行此代码,LED 将反复闪灼。
LED 方法包罗 on()、 off()、 toggle() 和 blink() 。
读取按键状态

要读取毗连到 GPIO2 的按钮的状态:
  1. from gpiozero import Button
  2. from time import sleep
  3. button = Button(2)
  4. while True:
  5.     if button.is_pressed:
  6.         print("Pressed")
  7.     else:
  8.         print("Released")
  9.     sleep(1)
复制代码
按钮功能包罗属性 is_pressed 和 is_held ;回调 when_pressed、 when_released 和 when_held ;以及方法 wait_for_press() 和 wait_for_release 。
使用按钮控制LED

以下示例代码读取毗连到 GPIO2 的按钮的状态,并在按下按钮时点亮毗连到 GPIO17 的 LED:
  1. from gpiozero import LED, Button
  2. led = LED(17)
  3. button = Button(2)
  4. while True:
  5.     if button.is_pressed:
  6.         led.on()
  7.     else:
  8.         led.off()
复制代码
大概:
  1. from gpiozero import LED, Button
  2. led = LED(17)
  3. button = Button(2)
  4. while True:
  5.     button.wait_for_press()
  6.     led.on()
  7.     button.wait_for_release()
  8.     led.off()
复制代码
大概:
  1. from gpiozero import LED, Button
  2. led = LED(17)
  3. button = Button(2)
复制代码
上一篇 – 树莓派超全系列文档–(10)RaspberryOS上使用 Python
下一篇 – 树莓派超全系列文档–(12)怎样使用raspi-config工具其一
回复

使用道具 举报

登录后关闭弹窗

登录参与点评抽奖  加入IT实名职场社区
去登录
快速回复 返回顶部 返回列表