Untitled

mail@pastecode.io avatar
unknown
plain_text
22 days ago
1.0 kB
1
Indexable
Never
import serial
import sys
import threading

COM_PORT = 'COM5'  # 請自行修改序列埠名稱
BAUD_RATES = 9600
ser = serial.Serial(COM_PORT, BAUD_RATES)

def read_from_port(ser):
    while True:
        if ser.in_waiting:
            mcu_feedback = ser.readline().decode().strip()  # 接收回應信息並解碼
            print('Arduino reaction:', mcu_feedback)
            if mcu_feedback.lower() == 'e':  # 如果接收到'e',關閉序列埠並退出程序
                ser.close()
                print('再見!')
                sys.exit()

def listen_for_exit():
    while True:
        end = input('按e關閉程式:').lower()
        if end == 'e':
            ser.close()
            print('再見!')
            sys.exit()

try:
    # 創建並啟動一個線程來讀取串口數據
    thread = threading.Thread(target=read_from_port, args=(ser,))
    thread.daemon = True
    thread.start()

    # 主線程繼續監聽用戶輸入
    listen_for_exit()

except KeyboardInterrupt:
    ser.close()
    print('再見!')
Leave a Comment