Reconnecting to device using pySerial

I am currently having a problem with the pySerial module in Python. My problem is connecting and disconnecting the device. I can successfully connect to my device and communicate with it as much as I want, and disconnect from it when I want. However, I cannot connect to the device after the connection has been disconnected.

Here is the shell class that my program uses for the serial port interface:

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 anyone know the reason this problem exists, and that I can try to fix it?

+6
source share
1 answer

You do not release the serial port when you are done. Use ser.close() to close the port before exiting the program, otherwise the port will remain blocked indefinitely. I would suggest adding for this a method called disconnect() in your class.

If you are on Windows, to fix the situation during testing, start the task manager and kill all python.exe or pythonw.exe processes that may block the serial port.

+2
source

Source: https://habr.com/ru/post/918419/


All Articles