Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 374
Marc Avatar asked Aug 24 '26 00:08

Marc


1 Answers

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.

like image 82
Marc Avatar answered Aug 26 '26 15:08

Marc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!