實作:內建輸入與外接輪出
-
- 實作
請用「內建輸入裝置」的「鍵盤」,使用按鍵「up」,控制「外接輸出裝置」的「LED燈」亮。
請用「內建輸入裝置」的「鍵盤」,使用按鍵「down」,控制「外接輸出裝置」的「LED燈」不亮。- 接線
- 程式
#+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ #|R|a|s|p|b|e|r|r|y|P|i|.|c|o|m|.|t|w| #+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ # Copyright (c) 2016, raspberrypi.com.tw # All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. # # Author : sosorry # Date : 06/22/2014 # Revised by Jean 02/20/2025 import RPi.GPIO as GPIO import time from pynput.keyboard import Key from pynput.keyboard import Listener GPIO.setmode(GPIO.BOARD) LED_PIN = 12 GPIO.setup(LED_PIN, GPIO.OUT) def on_press(key): print('{0} pressed'.format(key)) def on_release(key): print('{0} release'.format(key)) if key == Key.up: print("LED is on") GPIO.output(LED_PIN, GPIO.HIGH) if key == key.down: print("LED is off") GPIO.output(LED_PIN, GPIO.LOW) if key == Key.esc: # Stop listener GPIO.cleanup() return False # Collect events until released with Listener( on_press=on_press, on_release=on_release) as listener: listener.join()