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()
函數。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()
函數關機。GPIO二、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()
好了,本次介紹就到這裏,這個系列的全文會收錄在個人github目錄,歡迎你們star和溝通:https://github.com/asukafighting/RaspberryPiHackergit