我建議使用Python的線程類istantiate串行連接,在運行methos把你的while循環,設置您在結束使用殺IY的變種,你使用第二公共變種對於存儲數據有如果接收和主方法的數據負載..很快粘貼一個例子
class Arduino():
def __init__(self,Port='/dev/ttyUSB0',Boud=9600,connState=0):
self.parent=self
self.port=Port
self.boud=Boud
self.connState=connState
self.timeount=1
self.ser=None
self.connect()
def connect(self):
try:
self.ser=serial.Serial(self.port,self.boud,timeout=0.0001)
self.connState=1
return [1,'connect']
except:
self.connState=0
return [0,'no hardware found']
def loadData(self):
self.buffer=self.ser.read(1)
if (self.buffer!=''):
try:
print self.buffer
except Exception, e:
pass
ard=Arduino()
while True:
if ard.connState:
ard.loadData()
else:
print "Arduino not found"
break
並與開始:
import threading
class ThController(threading.Thread):
# Override Thread's __init__ method to accept the parameters needed:
def __init__(self,parent):
self.parent = parent
threading.Thread.__init__ (self)
def run (self):
while self.parent.ctrlattive:
j=json.loads(data)
self.parent.data=j
更好地使用'os.path.exists('/ dev/ttyUSB0')' – goetzc