Python Pyserial非轮询读取

Python Pyserial非轮询读取,python,serial-port,pyserial,Python,Serial Port,Pyserial,我正在使用Pyserial(一个Python串行库)从raspberry pi上的串行端口读取十六进制数据,操作系统是raspbian 我需要从串行端口每次读取一个字节,并立即处理数据,没有任何时间延迟。我现在所做的只是轮询,在循环中不断地从端口读取数据。问题是它占用了几乎95%的CPU,并且使其他进程变慢 我相信有一种更好的方法可以做到这一点,而不需要使用太多的CPU资源。我用“minicom”来监视串行端口,它不占用太多CPU。所以我想知道任何熟悉Pyserial的人都能帮我,或者任何人都能

我正在使用Pyserial(一个Python串行库)从raspberry pi上的串行端口读取十六进制数据,操作系统是raspbian

我需要从串行端口每次读取一个字节,并立即处理数据,没有任何时间延迟。我现在所做的只是轮询,在循环中不断地从端口读取数据。问题是它占用了几乎95%的CPU,并且使其他进程变慢

我相信有一种更好的方法可以做到这一点,而不需要使用太多的CPU资源。我用“minicom”来监视串行端口,它不占用太多CPU。所以我想知道任何熟悉Pyserial的人都能帮我,或者任何人都能告诉我minicom是如何做到这一点的

这是我的密码。非常感谢

while True:
    try:
        reading = ser.read().encode('hex')

        if reading == "":
            continue

        #always add to packet when it's not empty
        data_packet.append(reading)

        if check_byte == True:
            #sometimes, check byte could be 2a
            check_byte = False
            continue
        elif length_byte == True:
            #this byte is length
            packet_length = int(reading, 16)
            length_byte = False

        if packet_length == 0 and hex_equals(reading, "2a"):
            #start of a string
            #next byte is length
            length_byte = True
        elif packet_length > 0:
            packet_length -= 1
        elif hex_equals(reading, "23"):
            #end of packet
            data_packet_handle = data_packet
            data_packet = []
            handle_data(data_packet_handle)
        elif packet_length == 0:
            #if it's zero, the packet is over, but still have check and ending character
            #next byte is check byte
            check_byte = True
    except Exception, err:
        pass
        print Exception, err

我刚刚解决了自己的问题

之前,我设置了'timeout=0',因此它不断地检查串行端口

现在我设置'timeout=None',它将等待,直到有足够的数据来自串行端口。现在CPU的使用率只在有来自串口的数据时使用,而且没有那么多

以下是打开串行端口的代码:

ser = serial.Serial(port=serial_port, baudrate=2400, bytesize=8, parity='N', stopbits=1, timeout=None)  # open first serial port

示例代码中没有“timeout=0”。你能把这个贴在哪里吗?Thank.ser=serial.serial(端口=serial\u端口,波特率=2400,字节大小=8,奇偶校验=N',停止位=1,超时=None)