使用按钮开灯关灯
接线图非常简单,LED接GPIO17号口,按钮接GPIO2号口,负极接GND地线。
代码也非常简单:
from gpiozero import LED, Button from signal import pause led = LED(17) button = Button(2) button.when_pressed = led.on button.when_released = led.off pause() 复制代码执行代码,按下按钮,发光二极管就会亮,松开就会灭。
使用按钮开灯关灯(二)还有一种source的写法,直接把按钮的状态提供给发光二极管,达到同样的效果。
from gpiozero import LED, Button from signal import pause led = LED(17) button = Button(2) led.source = button pause() 复制代码 按钮按下和松开先上效果
接线非常简单,按钮一端连接GPIO2号针脚,一端连接GND地线。
代码灰常简单:
from gpiozero import Button button = Button(2) while True: if button.is_pressed: print("Button is pressed") else: print("Button is not pressed") 复制代码 等待按钮按下才执行直接上代码吧:
from gpiozero import Button button = Button(2) button.wait_for_press() print("Button was pressed") 复制代码程序执行到button.wait_for_press()这一句之后,会先停下,等待按钮按下之后,才会继续执行。
按下执行特定函数直接上代码:
from gpiozero import Button from signal import pause def say_hello(): print("Hello!") button = Button(2) button.when_pressed = say_hello pause() 复制代码按下按钮,执行say_hello()这个函数。
松开执行特定函数上效果图:
上代码:
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() 复制代码按下会执行say_hello()函数,松开会执行say_goodbye()函数。
长按4秒关机上代码:
from gpiozero import Button from subprocess import check_call from signal import pause def shutdown(): check_call(['sudo', 'poweroff']) shutdown_btn = Button(2, hold_time=4) shutdown_btn.when_held = shutdown pause() 复制代码增加了一个hold_time=4长按4秒才触发的初始化,触发之后执行shutdown()函数关机。
小游戏:谁的反应快?接线图:两个按钮分别连接GPIO2、3号口,LED连接GPIO 17号口。
上代码:
from gpiozero import Button, LED from time import sleep import random led = LED(17) player_1 = Button(2) player_2 = Button(3) time = random.uniform(2, 5) sleep(time) led.on() while True: if player_1.is_pressed: print("Player 1 wins!") break if player_2.is_pressed: print("Player 2 wins!") break led.off() 复制代码程序开始执行后,在(2,5)秒随机点亮LED灯,谁抢险按下按钮,就会显示谁赢了。
好了,本次介绍就到这里,这个系列的全文会收录在我的github目录,欢迎大家star和沟通:github.com/asukafighti…