[入门教程]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")
此处查阅了df的wiki,咨询了李工,按钮分为两种类型,一种是按下高电平,松开为低电平;另一种洽洽相反;
ZERO的库设置时可能正好和我用的模块相反;
gpiozero 库参考资料
如果您手头有案例中的配件,请测试一下看看效果。
测试代码2
from gpiozero import Button
from signal import pause
def say_hello():
print("Hello!")
button = Button(16)
button.when_pressed = say_hello
pause()
测试代码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()
测试代码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()
https://v.youku.com/v_show/id_XNDYyNTkyNzkwNA==.html
Python来控制树莓派可以更好玩
页:
[1]