Skip to main content
 首页 » 编程设计

python之Pyserial 非轮询读取

2024年11月01日14lyj

我正在使用 Pyserial(一个 Python 串行库)从树莓派上的串行端口读取十六进制数据,操作系统是 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