使用Pyserial打开串口时出现问题

时间:2011-03-30 17:38:29

标签: python pyserial

我正在尝试使用Pyserial读取通过串行端口通过蓝牙调制解调器发送的数值。我是Python的初学者,并找到了一个我正在尝试使用的好例子。

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次,但我不知道它来自何处或为什么端口无法正确打开。打开端口没有延迟,因为它在另一个程序上,所以我甚至不知道它是否试图打开。

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

1 个答案:

答案 0 :(得分:3)

except serial.serialutil.SerialException:

你正在捕捉并消除连接中的错误。注释掉这个块,看看它是否会产生错误信息。