杰瑞科技汇

Python import serial如何实现串口通信?

Of course! The import serial statement is the first step to using the PySerial library in Python, which is the standard library for serial communication.

Python import serial如何实现串口通信?-图1
(图片来源网络,侵删)

Here’s a complete guide covering what it is, how to install it, and how to use it with practical examples.


What is PySerial?

PySerial is a Python library that provides a straightforward way to communicate with devices connected to a serial port (also known as a COM port on Windows or /dev/tty* on Linux/macOS). This is essential for interacting with a wide range of hardware, such as:

  • Microcontrollers (Arduino, ESP32, Raspberry Pi Pico)
  • GPS modules
  • RFID readers
  • Modems
  • Various sensors and other serial-based devices.

Installation

Before you can import serial, you need to install the library. If you don't have it, open your terminal or command prompt and run:

pip install pyserial

The Basic Workflow

Using PySerial typically follows these steps:

Python import serial如何实现串口通信?-图2
(图片来源网络,侵删)
  1. Import the library: import serial
  2. Establish a connection: Create a Serial object, specifying the port and the baud rate.
  3. Read or Write Data: Use the object's methods (read(), write(), etc.) to send and receive data.
  4. Close the connection: When you're done, call the close() method to release the port.

Practical Examples

Let's look at the most common use cases.

Example 1: Sending Data to a Device (e.g., an Arduino)

This script opens a serial port and sends the text "Hello from Python!" followed by a newline character. The encode('utf-8') part converts the string into bytes, which is what serial communication requires.

import serial
import time
# --- Configuration ---
# Find your port in the Arduino IDE: Tools > Port
# On Linux: it might be '/dev/ttyUSB0' or '/dev/ttyACM0'
# On Windows: it might be 'COM3'
SERIAL_PORT = '/dev/ttyUSB0' 
BAUD_RATE = 9600
try:
    # 1. Establish the connection
    # The 'with' statement ensures the port is closed automatically
    with serial.Serial(SERIAL_PORT, BAUD_RATE, timeout=1) as ser:
        print(f"Connected to {ser.name} at {ser.baudrate} baud.")
        # 2. Write data (must be encoded to bytes)
        message = "Hello from Python!\n"
        ser.write(message.encode('utf-8'))
        print(f"Sent: {message.strip()}")
        # Wait a moment for the device to process the data
        time.sleep(1)
except serial.SerialException as e:
    print(f"Error: Could not open port {SERIAL_PORT}.")
    print("Please check the port name and ensure the device is connected.")
    print(f"Details: {e}")

Example 2: Reading Data from a Device (e.g., an Arduino)

This script opens a port and continuously reads data line by line as it becomes available. The timeout=1 is important; it makes the readline() method wait for up to 1 second for data. If no data arrives, it returns empty, preventing your script from getting stuck forever.

import serial
import time
# --- Configuration ---
SERIAL_PORT = '/dev/ttyUSB0'
BAUD_RATE = 9600
try:
    with serial.Serial(SERIAL_PORT, BAUD_RATE, timeout=1) as ser:
        print(f"Listening on {ser.name} at {ser.baudrate} baud. Press Ctrl+C to stop.")
        while True:
            # Check if data is available to read
            if ser.in_waiting > 0:
                # Read a line of data (reads until a newline character '\n')
                line = ser.readline()
                # Decode the bytes object to a string
                decoded_line = line.decode('utf-8').strip()
                if decoded_line: # Only print if the line is not empty
                    print(f"Received: {decoded_line}")
            # A small sleep to prevent the CPU from being overloaded
            time.sleep(0.1)
except serial.SerialException as e:
    print(f"Error: Could not open port {SERIAL_PORT}.")
    print("Please check the port name and ensure the device is connected.")
    print(f"Details: {e}")
except KeyboardInterrupt:
    print("\nProgram terminated by user.")

Finding Your Serial Port

If you don't know your port name, you can use a small script to list all available serial ports. PySerial provides a handy utility for this.

Python import serial如何实现串口通信?-图3
(图片来源网络,侵删)
import serial.tools.list_ports
# Get a list of all available ports
ports = serial.tools.list_ports.comports()
print("Available Serial Ports:")
if not ports:
    print("No serial ports found.")
else:
    for port in ports:
        # Each port object has useful attributes
        print(f"- Device: {port.device}")
        print(f"  - Description: {port.description}")
        print(f"  - HWID: {port.hwid}")
        print("-" * 20)

Output on a Linux machine with an Arduino connected:

Available Serial Ports:
- Device: /dev/ttyACM0
  - Description: USB Serial Device (ttyACM0)
  - HWID: USB VID:PID=2341:0043 SER=55786330313551 LOCATION=1-1.4
--------------------
- Device: /dev/ttyUSB0
  - Description: CP2102 USB to UART Bridge Controller
  - HWID: USB VID:PID=10C4:EA60 SER=0001 LOCATION=1-1.2
--------------------

Key Serial Object Attributes and Methods

Here are some of the most important properties and methods you'll use:

Attribute/Method Description
ser = serial.Serial(port, baudrate) The constructor to open a connection.
ser.name The name of the port (e.g., '/dev/ttyUSB0').
ser.baudrate The current baud rate.
ser.close() Closes the port.
ser.open() Opens a previously closed port.
ser.write(data) Writes data (must be a bytes object) to the port.
ser.read(size) Reads size number of bytes.
ser.readline() Reads until a newline character (\n) is found.
ser.in_waiting The number of bytes in the input buffer waiting to be read.
ser.timeout A float describing the read timeout in seconds. None is blocking, 0 is non-blocking.

Common Pitfalls and Best Practices

  1. Port Already in Use: You cannot open a serial port that is already open by another program (like the Arduino IDE or another Python script). Always close your connection with ser.close() or use the with statement.
  2. Permissions (Linux/macOS): On Linux, you might get a PermissionError if your user isn't in the dialout group. You can add your user with: sudo usermod -a -G dialout $USER (then log out and log back in).
  3. Data Encoding: Remember that ser.write() requires bytes. Use my_string.encode('utf-8') to convert a string. ser.read() and ser.readline() return bytes, which you should decode with my_bytes.decode('utf-8').
  4. Baud Rate Mismatch: The baud rate in your Python script must match the baud rate configured on the device you are communicating with (e.g., in your Arduino Serial.begin(9600);).
分享:
扫描分享到社交APP
上一篇
下一篇