Python utility module (32) pyserial

surroundings

foreword

Serial port usage is an essential skill for embedded system development, and tools such as securecrt and putty are generally used to send and receive data. This article will introduce how to use the third-party library pyserial to perform serial data operations in the python environment.

Install

Install using pip , execute the command

 pip install pyserial

Example of use

First, connect the serial port cable and find the device in the Device Manager , such as my COM11 here, which will be used in the following code

In addition to the port number, we also need to set several other properties of the serial port, such as baud rate, data bit, parity bit, stop bit, DTR/DSR , RTS/CTS , XON/XOFF

After sorting this out, you can see the following code

 import serial if __name__ == '__main__': # 如果不清楚当前的串口设备, pyserial 也提供了相应的api import serial.tools.list_ports ports = list(serial.tools.list_ports.comports(include_links=False)) for port in ports: print(port) # 创建串口对象ser = serial.Serial(port="COM11", baudrate=115200, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, timeout=1, rtscts=False) # 判断串口是否打开if ser.isOpen(): print('open success.') # 发送数据,这里只支持bytes 类型的数据,需要对字符串进行encode 编码send_len = ser.write(b'usb start') print('send data length: {}'.format(send_len)) # 读取数据,读取的内容也是bytes 类型read_msg = ser.read(30) print('read_msg: {}'.format(read_msg)) else: print('open failed.') # 关闭串口ser.close()

For more information, please refer to the official documentation https://pyserial.readthedocs.io/en/latest/

Topics in Python Practical Modules

More useful python modules, please move

https://xugaoxiang.com/category/python/modules/

This article is reprinted from https://xugaoxiang.com/2022/07/19/python-module-32-pyserial/
This site is for inclusion only, and the copyright belongs to the original author.

Leave a Comment