我正在从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.red(,否则数据将是这样的。
�
u
�
u
�
ASCII。为了获得十进制数据,我使用了ord(data(来获得类似的数据
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,则中断。