Reconnecting to device with pySerial

17,467

You aren't releasing the serial port when you are finished. Use ser.close() to close the port before exiting your program, otherwise the port will stay locked indefinitely. I would suggest adding a method called disconnect() in your class for this.

If you are on Windows, to remedy the situation during testing, start Task Manager and kill any python.exe or pythonw.exe processes that may be locking the serial port.

Share:
17,467
Andrew Donelick
Author by

Andrew Donelick

Updated on June 21, 2022

Comments

  • Andrew Donelick
    Andrew Donelick almost 2 years

    I am currently having a problem with the pySerial module in Python. My problem relates to connecting and disconnecting to a device. I can successfully connect to my device and communicate with it for as long as I want to, and disconnect from it whenever I desire. However, I am unable to reconnect to the device once the connection has been severed.

    Here is the wrapper class that my program uses to interface with the serial port:

    import serial, tkMessageBox
    
    class Controller:
    """ Wrapper class for managing the serial connection with the MS-2000. """
        def __init__(self, settings):
            self.ser = None
            self.settings = settings
    
        def connect(self):
            """ Connect or disconnect to MS-2000. Return connection status."""
            try:
                if self.ser == None:
                    self.ser = serial.Serial(self.settings['PORT'],
                                             self.settings['BAUDRATE'])
                    print "Successfully connected to port %r." % self.ser.port
                    return True
                else:
                    if self.ser.isOpen():
                        self.ser.close()
                        print "Disconnected."
                        return False
                    else:
                        self.ser.open()
                        print "Connected."
                        return True
            except serial.SerialException, e:
                return False
    
        def isConnected(self):
            '''Is the computer connected with the MS-2000?'''
            try:
                return self.ser.isOpen()
            except:
                return False
    
        def write(self, command):
            """ Sends command to MS-2000, appending a carraige return. """
            try:
                self.ser.write(command + '\r')
            except Exception, e:
                tkMessageBox.showerror('Serial connection error',
                                       'Error sending message "%s" to MS-2000:\n%s' %
                                   (command, e))
    
        def read(self, chars):
            """ Reads specified number of characters from the serial port. """
            return self.ser.read(chars)
    

    Does anybody know the reason why this problem exists and what I could try to do to fix it?

  • SaundersB
    SaundersB over 7 years
    Thank you. After all the searching I did to close the serial port, which Sublime Text, Python, has kept the port open when I rebuilt the project, this was the best solution.