SoFunction
Updated on 2025-03-10

Implementation example of serial port operation in Python

introduce

The serial communication function based on Python is mainly usedpyseriallibrary to implement.pyserialIt is a cross-platform Python library that provides support for reading and writing operations on serial ports (such as RS232, USB to serial ports, etc.). Here is a detailed description of how to use itpyserialto conduct serial communication.

Install PySerial

First, install itpyserialLibrary can be easily completed through the pip tool:

pip install pyserial

Basic concepts

  • Baud Rate: Indicates the number of data bits transmitted per second, which is an important parameter in serial communication. It is necessary to ensure that the sending and receiving ends set the same baud rate.

  • Data Bits: Usually 7 or 8 bits, referring to the amount of data transmitted each time.

  • Stop Bits: Used to identify the number of ends of one byte, by default, 1 stop bit.

  • Parity Bit: Optional parameters to detect transmission errors, there are three options: calibration, odd check and even check.

  • Flow Control: Hardware flow control (RTS/CTS, DTR/DSR) or software flow control (XON/XOFF), used to manage data flow.

Basic steps to using PySerial

  • Import module

    • import serial
    • from import list_ports
  • Find available serial ports

    • Availablelist_ports.comports()Function lists all available serial devices in the system.
  • Open the serial port connection

    • use()Create a serial port object and specify the corresponding parameters (such as port number, baud rate, etc.).
  • Configure serial port parameters

    • When creating a serial port object, you can pass additional keyword parameters to set baud rate, data bit, stop bit, check bit, etc.
  • Read and write data

    • By calling the serial port objectread()write()Method to read and send data.
  • Close the serial port connection

    • When the serial port is no longer needed, it should be calledclose()Method to free resources.

Serial communication service implementation

This code shows how to use itpyserialLibrary to manage and operate serial ports, including listing available serial ports, opening and closing ports, sending and receiving data. The following is a detailed functional analysis:

Environmental preparation

Make sure it is installedpyseriallibrary to be able to access and manage serial ports.

pip install pyserial

List all serial ports

list_portsThe function is used to scan all serial ports in the system and return a list of these port names. It also records the description information and hardware ID of each port, making it easier for debugging or user to select the correct port.

def list_ports():
    port_names = []
    ports = .list_ports.comports()
    for port, desc, hwid in ports:
        log_message(f"Port: {port}, Description: {desc}, HWID: {hwid}")
        port_names.append(port)
    return port_names

Serial Communication Service Class (CommService)

Defines a service class for serial communicationCommService, and a function that lists all available serial portslist_ports. It uses PythonserialLibrary to handle serial communication and introduces some auxiliary modules to enhance functionality

Import module

Dark version

import serial
import binascii
import .list_ports
from utils.const_util import AppConst
  • serial: Provides access to serial ports (such as RS232, USB to string, etc.).
  • binascii: Contains a function that converts binary data into an ASCII string.
  • .list_ports: Provide tool functions to enumerate serial ports on the system.
  • utils.const_util.AppConst: Application constants defined in custom modules.

List all available serial ports

Dark version

def list_ports():
    port_names = []
    ports = .list_ports.comports()
    for port, desc, hwid in ports:
        print(f"Port: {port}, Description: {desc}, HWID: {hwid}")
        port_names.append(port)

    return port_names
  • list_portsfunction: Iterate through all available serial ports and print the name, description, and hardware ID of each port.
  • Returns a list of all port names that can be used to select specific communication ports.

Serial communication service category

Dark version

class CommService:
    def __init__(self, comm_port):
        self.comm_port = comm_port
        self.ser_comm = None
  • Construction method__init__: Set the serial port name during initialization and initialize the actual serial connection object toNone

Setting up the serial port

    def set_comm_port(self, comm_port):
        self.comm_port = comm_port
  • set_comm_portmethod: Allow dynamic changes to the serial port name.

Open a serial connection

    def open_comm(self):
        try:
            self.ser_comm = (self.comm_port, 9600, bytesize=, parity=serial.PARITY_NONE,
                                          stopbits=serial.STOPBITS_ONE, timeout=1, xonxoff=False, rtscts=False,
                                          dsrdtr=False)
        except:
            return None
        return self.ser_comm
  • open_commmethod: Try to open the specified serial port and configure baud rate, byte size, check bit, stop bit and other parameters.
  • If the opening fails (e.g. the port does not exist or has been occupied), catch the exception and returnNone; Otherwise, return the open serial connection object.

