一、串口操作
import serial
port_list = list(serial.tools.list_ports.comports())
ser = serial.Serial(com, int(bps), timeout=int(timex))
ser.flushInput()
count = ser.inWaiting()
str = ser.readline(ser.in_waiting)
str = glo.ser.read(ser.in_waiting)
1 搜索串口
class getCom(QThread):
comUpdate = pyqtSignal(list)
port_list_orignal = []
def run(self):
"""得到所有的串口号
args: NONE
return: (串口号列表: ['COM1', ...], 串口名列表: ['通信端口 (COM1)'], 串口列表: ['COM1 - 通信端口 (COM1)', ...])
"""
while(True):
port_list = list(serial.tools.list_ports.comports())
if set(port_list) != set(self.port_list_orignal):
self.port_listUpdate(port_list)
if len(port_list) == 0:
print('No serial port found!')
exit()
else:
self.comUpdate.emit(port_list)
def port_listUpdate(self, port_list):
self.port_list_orignal = port_list
2 打开串口
def serialOpen(com, bps, timex):
"""打开串口
args: com: 串口号; bps: 波特率; timex: 超时时间
return: ser: 串口对象
"""
try:
ser = serial.Serial(com, int(bps), timeout=int(timex))
if ser.isOpen():
print('open success')
return ser
else:
print('open failed')
return None
except:
print("serialOpen: 串口不存在")
return
finally:
...
3 串口数据读取
class serialRead_original(QThread):
dateReadUpdate = pyqtSignal(str)
serDisconnect = pyqtSignal()
def run(self):
"""读取串口数据
args: NONE
return: NONE
"""
print("serialRead start")
ser.flushInput()
while(isConnected):
if serialIsOpen(ser) == False:
print("serialRead stop")
self.serDisconnect.emit()
serialClose(ser)
break
count = ser.inWaiting()
if count != 0:
str = ser.readline(ser.in_waiting)
self.dateReadUpdate.emit(str)
sleep(1)