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 = Com
self.BaudRate = BaudList[0]
self.Parity = ParityList[0]
self.DataBits = DataBits
self.StopBits = StopBits
self.sendString = 'test RS485'
self.numSend = 0
self.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 = True
except Exception as e:
self.ser.close()
print('2', e)
#self.ser.uartState = True
def 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 += 1
except Exception as e:
print(e)
if self.ser.isOpen() != True:
print("can't open the port",self.Com)
if self.numSend >= 20:
#self.numSend = 0
print('send 20 data')
break
time.sleep(2)
self.numSend += 1
def 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 = False
else:
break
def autoTest(self):
#启动写线程 启动读线程
for BaudRate in BaudList:
for Parity in ParityList:
print(BaudRate, Parity)
self.BaudRate = BaudRate
self.Parity = Parity
self.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 = 0
Com = '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()
在代码中,主要的操作就是对串口的几个操作,以及多线程的使用,这点很重要
这就是今天下午的劳动成果