准备
安装pyserial模块,即pip install pyserial
pyserial使用
导入模块 import serial
初始化 serial.Serial()
实例化一个串口对象
ser = serial.Serial(
port=None, # 串口名称
baudrate=9600, # 波特率
bytesize=EIGHTBITS, # 数据位
parity=PARITY_NONE, # 校验位
stopbits=STOPBITS_ONE, # 停止位
timeout=None, # 设置超时值, None永远等待、0不阻塞,立刻返回、某个值是会阻塞
xonxoff=0, # enable software flow control
rtscts=0, # enable RTS/CTS flow control
interCharTimeout=None # Inter-character timeout, None to disable
)
以上因串口不同设置值会有差异,例如我使用的串口板参数:baudrate=512000,bytesize=8,stopbits=1,特别注意:波特率值不要设置错误,否则一直乱码
串口名称可通过导入serial.tools.list_ports
模块,使用serial.tools.list_ports.comports()
获得所有串口
例如我设计的类部分代码,获取当前usb串口:
@property
def port(self):
return self.__port
@port.setter
def port(self,port):
if port:
self.__port=port
else:
for i in serial.tools.list_ports.comports():
if "USB-to-Serial" in i.description:
self.port=i.device
常见实例方法
改变已打开端口的参数,如
self.ser .baudrate =self.baudrate
self.ser .timeout = self.timeout
self.ser .bytesize=self.bytesize
获取实例对象的内容及状态等
open() # 打开端口
close() # 立即关闭端口
isOpen() #获取串口的状态
inWaiting() # 返回缓冲器字节的长度
write(s) # 把字符串s写到该端口
read(n) # 读取指定字节长度的字符串
flushInput() # 清除输入缓存区,放弃所有内容
flushOutput() # 清除输出缓冲区,放弃输出
sendBreak() # 发送中断条件
setRTS(level=1) # set RTS line to specified logic level
setDTR(level=1) # set DTR line to specified logic level
getCTS() # return the state of the CTS line
getDSR() # return the state of the DSR line
getRI() # return the state of the RI line
getCD() # return the state of the CD line
串口实例方法可参考:http://blog.csdn.net/dainiao01/article/details/5885122
网友评论