ser = serial.Serial(‘COM3’)
上句是最简单的打开串口,打开串口3,波特率9600
完整的参数列表如下,可以根据自己需求添加传入参数:
def __init__(self,
port=None, # 串口号
baudrate=9600, # 波特率
bytesize=EIGHTBITS, # 字节数
parity=PARITY_NONE,
stopbits=STOPBITS_ONE, # 停止位
timeout=None, # 超时等待时间
xonxoff=False,
rtscts=False,
write_timeout=None,
dsrdtr=False,
inter_byte_timeout=None,
exclusive=None,
**kwargs):
可设置的波特率
BAUDRATES = (50, 75, 110, 134, 150, 200, 300, 600, 1200, 1800, 2400, 4800, 9600, 19200, 38400, 57600, 115200)
ser.close()
ser.write()
通过串口写数据
注意:读取到的数据是bytes而不是string
读取n字节的数据
读取函数原型
def read(self, size=1):
读取所有已在缓存区的数据
知道读取到特定的字符或者一定的字节才结束读取,
LF表示换行 等同’\n’
size表示读取到多少字符就停止
ser = serial.Serial('COM3', 115200, timeout=2)
ser.write('Hello World!'.encode('gbk'))
recv_data = ser.read_all()
recv_data = str(recv_data, encoding="gbk")
print(recv_data)
主要是简单整合了一下自己用到的功能,方便以后再次使用,
# 本函数主要是实现的功能:
# 适用于可使用串口的自动测试场景,通过串口发送和接收处理数据
import serial
import time
class TestSerial():
# ser:serial port name 串口号
# rate:serial rate 串口波特率
# timeout:wait time when serial no response 连接等待时间
def __init__(self,ser,rate,timeout=0):
self.ser = ser
self.rate = rate
self.timeout = timeout
# close serial port 关闭串口
def __del__(self):
self.ser.close()
# open serial 打开串口
def open_serial(self):
try:
self.ser = serial.Serial(self.ser, self.rate, timeout=self.timeout)
except SerialException:
print('Please check your Serial port, it is not availbe')
raise
except Exception as e:
print('Open serial err;',e)
raise
# read a data by ser 单纯读取数据
def read_data(self):
data = self.ser.read_all()
if data == b'':
return None
else:
data = str(data, encoding="gbk")
return data
# read a data by ser
# read_data_handle is callback function
# 读取数据同时处理数据,通过handle传入处理数据的函数,
# 传入函数只有一个string类型传入参数,返回类型自定
def read_data_handle(self, handle):
data = self.ser.read_all()
if data == b'':
print('recvive nothing')
return None
else:
data = str(data, encoding="gbk")
try:
data = handle(data)
except Exception as e:
data = 'ErrorValue'
print('Err:handle(data)', e)
finally:
return data
# write a data by serial
# wait sleep_time sec when write a data finished
# 写数据,写完成等待sleep_time时间
def write_data(self, data, sleep_time=0):
if isinstance(data, str):
self.ser.write(data.encode('gbk'))
if sleep_time != 0:
time.sleep(sleep_time)
else:
print('write err :data must be a string variate')
# This is a callback function for deal with recvive data from serial
# 例:处理数据函数,
def handle(data):
return 'handle data'
if __name__ == '__main__':
test = TestSerial('COM5')
test.open_serial()
test.write_data('FETCh?\n', 0.5)
print(test.read_data_handle(handle))