python通过com串口连接硬件
使用python是通过com串口连接硬件设备
注意点
1.首先安装serial库,可以运行pip insatll pyserial或在ide上安装
2.Serial()方法参数
Port:串口号;
Baudrate:波特率
Parity:奇偶校验位
Bytesize:数据位
3.由于串口使用的是字节,故而要进行转码,否则串口会不识别
此处贴核心代码:
import threading
import time
import serial
import logging
class ComThread:
def __init__(self, Port='COM3',Baudrate=115200,Parity=serial.PARITY_NONE,Bytesize=serial.EIGHTBITS):
# 构造串口的属性
self.l_serial = None
self.thread_read = None
self.alive = False
self.waitEnd = None
# 串口号
self.port = Port
# 波特率
self.baudrate = Baudrate
# 校验位
self.parity = Parity
# 数据位
self.bytesize = Bytesize
self.ID = None
self.data = None
self.device_name = ''
# 定义串口等待的函数
def waiting(self):
logging.debug("定义串口等待的函数")
if not self.waitEnd is None:
self.waitEnd.wait()
def SetStopEvent(self):
logging.debug("设置stop event")
if not self.waitEnd is None:
self.waitEnd.set()
self.alive = False
self.stop()
# 启动串口的函数
def start(self):
try:
logging.debug("启动串口的函数")
self.l_serial = serial.Serial()
self.l_serial.port = self.port
self.l_serial.baudrate = self.baudrate
self.l_serial.parity = self.parity
self.l_serial.bytesize = self.bytesize
# 设置等待时间,若超出这停止等待
logging.debug("设置等待时间,若超出这停止等待")
self.l_serial.timeout = 2
logging.debug('参数--串口:'+str(self.port)+',位/秒:'+str(self.baudrate)+',奇偶校验:'+str(self.parity)+',数据位:'+str(self.bytesize))
self.l_serial.open()
# 判断串口是否已经打开
logging.debug("判断串口是否已经打开:"+str(self.l_serial.isOpen()))
if self.l_serial.isOpen():
# 这里写自己的逻辑,我这里是开了一个线程监听串口读数据
self.waitEnd = threading.Event()
self.alive = True
self.thread_read = None
logging.debug("激活标志alive:" + str(self.alive))
self.thread_read = threading.Thread(target=self.FirstReader)
self.thread_read.setDaemon(True)
self.thread_read.start()
logging.debug("线程启动。。。")
return True
else:
return False
except Exception as e:
logging.debug(str(self.port)+"开启异常:"+str(e))
return False
# 发送数据
def SendDate(self,i_msg,send):
lmsg = ''
isOK = False
if isinstance(i_msg):
lmsg = i_msg.encode('gb18030')
else:
lmsg = i_msg
try:
# 发送数据到相应的处理组件
self.l_serial.write(send)
except Exception as ex:
pass;
return isOK
def FirstReader(self):
logging.debug(":数据监控开始。。。")
# num = 0
data = ''
bytes_data = ''.encode('utf-8')
try:
while self.alive:
time.sleep(0.2)
tmp_data = ''
tmp_data = tmp_data.encode('utf-8') # 由于串口使用的是字节,故而要进行转码,否则串口会不识别
n = self.l_serial.inWaiting() # 获取接收到的数据长度
if n == 0:
self.data = data
bytes_data = b''
data = ''
continue
logging.debug("获取接收到的数据长度:"+str(n))
if n:
# 读取数据并将数据存入data
# print(self.l_serial.read(n))
tmp_data = tmp_data + self.l_serial.read(n)
# 输出接收到的数据
logging.debug('get data from serial port:'+str(tmp_data))
# 显示data的类型,便于如果出错时检查错误
logging.debug('输出数据的数据类型:' + str(type(tmp_data)))
# 获取还没接收到的数据长度
n = self.l_serial.inWaiting()
# 判断是否已经将下位机传输过来的数据全部提取完毕,防止之前没有获取全部数据
logging.debug('获取还没接收到的数据长度:' + str(n))
bytes_data = bytes_data + tmp_data
data = data + str(tmp_data)
except Exception as e:
logging.debug('获取com数据异常:'+str(e))
self.waitEnd.set()
self.alive = False
def stop(self):
try:
self.alive = False
self.is_send = False
self.data = None
if self.thread_read is not None:
self.thread_read.join()
logging.debug(str(self.thread_read.ident) + '线程关闭。。。')
if self.l_serial is not None and self.l_serial.isOpen():
self.l_serial.close()
logging.debug(str(self.l_serial.port) + '串口关闭。。。')
except Exception as e:
logging.debug('关闭'+str(self.port)+'线程失败:'+str(e))
写得比较粗糙,望见谅

浙公网安备 33010602011771号