pyerial读写串口
错误:
AttributeError: module 'serial' has no attribute 'Serial'
1.自己写的文件命令成立serial.py,import serial 产生冲突
2.安装的serial包不对,应该安装pyserial包
ubuntu下查看串口:
dmesg | grep ttyS*
sudo chmod 666 /dev/ttyUSB0
具体使用可以参考官网:https://pythonhosted.org/pyserial/shortintro.html
1.查找所有串口:
import time import serial import serial.tools.list_ports import platform class getMCUVersion: def __init__(self): self.baudrate = 115200 self.locsys = platform.system() self.mcu_name = "" self.use_serial_list = [] def find_seral(self): comlist = serial.tools.list_ports.comports() # 为所有的串口分别生成ListPortInfo object,列表封装 # for i in range(len(comlist)): # print(comlist[i]) #打印串口详细信息 if self.locsys == "Linux": for element in comlist: if 'USB' in str(element): # print("使用{0}".format(element.device)) self.use_serial_list.append(element.device) elif self.locsys == "Windows": for element in comlist: if 'USB-to-Serial' in str(element): # print("使用{0}".format(element.device)) self.use_serial_list.append(element.device) return self.use_serial_list def get_version(self, ser, timeout=3): if ser == '': return "not serial cable, check MCU serial cable" lab_ver = 0 try: ser = serial.Serial(ser, self.baudrate, writeTimeout=0.5, timeout=0.01) start = time.time() while True: current = time.time() if current - start > timeout: break data = ser.readline() if 'FSD_A' in str(data) or 'ADMAX_A' in str(data): mcu_name = "MCU1_VER" break elif 'FSD_B' in str(data) or 'ADMAX_B' in str(data): mcu_name = "MCU2_VER" break count = ser.write(b"version\r") if count <= 0: print("输入指令长度小于等于0,请检查") return for i in range(20): data = ser.readline() if 'X01' in str(data): ver = str(data)[2:-5] if ver.find('\\x00') != -1: ver = ver[4:] if ver.find('\\r') != -1: ver = ver[2:] if ver.find('\r') != -1: ver = ver[1:] return mcu_name + ":" + ver else: lab_ver += 1 if lab_ver == 10: return ser.flush() ser.close() except Exception as e: pass return def get_swap(self, ser, timeout=3): if ser == '': return "not serial cable, check MCU serial cable" lab_swap = 0 try: ser = serial.Serial(ser, self.baudrate, writeTimeout=0.5, timeout=0.01) ser.flush() start = time.time() while True: current = time.time() if current - start > timeout: break data = ser.readline() if 'FSD_A' in str(data) or 'ADMAX_A' in str(data): mcu_name = "MCU1_SWAP" break elif 'FSD_B' in str(data) or 'ADMAX_B' in str(data): mcu_name = "MCU2_SWAP" break count = ser.write(b"getswap\r") if count <= 0: print("输入指令长度小于等于0,请检查") return -1 for i in range(20): data = ser.readline() if 'Swap' in str(data): swap = str(data)[2:-5] if swap.find('\\x00') != -1: swap = swap[4:] if swap.find('\\r') != -1: swap = swap[2:] if swap.find('\r') != -1: swap = swap[1:] return mcu_name + ":" + swap.strip('\r') else: lab_swap += 1 if lab_swap == 10: return ser.flush() ser.close() except Exception as e: pass return def test_one(self, ser): try: ser = serial.Serial(ser, self.baudrate, writeTimeout=0.5) ser.write(b"version\r") ser.write(b"getswap\r") ser.close() except Exception as e: if "Permission denied" in str(e): print('请给串口权限,执行命令:sudo chmod 777 ' + ser) return def run(self): serial_lst = self.find_seral() if len(serial_lst) < 2: return 0 rest = dict() loop = 10 while loop: print('< 第{}次读取串口 >'.format(11-loop)) for SER in serial_lst: self.test_one(SER) ver = self.get_version(SER) swap = self.get_swap(SER) if not ver or not swap: continue else: rest[ver.split(':')[0]] = ver.split(':')[1] rest[swap.split(':')[0]] = swap.split(':')[1] if len(rest) == 4: return rest loop = loop - 1 return rest if __name__ == '__main__': test = getMCUVersion() ret = test.run() if not ret: print('请检查MCU串口是否连接') exit(-1) print(ret['MCU1_VER']) print(ret['MCU1_SWAP']) print(ret['MCU2_VER']) print(ret['MCU2_SWAP']) time.sleep(3)
2.创建一个串口
ser = serial.Serial(ser, self.baudrate, writeTimeout=0.5, timeout=0.01)
3.写入数据
ser.write(b"version")
4.读取数据,如果串口有心跳,可以读取多行数据根据关键字查找
data = ser.readline()
5.刷新串口,关闭串口
ser.flush()
ser.close()