龙溪网站建设哪家便宜/营销广告文案
PC安装方式:pip install pyserial
导入:import serial
实例化串口:如果不存在该com口的话,会创建失败
如果重复打开这个com口的话也会报错
self.ser = serial.Serial(port=self.Com, baudrate=self.BaudRate, bytesize=self.DataBits, parity=self.Parity,stopbits=self.StopBits, timeout=None)
所以需要使用try
打开串口与关闭串口:
self.ser.open()
self.ser.close()
同样需要注意不要重复打开这个串口,因为打开之后如果没有关闭的话,也是会出错的,
发送信息:
(在串口中写)
self.ser.write(self.sendString.encode('utf-8'))
(接收数据)
data = self.ser.read(count).decode(encoding='utf-8')
class serialClass(object):def __init__(self,Com,BaudList,ParityList,DataBits,StopBits):self.Com = Comself.BaudRate = BaudList[0]self.Parity = ParityList[0]self.DataBits = DataBitsself.StopBits = StopBitsself.sendString = 'test RS485'self.numSend = 0self.uartState = False#self.serialOpen()def serialOpen(self):# 配置串口,尝试打开串口try:self.ser = serial.Serial(port=self.Com, baudrate=self.BaudRate, bytesize=self.DataBits, parity=self.Parity,stopbits=self.StopBits, timeout=None)except Exception as e:print(2,e)if not self.ser.isOpen():try:self.ser.open()#self.uartState = Trueexcept Exception as e:self.ser.close()print('2', e)#self.ser.uartState = Truedef serialWrite(self,):# 发送20次统计收发成功率while self.ser.isOpen():try:self.ser.write(self.sendString.encode('utf-8'))time.sleep(0.1)print('write is:',self.sendString)self.numSend += 1except Exception as e:print(e)if self.ser.isOpen() != True:print("can't open the port",self.Com)if self.numSend >= 20:#self.numSend = 0print('send 20 data')breaktime.sleep(2)self.numSend += 1def serialRead(self):# 有可能与串口测试部分冲突,需要将此设置为最高级别while True:# 读是一直读,写是有限次if (self.numSend<=20):#time.sleep()count = self.ser.inWaiting()if count > 0:try:data = self.ser.read(count).decode(encoding='utf-8')print("receive is:", data, end='')except Exception as e:print(e)self.uartState = Falseelse:breakdef autoTest(self):#启动写线程 启动读线程for BaudRate in BaudList:for Parity in ParityList:print(BaudRate, Parity)self.BaudRate = BaudRateself.Parity = Parityself.serialOpen()self.WriteThread = threading.Thread(target=self.serialWrite)self.WriteThread.start()self.ReadThread = threading.Thread(target=self.serialRead)self.ReadThread.start()self.WriteThread.join()self.ReadThread.join()#join 很重要,因为需要在写之后将串口关闭,再将串口配置成另外一个类型,需要在这个期间只有读写不再开启新的线程,在这两个线程结束之后关闭串口和配置与开启新的串口self.ser.close()self.numSend = 0Com = 'com3'
BaudList = [1200,4800,9600,19200,38400,57600,115200]
#ParityList = ['NONE','ODD','EVEN']
ParityList = [serial.PARITY_NONE,serial.PARITY_ODD,serial.PARITY_EVEN]
DataBits = serial.EIGHTBITS
StopBits = serial.STOPBITS_ONE
#parity=serial.PARITY_NONE
RS485_1 = serialClass(Com=Com,BaudList=BaudList,ParityList=ParityList,DataBits=DataBits,StopBits=StopBits)
RS485_1.autoTest()
在代码中,主要的操作就是对串口的几个操作,以及多线程的使用,这点很重要
这就是今天下午的劳动成果