简体   繁体   中英

Convert string list to float list

I am attempting to receive serial data into Python from a microcontroller. The microcontroller outputs the following through serial comms using this C code. It outputs a revolutions per minute value (floating point) and a time value terminated with a return carriage.

 printf("f;%lu\r", appData.rpm, appData.time_elapsed);

In Python I have the following code to get this serial data. I'd like to put the time values in their own array and I'd like to put the RPM values in their own array. I currently have the code placing each line into a string list with the rpm and time values as separate columns.

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()

I'm getting the error shown below when trying to convert a string to a float. Any help would be greatly appreciated.

['\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'

Try this for the data portion:

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']

Hope this helps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM