[Raspberry Pi]树莓派多线程下串口收发数据
鼠鼠用的是python开发树莓派,因为python是最优美的语言!
少废话,直接上代码:
import threading
import serial
import cv2
ser = serial.Serial("/dev/ttyAMA0", 115200)
ser.timeout = 5
if not ser.isOpen:
ser.open() # 打开串口
startRdFlag = 0
rxBuffer = []
dataUpdateFlag = 0
def comPrint(_string):
message = _string
ser.write(message.encode())
def readThread():
global rxBuffer, dataUpdateFlag
print("start Read Thread!\n")
while True:
if dataUpdateFlag == 0:
rxBufferLen = ser.inWaiting()
if rxBufferLen > 0:
rxBuffer = ser.readline()
dataUpdateFlag = 1 # 通知主任务有新数据
def mainThread():
global dataUpdateFlag,rxBuffer
print("start Main Thread!\n")
while True:
ret, frame = cap.read()
cv2.imshow("frame", frame)
if dataUpdateFlag == 1: # 有新数据
# 处理数据
print(rxBuffer)
# flag归零
dataUpdateFlag = 0
# 处理完数据,开始接收新数据
cv2.waitKey(5)
cv2.destroyWindow()
if __name__ == '__main__':
thread1 = threading.Thread(target=mainThread)
thread2 = threading.Thread(target=readThread)
thread1.start()
thread2.start()
标签:__,树莓,rxBuffer,ser,dataUpdateFlag,串口,多线程
From: https://www.cnblogs.com/Asaka-QianXiang/p/17537730.html