pyserial只在1个线程上刷新

时间:2015-11-03 10:56:51

标签: multithreading pyserial serial-communication

我在每个端口上有2个虚拟COM端口和一个客户端。该连接适用于阅读。但它只写在其中一个线程上。例如:当我在write_thread上写入时,它将它发送到串口并将其打印到控制台。但是在连接的客户端上,它只显示write_worker从read_worker收到响应时的输出。 有什么帮助吗?

import serial
import time
import threading

def read_worker():
    """"constantly reads and responds back"""
    while True:
        read_text = ser.readline()
        read = read_text.decode("utf-8")
        print(read)

        response = "response to: " + read
        ser.write(response.encode())
        ser.flush()
        print(response)
        time.sleep(.1)

def write_worker():
    """Constantly writes to see if it can"""
    i = 0
    while True:
        i += 1

        response = "Writing: " + str(i)
        ser.write(response.encode())
        print(response)
        time.sleep(2)


ser = serial.Serial(
    port="COM1",
    baudrate=115200,
    bytesize=serial.EIGHTBITS,
    stopbits=serial.STOPBITS_ONE,
    rtscts=True)

threading.Thread(target=read_worker).start()
threading.Thread(target=write_worker).start()

1 个答案:

答案 0 :(得分:0)

更新回答

有时缓冲区仅在收到换行符时刷新,因此我会尝试更改

response = "Writing: " + str(i)

response = "Writing: " + str(i) + "\r\n"

仍然有效,但不是问题

串口只能打开一次。您现在正在向COM1发送字节,因此无法在另一个线程中打开相同的COM1并读取这些字节。

您的设置应如下所示:

COM1 ==虚拟零调制解调器(!重要的是必须越过tx / rx对)== COM2

然后,您可以例如写入COM1并在COM2上读取结果。

相关问题