使用Pyserial打开串口时遇到问题

0 投票
1 回答
3026 浏览
提问于 2025-04-16 14:45

我正在尝试使用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次,但我不知道这个“100”是从哪里来的,也不知道为什么端口没有正确打开。与另一个程序不同,这段代码在打开端口时没有延迟,所以我甚至不知道它是否尝试去打开。

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

1 个回答

3
except serial.serialutil.SerialException:

你现在是在捕捉并忽略连接时的错误。把这一段代码注释掉,看看是否会出现错误信息。

撰写回答