硬体規格
輕觸開關圖片如下所示
共有四個腳位,但只有二個引腳,內凹的 1、3 及 2、4 相連。按下後,1、2、3、4 全相連。
當按下時,12及34才會相連。放開時就會斷開。
線路接法
將樹莓派腳位 1 的 3.3V 訊號電壓給輕觸開關 1 或 3 ,然後 GPIO 27 接入輕觸開關 2 或 4 腳位進行偵測是否開關有按下,如下圖所示。
按下開關才亮
執行如下代碼,一開始燈不會亮,按下開關燈就亮起,放開就會熄滅。
from gpiozero import Button from gpiozero import LED from signal import pause led=LED(17) button=Button(2) button.when_pressed=led.on button.when_released=led.off pause()
按下亮,再按下滅
此例按一下 switch 燈會亮,再按一下燈會滅
from gpiozero import Button from gpiozero import LED from signal import pause import time def test(): global led_status if led_status: led.off() else: led.on() led_status=not led_status time.sleep(0.03) led_status=False led=LED(17) button=Button(2) button.when_released=test pause()
長按
Button 類別也支援長按的能,底下的代碼,在按鈕按住 2 秒後,即會自動關機
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=2) shutdown_btn.when_held = shutdown pause()
執行緒
若要變換 Led,則需使用執行緒。
本範例按一下按鈕,三個 Led 依順序切換,再按一下則全部關掉,完整程式碼如下。
import RPi.GPIO as gpio import time import threading WAIT_TIME=200 led18 = 13 led23 = 19 led24 = 26 touch_key=17 ledOn=False def led(data): global ledOn ledOn = not ledOn print("Thomas", ledOn) if ledOn: t=threading.Thread(target=runnable) t.start() else: gpio.output(led18, gpio.LOW) gpio.output(led23, gpio.LOW) gpio.output(led24, gpio.LOW) def runnable(): while ledOn: gpio.output(led18, gpio.HIGH) time.sleep(0.05) gpio.output(led18, gpio.LOW) time.sleep(0.01) gpio.output(led23, gpio.HIGH) time.sleep(0.05) gpio.output(led23, gpio.LOW) time.sleep(0.01) gpio.output(led24, gpio.HIGH) time.sleep(0.05) gpio.output(led24, gpio.LOW) time.sleep(0.01) gpio.output(led24, gpio.HIGH) time.sleep(0.1) gpio.output(led24, gpio.LOW) time.sleep(0.01) gpio.output(led23, gpio.HIGH) time.sleep(0.1) gpio.output(led23, gpio.LOW) time.sleep(0.01) gpio.output(led18, gpio.HIGH) time.sleep(0.1) gpio.output(led18, gpio.LOW) time.sleep(0.01) def init(callback): gpio.setwarnings(False) gpio.setmode(gpio.BCM) gpio.setup(led18, gpio.OUT) gpio.output(led18, gpio.LOW) gpio.setup(led23, gpio.OUT) gpio.output(led23, gpio.LOW) gpio.setup(led24, gpio.OUT) gpio.output(led24, gpio.LOW) gpio.setup(touch_key, gpio.IN) gpio.add_event_detect(touch_key, gpio.RISING, callback=callback,bouncetime=WAIT_TIME)#放開 #gpio.add_event_detect(touch_key, gpio.FALLING, callback=callback,bouncetime=WAIT_TIME)#按下 def destroy(): try: gpio.remove_event_detect(touch_key) gpio.cleanup() except Exception as e : print(f"destroy fail:{e}") if __name__=='__main__': try: init(led) while True: time.sleep(1) except: destroy()
todo