2011-03-30 96 views
0

我试图读取通过蓝牙调制解调器使用Pyserial从串口发送的数值。我是Python的初学者,并发现了一个很好的例子,我试图利用它。用Pyserial打开串口时出现问题

from threading import Thread 
import time 
import serial 

last_received = '' 
def receiving(ser): 
    global last_received 
    buffer = '' 
    while True: 
     buffer = buffer + ser.read(ser.inWaiting()) 
     if '\n' in buffer: 
      lines = buffer.split('\n') # Guaranteed to have at least 2 entries 
      last_received = lines[-2] 
      #If the modem sends lots of empty lines, you'll lose the 
      #last filled line, so you could make the above statement conditional 
      #like so: if lines[-2]: last_received = lines[-2] 
      buffer = lines[-1] 


class SerialData(object): 
    def __init__(self, init=50): 
     try: 
      self.ser = ser = serial.Serial(
      port='/dev/tty.FireFly-16CB-SPP', 
      baudrate=115200, 
      stopbits=serial.STOPBITS_ONE, 
      bytesize=serial.EIGHTBITS 
      ) 
     except serial.serialutil.SerialException: 
      #no serial connection 
      self.ser = None 
     else: 
      Thread(target=receiving, args=(self.ser,)).start() 

    def next(self): 
     if not self.ser: 
      return 140 #return anything so we can test when Arduino isn't connected 
     #return a float value or try a few times until we get one 
     for i in range(40): 
      raw_line = last_received 
      try: 
       return float(raw_line.strip()) 
      except ValueError: 
       print 'bogus data',raw_line 
       time.sleep(.005) 
     return 0. 
    def __del__(self): 
     if self.ser: 
      self.ser.close() 

if __name__=='__main__': 
    s = SerialData() 
    for i in range(500): 
     time.sleep(.015) 
     print s.next() 

我可以在另一个程序中打开端口,并且可以从它发送/接收数据。但是,上面的代码似乎并没有打开端口,只是重复“100”到终端窗口500次,但我不知道它来自哪里或为什么端口无法正常打开。打开端口没有任何延迟,因为它在另一个程序上,所以我甚至不知道它是否尝试打开。

我不知道还有什么要尝试的,或者错误在哪里,所以我在寻求帮助。我究竟做错了什么?

回答

3
except serial.serialutil.SerialException: 

你正在捕捉和沉默连接错误。注释掉这个块,看它是否产生错误信息。