如何使用 PySerial 从 COM 端口读取和写入?
How to read and write from a COM Port using PySerial?
我安装了 Python 3.6.1 和 PySerial。我正在尝试
我能够获取已连接的端口列表。我现在希望能够将数据发送到 COM 端口并接收返回的响应。我怎样才能做到这一点?我不确定下一步要尝试的命令。
代码:
import serial.tools.list_ports as port_list
ports = list(port_list.comports())
for p in ports:
print (p)
输出:
COM7 - Prolific USB-to-Serial Comm Port (COM7)
COM1 - Communications Port (COM1)
我从PySerial Documentation看到打开COM端口的方法如下:
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
我在 Windows 上 运行,我收到以下行的错误:
ser = serial.Serial('/dev/ttyUSB0')
这是因为“/dev/ttyUSB0”在 Windows 中没有意义。我可以在 Windows 做什么?
可能是您想要的。我会看看有关写作的文档。
在 windows 中使用不带 /dev/tty/ 的 COM1 和 COM2 等,因为这是基于 unix 的系统。读取只需使用 s.read() 等待数据,写入使用 s.write().
import serial
s = serial.Serial('COM7')
res = s.read()
print(res)
如果发送的是整数,您可能需要解码才能获得整数值。
在 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""表示你正在发送字节
我安装了 Python 3.6.1 和 PySerial。我正在尝试
我能够获取已连接的端口列表。我现在希望能够将数据发送到 COM 端口并接收返回的响应。我怎样才能做到这一点?我不确定下一步要尝试的命令。
代码:
import serial.tools.list_ports as port_list
ports = list(port_list.comports())
for p in ports:
print (p)
输出:
COM7 - Prolific USB-to-Serial Comm Port (COM7)
COM1 - Communications Port (COM1)
我从PySerial Documentation看到打开COM端口的方法如下:
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
我在 Windows 上 运行,我收到以下行的错误:
ser = serial.Serial('/dev/ttyUSB0')
这是因为“/dev/ttyUSB0”在 Windows 中没有意义。我可以在 Windows 做什么?
import serial
s = serial.Serial('COM7')
res = s.read()
print(res)
如果发送的是整数,您可能需要解码才能获得整数值。
在 Windows 上,您需要通过 运行
安装 pyserialpip 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""表示你正在发送字节