我目前在Python中的pySerial模块上遇到了问题。我的问题与连接和断开设备有关。我可以成功连接到我的设备并随心所欲地与之通信,并随时断开与它的连接。但是,一旦连接断开,我将无法重新连接到设备。
这是我的程序用来与串行端口接口的包装类:
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)
有谁知道这个问题存在的原因以及我可以尝试做些什么来解决这个问题?
完成后,
您不会释放串行端口。在退出程序之前使用 ser.close()
关闭端口,否则端口将无限期保持锁定状态。为此,我建议在您的类中添加一个名为 disconnect()
的方法。
如果您使用的是Windows,要在测试期间纠正这种情况,请启动任务管理器并杀死可能锁定串行端口的任何python.exe
或pythonw.exe
进程。