【发布时间】:2022-08-03 01:52:12
【问题描述】:
是否可以在一个 python 文件中写入然后读取相同的串行端口?或者有2个不同的线程?我已经尝试过两种方式。使用 2 个不同的线程,我得到“拒绝访问”。在同一个文件中,我写了,它显示了我写的#bytes,但是当我读的时候,我得到了 0 个字节。消息在被读取之前是否存储在缓冲区中?这是我从同一个文件中尝试的代码:
# rwSerialPort.py
import sys, time
import serial.tools.list_ports as portlist
import serial
ports = list( portlist.comports() )
for p in ports:
print(p)
# This will hold received UART data
data = \"\"
stopMessage = \"STOP\\n\"
messages = [\"This is the first message sent to the Serial Port\\n\",
\"This is the second message sent to the Serial Port\\n\",
\"This is the third message sent to the Serial Port\\n\",
\"STOP\\n\"]
# Set up serial port for read
serialPort = serial.Serial( port=\"COM3\", baudrate=9600, bytesize=8, timeout=2, stopbits=serial.STOPBITS_ONE )
print( \'Starting Serial Port Send\' )
for msg in messages:
serialPort.write( msg.encode() )
print(\'Sent Serial Port: \', msg, \' #bytes: \', len(msg) )
time.sleep(.5)
serialPort.rts = False
serialPort.dtr = False
data = serialPort.readline()
#data = serialPort.read(size=50)
print(\'Serial Port Received #bytes: \', len(data) )
print( data.decode() )
print( \'Finished sending messages, now read them\' )
while True:
if serialPort.in_waiting > 0:
# Read data until hit a carriage return / new line
data = serialPort.readline()
try:
print(\'Serial Port Received #bytes: \', len(data) )
print( data.decode(\"ASCII\") )
if data.decode(\"ASCII\") == stopMessage:
print(\'Closing Serial Port\')
serialPort.close()
break
except:
print(\'Unable to print received serial data\')
print(\'Closing Serial Port Send\')
serialPort.close()
if __name__ == \'__main__\':
rwSerialPort()
我已经尝试过 readline() 和 read(size=#)。我没有得到任何回报。第一次读/写后的循环是我最初用来读回的。没有任何效果。我在一台只有一个串行端口 COM3 的 Windows 10 笔记本电脑上。不能先写再读吗?我没有连接到任何硬件。我用谷歌搜索和搜索,但没有找到答案。谢谢你的帮助!
标签: python windows pyserial read-write