与 Windows 读写同一串口

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

是否可以在一个Python文件中写入然后读取同一个串口?或者有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=#)。我没有得到任何回报。第一次读/写之后的循环是我最初用来读回的。什么都不起作用。我使用的是一台 Windows 10 笔记本电脑,只有一个串行端口 COM3。是不是不能先写再读?我没有连接到任何硬件。我用谷歌搜索了又搜索,但没有找到答案。感谢您的帮助!

python windows pyserial read-write
2个回答
3
投票

除非你在端口上插入了环回,否则你写入端口的所有数据都会发送到任何地方,环回插头将端口的 TX 连接到它的 RX,只有这样你才能看到你写出的数据.


0
投票

酷,将 arduino 插入 USB 端口后 我加 : 对于端口中的 p: 打印(页) if ((p[1][-3]).isnumeric()): portCOM=“COM”+p[1][-3]+p[1][-2] 别的: portCOM=“COM”+p[1][-2] 打印(端口COM) ... 串行端口=串行.串行(端口= portCOM,....

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