這是一個簡單、乾淨的 Python 序列埠監控程式(命令列版本),使用 pyserial。它可在 Windows、macOS 與 Linux 上運作,讀寫 Arduino 或其他微控制器,用法就像 Arduino IDE 的序列埠監控視窗。
🔧 第 1 步:安裝 pyserial
bashCopyEditpip install pyserial
🐍 第 2 步:基本的序列埠監控腳本
pythonCopyEditimport serial
import threading
# === CONFIGURATION ===
PORT = '/dev/ttyUSB0' # Change to your actual port, e.g. COM3 on Windows
BAUDRATE = 9600
def read_from_port(ser):
while True:
try:
if ser.in_waiting:
line = ser.readline().decode('utf-8', errors='ignore').strip()
print(f"[RX] {line}")
except Exception as e:
print(f"[Error] {e}")
break
def main():
try:
ser = serial.Serial(PORT, BAUDRATE, timeout=1)
print(f"[Connected] Listening on {PORT} at {BAUDRATE} baud")
thread = threading.Thread(target=read_from_port, args=(ser,), daemon=True)
thread.start()
while True:
cmd = input("> ")
if cmd.lower() in ['exit', 'quit']:
break
ser.write((cmd + "\n").encode('utf-8'))
except serial.SerialException as e:
print(f"[Failed to connect] {e}")
except KeyboardInterrupt:
print("\n[Stopped by user]")
if __name__ == "__main__":
main()
🧪 輸出範例
bashCopyEdit[Connected] Listening on /dev/ttyUSB0 at 9600 baud
> LED ON
[RX] LED is now ON
> LED OFF
[RX] LED is now OFF
> quit
✅ 功能
- 即時讀取序列埠
- 可用鍵盤輸入傳送指令
- 適用於任何序列裝置(Arduino、ESP32 等)
- 輸入
quit或按Ctrl+C可正常結束