我正在尝试从微控制器接收串行数据到Python中。微控制器使用此C代码通过串行通信输出以下内容。输出每分钟转数(浮点数)和以回车结束的时间值。
printf("f;%lu\r", appData.rpm, appData.time_elapsed);
在Python中,我有以下代码来获取此串行数据。我想将时间值放在他们自己的数组中,并将RPM值放在他们自己的数组中。我目前有将每一行放入rpm和time值作为单独列的字符串列表中的代码。
import serial
import matplotlib.pyplot as plt
import numpy as np
import ast
import io
line = []
ser = serial.Serial(
port='COM15',\
baudrate=19200,\
parity=serial.PARITY_NONE,\
bytesize=serial.EIGHTBITS,\
timeout=0)
#Send the start command
print(ser.write('s\r'.encode())) #tell the pic to send data. encode converts to a byte array
ser.close()
ser.open()
#this will store the line
seq = []
count = 1
#variables to store the data numerically
floats = []
time = []
RPM = []
samples = 0
ser.reset_input_buffer()
while True:
for i in ser.read():
seq.append(chr(i)) #convert from ASCII and append to array
joined_seq = ''.join((str)(j) for j in seq) #Make a string from array
if chr(i) == '\r':
joined_seq = joined_seq[:-1]
data = joined_seq.split(',')
print(data)
time.append(float(data[0]))
RPM.append(float(data[0]))
seq = []
data = []
count += 1
samples +=1
break
ser.close()
尝试将字符串转换为浮点数时出现以下错误。 任何帮助将不胜感激。
['\t\x82\x82\x82bª\x82\x82\x82\x82j0.0000', '100000']
Traceback (most recent call last):
File "gui.py", line 38, in <module>
time.append(float(data[0])) ValueError: could not convert string to float: '\t\x82\x82\x82bª\x82\x82\x82\x82j0.0000'
答案 0 :(得分:0)
在数据部分尝试以下操作:
data = '\t\x82\x82\x82bª\x82\x82\x82\x82j0.0000, 100000'
data = joined_seq.decode('ascii', errors='ignore').replace('\t', '').replace('j', '').replace('b', '').split(',')
data
[u'0.0000', u' 100000']
希望这会有所帮助