2015浏览
查看: 2015|回复: 1

[教程] [入门教程]zero玩树莓派4 按钮开灯

[复制链接]
学习过LED模块之后,通常要开始按钮的学习,今天测试了,DF的按钮和ZERO库的兼容性实验,有点不一样。

一、实验目的
按钮控制LED灯的开关


二、实验设备
1.树莓派 *1       https://www.dfrobot.com.cn/goods-1976.html
2.树莓派扩展板*1     https://www.dfrobot.com.cn/goods-2041.html
3.LED模块*1 (gpio17号口) https://www.dfrobot.com.cn/goods-72.html
4.数字大按钮模块 黄色*1 (gpio17号口)   https://www.dfrobot.com.cn/goods-78.html

三、代码实现
测试代码1.用print()命令打印按钮的状态,示例代码库中的代码,意思是按下按钮提示“”Button is pressed“”松开按钮提示“”Button is not pressed“”
但是实际运行效果相反,松开按钮提示“”Button is pressed“”按下按钮提示“”Button is not pressed“”
from gpiozero import Button
button = Button(16)
while True:
    if button.is_pressed:
        print("Button is pressed")  
    else:
        print("Button is not pressed")



[入门教程]zero玩树莓派4  按钮开灯图1


此处查阅了df的wiki,咨询了李工,按钮分为两种类型,一种是按下高电平,松开为低电平;另一种洽洽相反;
ZERO的库设置时可能正好和我用的模块相反;
[入门教程]zero玩树莓派4  按钮开灯图3
[入门教程]zero玩树莓派4  按钮开灯图2


gpiozero 库参考资料
如果您手头有案例中的配件,请测试一下看看效果。
[入门教程]zero玩树莓派4  按钮开灯图4


测试代码2
from gpiozero import Button
from signal import pause
def say_hello():
    print("Hello!")
button = Button(16)
button.when_pressed = say_hello
pause()


[入门教程]zero玩树莓派4  按钮开灯图5


测试代码3
from gpiozero import Button
from signal import pause
def say_hello():
    print("Hello!")
def say_goodbye():
    print("Goodbye!")
button = Button(16)
button.when_pressed = say_hello
button.when_released = say_goodbye
pause()



[入门教程]zero玩树莓派4  按钮开灯图6


测试代码4 按钮控制LED亮灭


from gpiozero import LED, Button
from signal import pause
led = LED(17)
button = Button(16)
button.when_pressed = led.on
button.when_released = led.off
pause()





DFrJ5KYVQaH  中级技匠

发表于 2020-4-11 22:04:04

Python来控制树莓派可以更好玩
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

为本项目制作心愿单
购买心愿单
心愿单 编辑
[[wsData.name]]

硬件清单

  • [[d.name]]
btnicon
我也要做!
点击进入购买页面
上海智位机器人股份有限公司 沪ICP备09038501号-4

© 2013-2024 Comsenz Inc. Powered by Discuz! X3.4 Licensed

mail