Python serial communication module PySerial usage tutorial (CH340 USB TTL adapter chip)

1. Introduction to CH340 USB TTL

TTL is generally the level sent from the microcontroller or chip. The high level is 5V (51 microcontroller) or 3.3V (STM32). The function of the USB to TTL module is to convert the level to a level that both parties can recognize for communication.

The level logic of the microcontroller communication interface is different from that of the PC communication interface. The communication interface on the PC has a USB interface, and the corresponding level logic follows USB principles; there is also a DB9 interface (nine-pin port), and the corresponding level logic follows RS-232 principles.

The serial communication on the microcontroller passes through the four pins of RXD, TXD, VCC and GND of the microcontroller, and the corresponding level logic follows the TTL principle.

USB is a serial port (serial port is a large class of interfaces, including but not limited to RS232). It has a complex communication protocol, supports hot plugging, and can transmit data at very fast speeds. Serial port refers to RS232 serial port, which is a transmission interface with almost no protocol and can directly send and receive data.

The USB to TTL serial port module is a very practical tool that can test the UART serial port communication of the module and download programs to the microcontroller through the UART interface of the microcontroller. The serial port assistant software on the computer can very intuitively display the data returned by the serial port device and send the corresponding control data to the serial port device. Common USB to serial port modules include CP2102, PL2303, FT232, CH340 and other serial port chip solutions. The following takes the CH340 serial port module as an example to perform a self-test on it.

  • Working principle of serial port sending: 串口应用发送数据 -> USB 串口驱动获取数据 -> 驱动将数据经过 USB 通道发送给 USB 串口设备 -> USB 串口设备接收到数据通过串口发送;
  • Working principle of serial port reception: USB 串口设备接收串口数据 -> 将串口数据经过 USB 打包后上传给 USB 主机 -> USB 串口驱动获取到通过 USB 上传的串口数据 -> 驱动将数据保存在串口缓冲区提供给串口应用读取.

We open the serial port debugging tool, short-circuit the and pins of the CH340 USB TTL module (connect them together with the same line, which is equivalent to sending information to ourselves), then plug it into the computer, open the device manager, and ensure that the computer has recognized TXDit . RXDPort ( USB-SERIAL CH340 (COM4)), note that COM4the following number may be random, not necessarily this port.

Try to send a message to yourself, select the set serial port, open the serial port, enter and send the text, and check whether it is received, or whether the received characters are consistent. If you can send and receive data by yourself, and the sent and received data are consistent, it means the driver configuration Complete, and the module is fully functional:

Insert image description here

Precautions:

  • When the CH340 module is plugged into the USB2.0 port, the 5V pin output current is only about 500MA. If you want to connect a large module with relatively high power, it is recommended to connect USB3.0 or connect the high-power module to a separate external power supply and share the ground;
  • Do not short-circuit with , otherwise the module will be burned. If you find that the module light does not light up or the module is extremely hot after plugging in, please unplug it immediately and check whether it is reversely connected or short-circuited VCC.GND

2. PySerial Tutorial

Serial communication refers to a communication method that transmits data bit by bit between peripherals and computers through data signal lines, ground lines, control lines, etc. This communication method uses fewer data lines and can save communication costs in long-distance communication, but its transmission speed is lower than parallel transmission. The serial port is a very common device communication protocol on computers.

The PySerial module encapsulates Python's access to the serial port and provides a unified interface for use on multiple platforms. It supports multiple platforms such as Windows, Linux, OSX, BSD, etc. If you want to use the PySerial module, you must first ensure that the Python version is higher than Python 2.7 or Python 3.4. In addition, if you are using a Windows system, you must use Win7 and above.

First we install PySerial:

pip install pyserial

(1) Determine whether the computer has an available serial port and determine the serial port number of the available serial port.

import serial
import serial.tools.list_ports

ports_list = list(serial.tools.list_ports.comports())  # 获取所有串口设备实例
if len(ports_list) <= 0:
    print("无可用的串口设备!")
