简体   繁体   中英

python and serial port thread

I have gone through a few questions on this topic but I'm still having a problem getting it to work. I want to be able to launch a program which will monitor the serial port but will still let me send commands to the serial port. I found this question/topic to be very useful PySerial non-blocking read loop to answer my question but it's still not working. I'm trying to write a non blocking serial port read using threading and still be able to send a command like "fs ls" (file system list files). Below is my attempt. When I run this, I'm getting stuck inside the while True case. I was expecting threading to launch this and then move on. then when the 5 "fs ls" commands get run I'd see the command line response's in the std_out. Instead I get nothing. NB! the is a command that works on the device I'm talking to and it simple returns the contents of the current directory just like a Linux ls command. All ideas are welcome. cheers

import sys
import serial
import time
import threading

class dutserial(object):
    def __init__(self, port):
        self._port = port
        self._baudrate=921600
        self._conn = None    

    def dutOpenConn(self):
        try:
            self._conn = serial.Serial(self._port, self._baudrate)
            return self._conn
        except:
            print "Failed to open port %s " % str(self._port)

    def dutCloseConn(self):
        self._conn.close()

    def dutSendCmd(self, cmd):
        self._conn.write(cmd + '\r\n')

    def dutRead(self):
        #self._conn.write('fs ls \r\n')
        time.sleep(1)
        out = ''
        while True:           
            while self._conn.inWaiting() > 0:
                out += self._conn.read(1)

            if out != '':
                print ">>" + out        

def main():
    s = dutserial('com4')
    s.dutOpenConn()
    ReadThread = threading.Thread(target= s.dutRead())
    ReadThread.start()

    # The program is hanging up here. it never moves on to the next loop 
    # where I'm planning on testing out my no-blocking serial port read

    for _ in range(5):
        s.dutSendCmd('fs ls')
        time.sleep(2)

    print 'Done.......'    


if __name__ == '__main__':
    main()

Hi i think what causing your code to stuck is because in the thread function you should not put the () after the methods you wish as your thread target. If you put the () ( s.dutRead()) It wil make your code only to execute the methods s.dutRead(), so please try to.remove the () on the target thread

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM