-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserial_com.py
More file actions
35 lines (30 loc) · 1.09 KB
/
Copy pathserial_com.py
File metadata and controls
35 lines (30 loc) · 1.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import serial # 引用pySerial模組
from time import sleep
import sys
COM_PORT = 'COM4' # 指定通訊埠名稱
BAUD_RATES = 9600 # 設定傳輸速率
ser = serial.Serial(COM_PORT, BAUD_RATES) # 初始化序列通訊埠
try:
while True:
# 接收用戶的輸入值並轉成小寫
choice = input('按1開燈、按2關燈、按e關閉程式 ').lower()
if choice == '1':
print('傳送開燈指令')
ser.write(b'1') # 訊息必須是位元組類型
# sleep(0.5) # 暫停0.5秒,再執行底下接收回應訊息的迴圈
elif choice == '2':
print('傳送關燈指令')
ser.write(b'L2')
# sleep(0.5)
elif choice == 'e':
ser.close()
print('再見!')
sys.exit()
else:
print('指令錯誤…')
while ser.in_waiting:
mcu_feedback = ser.readline().decode() # 接收回應訊息並解碼
print('控制板回應:', mcu_feedback)
except KeyboardInterrupt:
ser.close()
print('再見!')