python提供了豐富的module 對串口的操作同樣有對應(yīng)的module:serial
環(huán)境:python3.5 藍(lán)牙模塊:HC-05 波特率38400
首先導(dǎo)入serial模塊(通過pip install serial 安裝)
獲取串口ser 通過serial.Serial(地址,波特率,超時(shí)時(shí)間)
創(chuàng)建線程監(jiān)聽串口數(shù)據(jù)
使用 ser.in_waiting() 獲知數(shù)據(jù)量 這個(gè)函數(shù)返回當(dāng)前串口收到的數(shù)據(jù)長度
收取數(shù)據(jù)后進(jìn)行詳細(xì)操作
import serial
import GlobalVarible
import threading
import time
from ProcMsg import ProcMsg
ser = serial.Serial('com2', 38400, timeout=0.5)
index = 0
i = 0
def loop():
print("串口狀態(tài):" + str(ser.is_open))
while ser.isOpen():
if (ser.in_waiting > 0):
buffer = ser.read(ser.in_waiting)
i = len(buffer)
p = ProcMsg(buffer)
print(type(buffer))
p.proc()
elif (ser.in_waiting <= 0):
time.sleep(1)
t = threading.Thread(target=loop(), name="LoopThread")
t.start()
t.join()