else:
    print("可用的串口设备如下:")
    for port in ports_list:  # 依次输出每个设备对应的串口号和描述信息
        print(list(port)[0], list(port)[1])  # COM4 USB-SERIAL CH340 (COM4)

(2) Open and close the serial port

serial.SerialThe parameters are as follows:

  • port: Serial port name ( COMnor /dev/ttyUSB) or None;
  • baudrate (int): Baud rate, such as 9600 or 115200;
  • bytesize: Number of data digits. Possible parameter values ​​are: FIVEBITS, SIXBITS, SEVENBITS, EIGHTBITS;
  • parity: Parity check, possible parameter values: PARITY_NONE, PARITY_EVEN, PARITY_ODD, PARITY_MARK, PARITY_SPACE;
  • stopbits: The number of stop bits, possible parameter values: STOPBITS_ONE, STOPBITS_ONE_POINT_FIVE, STOPBITS_TWO;
  • timeout (float): Set the maximum time for PySerial to continue reading data (unit: seconds);
  • xonxoff (bool): Whether to enable software flow control;
  • rtscts (bool): Whether to enable hardware (RTS/CTS) flow control;
  • dsrdtr (bool): Whether to enable hardware (DSR/DTR) flow control;
  • write_timeout (float): Set the longest time for PySerial to write serial port data (unit: seconds);
  • inter_byte_timeout (float): Timeout between characters, if not, it is disabled (disabled by default);
  • exclusive (bool): Set exclusive access mode (POSIX only). If the port is already open in exclusive access mode, you cannot open the port in exclusive access mode.

The exception return value is as follows:

  • ValueError: If some parameters are not within the allowed parameters, it will be returned ValueError, such as baud rate setting;
  • SerialException: Returned if the device cannot be found or set SerialException.
ser = serial.Serial("COM4", 115200)  # 打开COM4,将波特率配置为115200,其余参数使用默认值
if ser.isOpen():  # 判断串口是否成功打开
    print("串口成功打开")
    print(ser.name)  # 输出串口号,即COM4
else:
    print("串口打开失败")

ser.close()  # 关闭串口
if ser.isOpen():  # 判断串口是否关闭
    print("串口未关闭")
else:
    print("串口已关闭")

(3) Sending and receiving data

Note: timeoutThe parameters will affect read()the use of the function. This timeoutparameter is very important and directly affects our reading of serial port data.

  • timeout = None: Wait until the set number of received bytes is reached and then exit;
  • timeout = 0: Non-blocking mode, returns immediately in any case, returns zero or more, up to the requested number of bytes;
  • timeout = xtimeout: Set to xseconds (floating allowed) to return immediately when the requested number of bytes are available , otherwise wait for the timeout to expire and return all bytes received before then.
# 打开COM4,将波特率配置为115200,读超时时间为1秒
ser = serial.Serial(port="COM4", baudrate=115200, timeout=1)

# 串口发送数据ABC123,并输出发送的字节数
write_len = ser.write("ABC123".encode('utf-8'))  # 可以指定encode
print(f"串口共发出{
      
      write_len}个字节")  # 串口共发出6个字节

while True:
    com_input = ser.read(10)  # 每次读10字节的数据,可以指定decode:ser.read().decode()
    if com_input:   # 如果读取结果非空,则输出
        print(com_input)  # b'ABC123'
        print(com_input.decode('utf-8'))  # ABC123
    else:
        break

ser.close()

(4) Actual test of transferring file data

with open('../images/sonar_images/seg_height15_txt_01(compressed)/20210108_142207_01_XTF/8_15height.lz', 'rb') as f:  # 可以用编码'ISO-8859-1'
    file = f.read()
    print(file)

    ser = serial.Serial(port="COM4", baudrate=115200, timeout=1)
    write_len = ser.write(file)
    print(f"串口共发出{
      
      write_len}个字节")

    print(ser.in_waiting)  # input buffer中缓存字节数
    while True:
        com_input = ser.read(write_len)  # 读取所有字节
        if com_input:  # 如果读取结果非空,则输出
            print(com_input)
        else:
            break

    ser.close()

Guess you like

Origin blog.csdn.net/m0_51755720/article/details/132789900