You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用pyserial无法从串口获取响应的问题求助

使用pyserial无法从串口获取响应的问题求助

我现在遇到一个串口通信的问题:我用两种方式尝试连接设备:

  • 方式1:Python的pyserial库
  • 方式2:PuTTY

用PuTTY的时候能正常连接设备并使用,但用Python脚本只能成功打开串口,却没法正常发送命令或者读取返回内容。

我已经确认Python脚本和PuTTY用的是完全一样的串口参数,但肯定哪里漏了配置,有没有人能帮我看看怎么修改脚本?

我的Python环境是Windows 11,代码如下:

import serial
import time


def send_command_to_com_port(ser, command):
    try:
        # Send the command
        command_encoded = command.encode('ascii')
        ser.write(command_encoded)
        print(command_encoded)

    except serial.SerialException as e:
        print(f"Error communicating with the COM port: {e}")


def read_from_com_port(ser):
    try:
        # Read response from the COM port
        response = ser.read_until("\n")  # Read until a newline character is encountered
        if response:
            print(f"Response received: {response.decode('ascii').strip()}")
        else:
            print("No response received from the COM port.")

    except serial.SerialException as e:
        print(f"Error communicating with the COM port: {e}")


# Specify the COM port and send the command
com_port = "COM4"

# Configure the serial connection
ser = serial.Serial(
    port=com_port,  # Replace with your COM port (e.g., 'COM3' on Windows or '/dev/ttyUSB0' on Linux)
    baudrate=115200,  # Baud rate
    bytesize=serial.EIGHTBITS,  # 8 data bits
    parity=serial.PARITY_NONE,  # No parity bit
    stopbits=serial.STOPBITS_ONE,  # One stop bit
    timeout=1  # Timeout in seconds
)

# Ensure the COM port is open
print(f"Serial port opened: {ser.is_open}")

# Send commands to the COM port
send_command_to_com_port(ser, 'm0\n')
time.sleep(2)
read_from_com_port(ser)

# Close the serial port
ser.close()
print("Serial connection closed.")

运行脚本后,输出总是这样:

Serial port opened: True
b'm0\n'
No response received from the COM port.
Serial connection closed.

Process finished with exit code 0

补充说明:设备要求所有指令必须用ASCII编码,并且以换行符'\n'结尾。发送m0命令后应该能收到一个字符串确认,但我这边完全没返回。

备注:内容来源于stack exchange,提问作者mizix

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.14 10:54:50