我目前在python中的pySerial模块有问题。我的问题涉及连接和断开设备。我可以成功地连接到我的设备,并且只要我想和它沟通,并在我需要的时候断开连接。但是,一旦连接断开,我无法重新连接到设备。用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)
有谁知道为什么这个问题存在,我可以尝试做些什么来解决它的原因是什么?
当你尝试重新连接时,你会得到什么异常/痕迹?你在Windows还是Linux? – jedwards
“连接被切断”是什么意思?你的意思是拔掉串口线,或者退出你的python进程? – TJD
@andrew donelick与您的问题的答案无关,但为什么不初始化'__init __()'中的'Serial'对象? – 2012-06-19 00:16:50