因此,一个较大项目的一部分需要使用树莓派从串口接收一个很长的十六进制字符串。我以为一切正常,但后来发现它在字符串中间丢失了一大块数据。
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
这是用于检索数据的脚本,波特率和串行命令设置正确,脚本以“无缓冲”(-u) 方式运行,但完整的字符串未保存。该字符串的长度约为 16384 个字符,但仅保存了大约 9520 个字符(有所不同)(无法提供该字符串进行分析)。有人知道我错过了什么吗?为你能给我的任何帮助干杯。
最佳答案
很高兴我的评论有所帮助!
将超时设置为一个较小的数字,例如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.
我将 block 放在列表中的原因是连接操作比字符串上的“+=”更有效。
关于python - 在接收到的串行字符串中丢失数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16306816/