小编典典

丢失接收到的串行字符串中的数据

python

因此,较大项目的一部分需要使用树莓派从串行端口接收一个较长的十六进制字符串。我以为我可以正常工作,但是后来发现它在字符串中间丢失了一大堆数据。

def BUTTON_Clicked(self, widget, data= None):

        ser = serial.Serial("/dev/ex_device", 115200, timeout=3)

        RECEIVEDfile = open("RECIEVED.txt", "r+", 0) #unbuffered


        #Commands sent out
        ser.write("*n\r")
        time.sleep(1)
        ser.flush()
        ser.write("*E")
        ser.write("\r")

        #Read back string rx'd
        RECEIVED= ser.read()


        RECEIVED= re.sub(r'[\W_]+', '', RECEIVED) #remove non-alphanumeric characters (caused by noise maybe?)
        RECEIVEDfile.write(re.sub("(.{4})", "\\1\n", RECEIVED, 0, re.DOTALL)) #new line every 4 characters


        RECEIVEDfile.close              
        ser.write("*i\r")
        ser.close

这是用于检索数据的脚本,设置了正确的波特率和串行命令,并且脚本以“
unbuffered”(-u)运行,但未保存完整字符串。该字符串长约16384个字符,但仅保存了约9520个字符(有所不同)(无法提供用于分析的字符串)。有人知道我在想什么吗?为您能给我的任何帮助加油。


阅读 139

收藏
2021-01-20

共1个答案

小编典典

很高兴我的评论有所帮助!

将超时设置为较低的数字,例如1秒。然后尝试这样的事情。它尝试读取较大的块,但超时很快,并且长时间不阻塞。任何已读取的内容都将放入列表(rx_buf)。然后,只要您有待读取的未读字节,就永远循环。真正的问题是“知道”何时不希望有更多数据。

rx_buf = [ser.read(16384)] # Try reading a large chunk of data, blocking for timeout secs.
while True: # Loop to read remaining data, to end of receive buffer.
    pending = ser.inWaiting()
    if pending:
         rx_buf.append(ser.read(pending)) # Append read chunks to the list.
    else:
         break

rx_data = ''.join(rx_buf) # Join the chunks, to get a string of serial data.

我将大块放在列表中的原因是,对字符串的联接操作比’+ =’更有效。

2021-01-20