如何使用 PySerial 从 COM 端口读写?

问题描述 投票:0回答:2

我安装了 Python 3.6.1 和 PySerial。我可以获得已连接的 COM 端口列表。我想向 COM 端口发送数据并接收响应:

import serial.tools.list_ports as port_list
ports = list(port_list.comports())
for p in ports:
    print (p)

输出:

COM7 - 多产 USB 转串行通信端口 (COM7)
COM1 - 通讯端口 (COM1)

来自 PySerial 文档

>>> import serial
>>> ser = serial.Serial('/dev/ttyUSB0')  # open serial port
>>> print(ser.name)         # check which port was really used
>>> ser.write(b'hello')     # write a string
>>> ser.close()             # close port

我从

ser = serial.Serial('/dev/ttyUSB0')
收到错误,因为“/dev/ttyUSB0”在 Windows 中没有意义。我可以在 Windows 中做什么?

python windows pyserial
2个回答
17
投票

可能就是你想要的。我会看一下有关写作的文档。 在 Windows 中,使用 COM1 和 COM2 等,而不使用 /dev/tty/,因为这适用于基于 UNIX 的系统。读取时只需使用 s.read() 等待数据,写入时使用 s.write()。

import serial

s = serial.Serial('COM7')
res = s.read()
print(res)

如果发送的是整数值,您可能需要解码以获取整数值。


12
投票

在Windows上,您需要通过运行来安装pyserial

pip install pyserial

那么你的代码就是

import serial
import time

serialPort = serial.Serial(
    port="COM4", baudrate=9600, bytesize=8, timeout=2, stopbits=serial.STOPBITS_ONE
)
serialString = ""  # Used to hold data coming over UART
while 1:
    # Wait until there is data waiting in the serial buffer
    if serialPort.in_waiting > 0:

        # Read data out of the buffer until a carraige return / new line is found
        serialString = serialPort.readline()

        # Print the contents of the serial data
        try:
            print(serialString.decode("Ascii"))
        except:
            pass

使用以下方法向端口写入数据

serialPort.write(b"Hi How are you \r\n")

注意:b"" 表示您正在发送字节

© www.soinside.com 2019 - 2024. All rights reserved.