【问题标题】:Read and write to same serial port with Windows使用 Windows 读写同一个串口
【发布时间】: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


    【解决方案1】:

    除非您将环回插入端口,否则您写入端口的所有数据都发送到任何地方,环回插头将端口的 TX 连接到它的 RX,然后您才能看到您写出的数据。

    【讨论】:

    • 啊!谢谢!是的,我想我正在从端口写出到无处,然后从无处读取正在写入端口的任何内容。谢谢你的环回想法!!好消息是读取和写入似乎可以工作:)
    猜你喜欢
    • 1970-01-01
    • 2019-07-03
    • 1970-01-01
    • 1970-01-01
    • 2013-07-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多