简介
打开串口
打开“9600,8,N,1”的端口,没有超时:
>>> import serial
>>> ser = serial.Serial('/dev/ttyUSB0') # open serial port
>>> print(ser.name) # check which port was really used
>>> ser.write(b'hello') # write a string
>>> ser.close() # close port
打开命名端口“19200,8,N,1”,1s超时:
>>> with serial.Serial('/dev/ttyS1', 19200, timeout=1) as ser:
... x = ser.read() # read one byte
... s = ser.read(10) # read up to ten bytes (timeout)
... line = ser.readline() # read a '\n' terminated line
打开端口“38400,8,E,1”,非阻塞硬件握手:
>>> ser = serial.Serial('COM3', 38400, timeout=0,
... parity=serial.PARITY_EVEN, rtscts=1)
>>> s = ser.read(100) # read up to one hundred bytes
... # or as much is in the buffer
稍后配置端口
获取Serial实例并在以后配置/打开它:
>>> ser = serial.Serial()
>>> ser.baudrate = 19200
>>> ser.port = 'COM1'
>>> ser
Serial<id=0xa81c10, open=False>(port='COM1', baudrate=19200, bytesize=8, parity='N', stopbits=1, timeout=None, xonxoff=0, rtscts=0)
>>> ser.open()
>>> ser.is_open
True
>>> ser.close()
>>> ser.is_open
False
上下文管理器也支持:
with serial.Serial() as ser:
ser.baudrate = 19200
ser.port = 'COM1'
ser.open()
ser.write(b'hello')
读取
使用时要小心readline()
。在打开串口时指定超时,否则如果没有收到换行符,它可能永远阻塞。另请注意,readlines()
仅适用于超时。 readlines()
取决于超时并将其解释为EOF(文件结束)。如果端口未正确打开,则会引发异常。
还要查看源代码发布中的示例目录中的示例文件或联机。
注意
在eol
为参数readline()
,不再支持时pySerial与其中模块新Python版本(V2.6 +)运行 io
可用。
EOL
要指定EOL字符readline()
或使用通用换行模式,建议使用io.TextIOWrapper:
import serial
import io
ser = serial.serial_for_url('loop://', timeout=1)
sio = io.TextIOWrapper(io.BufferedRWPair(ser, ser))
sio.write(unicode("hello\n"))
sio.flush() # it is buffering. required to get the data out *now*
hello = sio.readline()
print(hello == unicode("hello\n"))
测试端口
列出端口
python -m serial.tools.list_ports
将打印可用端口列表。也可以添加regexp作为第一个参数,列表将只包含匹配的条目。
注意
枚举可能不适用于所有操作系统。它可能不完整,列出不可用的端口或可能缺少端口的详细描述。
访问端口
pySerial包含一个名为serial.tools.miniterm的基于控制台的小型终端程序 。它可以以 (使用选项获取所有选项的列表)开始。python -m serial.tools.miniterm <port_name>
-h