小实验目录
树莓派科学小实验 001 点亮第一盏LED灯 002 点亮LED灯组 03_开关控制LED灯
一、实验部件
1 实验元件:
LED 灯 和按键模块
2 连接GPIO针脚
实验用到的GPIO管脚:17,27,6,13
提示:以下是本篇文章正文内容,下面案例可供参考
二、官网的例子
from gpiozero import Button
from signal import pause
def say_hello():
print("Hello!")
def say_goodbye():
print("Goodbye!")
button = Button(2)
button.when_pressed = say_hello
button.when_released = say_goodbye
pause()
三、通过按键来控制LED灯的亮灭
"""
#类说明文件
author = "Derek Tian"
version = '0.0.1'
make day=2022-01-24
"""
__docformat__ = "restructuredtext en"
__all__ = []
__license__ = "MIT license"
from gpiozero import Button,LED
from signal import pause
button1=Button(6)
button2=Button(13)
red=LED(17)
yellow=LED(27)
def say_hello():
print("hello!")
red.on()
def say_goodbye():
print("Goodbye!")
red.off()
def say_hi():
yellow.on()
print("yellow led on")
def say_b():
yellow.off()
print("Yellow led off")
button1.when_pressed = say_hello
button1.when_released = say_goodbye
button2.when_activated=say_hi
button2.when_deactivated=say_b
pause()
当按键1 按下时:屏幕打印hello!抬起时打印Goodbye 当按键2 按下时:屏幕显示yello led on,抬起时打印yellow led of
结论:
需要给按键的按下和抬起定义事件,将需要的工作放在事件中。然后将事情赋值给开关的动作函数。不需要写While 的死循环 。 程序回自动多次调用。代码非常简单和清洁。
|