Close the serial connection

    def close_comm(self):
        if self.is_opened:
            self.ser_comm.close()
            self.ser_comm = None
  • close_commmethod: Check if the serial connection is open, if so, close the connection and reset the connection object toNone

Send data

    def send_comm(self, data):
        if self.is_opened:
            try:
                self.ser_comm.write(((' ', '')))
            except :
                msg = AppConst.COMM_SEND_OVER
                return False, msg
            return True, ''
        else:
            msg = AppConst.COMM_SEND_FAILED
            return False, msg
  • send_commmethod: If the serial connection is open, try to send data in hexadecimal format.
  • use()Convert the hexadecimal string to a byte array and send it.
  • Catches possible timeout exceptions and returns the corresponding error message.
  • Return after successful sendingTrueIf the message is empty, if the sending fails, it will be returned.Falseand error messages.

Read data

    def read_comm(self):
        if self.is_opened:
            if self.ser_comm.in_waiting > 0:
                try:
                    data = self.ser_comm.readline()
                except:
                    return None
                return (data).decode('ascii')
            return None
        else:
            return None
  • read_commmethod: If the serial connection is open and there is data to be read, try to read a row of data.
  • use()Converts the read data into a hexadecimal representation and decodes it into an ASCII string.
  • If an exception occurs or there is no data to read, returnNone

Check connection status

    def is_opened(self):
        return self.ser_comm is not None and self.ser_comm.is_open
  • is_openedmethod: Check whether there is currently a valid serial connection object and whether the connection is open.

Summarize

CommServiceThe class encapsulates all the basic operations required to communicate with a serial device, including opening/closing a connection, sending/receiving data, and checking the connection status. It also provides a static methodlist_portsTo list all serial ports on the system, this is useful when users need to select specific ports for communication. In addition, by usingtry-exceptStatements and code implement simple error handling logic to ensure that the basic operation of the program can be maintained even in the event of problems. Finally, useAppConstConstants in this article enable centralized management of error messages, easy maintenance and international support.

Complete code

import serial
import binascii
import .list_ports
from utils.const_util import AppConst


def list_ports():
    port_names = []
    ports = .list_ports.comports()
    for port, desc, hwid in ports:
        print(f"Port: {port}, Description: {desc}, HWID: {hwid}")
        port_names.append(port)

    return port_names


class CommService:
    def __init__(self, comm_port):
        self.comm_port = comm_port
        self.ser_comm = None

    def set_comm_port(self, comm_port):
        self.comm_port = comm_port

    def open_comm(self):
        try:
            self.ser_comm = (self.comm_port, 9600, bytesize=, parity=serial.PARITY_NONE,
                                          stopbits=serial.STOPBITS_ONE, timeout=1, xonxoff=False, rtscts=False,
                                          dsrdtr=False)
        except:
            return None
        return self.ser_comm

    def close_comm(self):
        if self.is_opened:
            self.ser_comm.close()
            self.ser_comm = None

    def send_comm(self, data):
        if self.is_opened:
            try:
                self.ser_comm.write(((' ', '')))
            except :
                msg = AppConst.COMM_SEND_OVER
                return False, msg
            return True, ''
        else:
            msg = AppConst.COMM_SEND_FAILED
            return False, msg

    def read_comm(self):
        if self.is_opened:
            if self.ser_comm.in_waiting > 0:
                try:
                    data = self.ser_comm.readline()
                except:
                    return None
                return (data).decode('ascii')

            return None
        else:
            return None

    def is_opened(self):
        return self.ser_comm is not None and self.ser_comm.is_open

Example of usage

The following is a simple usage example, assuming there is already an instantiated oneCommServiceObjectcomm_service

# List all available serial portsavailable_ports = list_ports()

# Assume that the first available port is selected for communicationif available_ports:
    comm_service.set_comm_port(available_ports[0])
    ser = comm_service.open_comm()
    if ser:
        # Send some data to the serial port        success, msg = comm_service.send_comm("55 AA 01 02 03")
        if success:
            print("Data sent successfully.")
        else:
            print(f"Failed to send data: {msg}")

        # Try to read data from the serial port        received_data = comm_service.read_comm()
        if received_data:
            print(f"Received data: {received_data}")

        # Close the serial port        comm_service.close_comm()
else:
    print("No available serial ports found.")

This way, you can easily interact with any serial device connected to your computer, whether reading sensor data or controlling external hardware.

This is the end of this article about the implementation example of serial port operation in Python. For more related Python serial port operation content, please search for my previous article or continue browsing the related articles below. I hope everyone will support me in the future!