我从传感器收到串行数据,我只需要最后 20 个字节的数据,并想将其保存在文件中

I recieved Serial data from sensor what i want only last 20 bytes of data and want to save it in a file

我正在从 beaglebone 的 UART1 端口上的传感器获取数据。但我只想要最后 20 个字节的数据。 但是用 python 代码面对这些问题。 第一:-

import serial, time
ser = serial.Serial()
ser.port = "/dev/ttyO1"

ser.baudrate = 9600
ser.bytesize = serial.EIGHTBITS #number of bits per bytes
ser.parity = serial.PARITY_NONE #set parity check: no parity
ser.stopbits = serial.STOPBITS_ONE #number of stop bits
#ser.timeout = None          #block read
ser.timeout = 5 

   ser.open()
   file.open("data.txt","w")

time.sleep(5)  #give the serial port sometime to receive the data
while True:
     data = ord(ser.read())
     print(data)
     file.write(data)

使用此代码,我可以打印数据。当收到所有数据并且只有最后 10 或 20 个字节将存储在文件中时,我不知道如何结束循环。 我使用了 ord(ser.read) 否则数据将是这样的。

�

u
�

u
�

A​​SCII。为了以十进制获取数据,我使用了 ord(data) get data like this

79
1
1
12
0
13
116

您可以读取文件中的数据,创建列表,删除最后一个(列表的第一个元素)数据点,追加(到列表末尾)新的数据点,然后保存。

while True:
    text = file.readlines()
    text = [line.strip() for line in text]
    try:
        data = ord(ser.read())
    except:
        break
    if len(text) == 20:
        text.pop(0)
    text.append(data)
    file.write('\n'.join(text))

完整代码:

import serial, time
ser = serial.Serial()
ser.port = "/dev/ttyO1"

ser.baudrate = 9600
ser.bytesize = serial.EIGHTBITS #number of bits per bytes
ser.parity = serial.PARITY_NONE #set parity check: no parity
ser.stopbits = serial.STOPBITS_ONE #number of stop bits
#ser.timeout = None          #block read
ser.timeout = 5 

ser.open()
file.open("data.txt","w")

time.sleep(5)  #give the serial port sometime to receive the data
while True:
    text = file.readlines()
    text = [line.strip() for line in text]
    try:
        data = ord(ser.read())
    except:
        break
    if len(text) == 20:
        text.pop(0)
    text.append(data)
    file.write('\n'.join(text))

file.close()

你不清楚跳出循环,所以我把那部分漏掉了。如果你想在第 20 个数据点之后中断,你应该检查列表的长度,如果等于 20,则中断。