我正在尝试从微控制器接收串行数据到 Python 中。微控制器使用此 C 代码通过串行通信输出以下内容。它输出一个每分钟转数值(浮点数)和一个以回车结束的时间值。 printf("f;%lu\r", appData.rpm, appData.time_elapsed);在 Python 中,我有以下代码来获取此串行数据。我想把时间值放在他们自己的数组中,我想把 RPM 值放在他们自己的数组中。我目前有代码将每一行放入一个字符串列表中,rpm 和时间值作为单独的列。import serialimport matplotlib.pyplot as pltimport numpy as npimport astimport ioline = []ser = serial.Serial( port='COM15',\ baudrate=19200,\ parity=serial.PARITY_NONE,\ bytesize=serial.EIGHTBITS,\ timeout=0)#Send the start commandprint(ser.write('s\r'.encode())) #tell the pic to send data. encode converts to a byte arrayser.close()ser.open()#this will store the lineseq = []count = 1#variables to store the data numericallyfloats = []time = []RPM = []samples = 0ser.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 breakser.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'
1 回答
慕桂英546537
TA贡献1848条经验 获得超10个赞
试试这个数据部分:
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']
希望这可以帮助
添加回答
举报
0/150
提交
取消