Search code examples
pythonpython-3.xpython-3.3pyserialloopback

How do I make the pyserial loopback work?


I'm trying to test a serial connection, prior to hooking up the external device that will actually source the data. I'm trying to use pySerial's "loop://" device, but I'm not receiving data correctly. I've started with a very toy program, just be sure I understood how/if it would work. Clearly I don't. :)

Here is my data "Source"

def serialDataPump():
    ser = serial.serial_for_url('loop://', timeout=1)
    testCtr = 0;
    while not bbq.closing and testCtr<10:
        ser.write(bytes("Test\n", encoding='ascii'))
        time.sleep(1)
        testCtr += 1

Here is my data "sink":

def serialDataTestRcv():
    ser = serial.serial_for_url('loop://', timeout=1)
    while not bbq.closing:
        line = ser.readline()
        sys.stdout.write('received' + str(line))

And here is my test Function - I use two threads:

def testSerMain():
    thread1 = Thread(target = serialDataPump)
    thread2 = Thread(target = serialDataTestRcv)
    thread1.start()
    thread2.start()
    thread1.join()
    bbq.closing = True
    time.sleep(2)
    exit()

And finally, here is the output - I am receiving the EOLs at a minimum, because readline() unblocks, and loops exactly 11 times, prior to terminating, which indicates that both the pump and the receive are looping and terminate properly. However, as you can see, it receives just empty data + the EOL:

>>> 
receivedb''receivedb''receivedb''receivedb''receivedb''receivedb''receivedb''receivedb''receivedb''receivedb''receivedb''
>>> 

Win 7, x64m py3.3

Incidentally, I know about com0com - I just can't run it on the machine I'm on.


Solution

  • I discovered the problem - you must use the same instance of ser = serial.serial_for_url('loop://', timeout=1) that you created for both receive and Xmt.