Logging data from Arduino using PySerial

Thomas t.tchorzewski at gmail.com
Tue Feb 4 05:07:48 CET 2014


I've written a script to log data from my Arduino to a csv file. The script works well enough but it's very, very slow. I'm quite new to Python and I just wanted to put this out there to see if any Python experts could help optimise my code. Here it is:

    import serial
    import re
    import csv
    import numpy as np
    import matplotlib.pyplot as plt
    
    portPath = "/dev/ttyACM0"
    baud = 9600
    sample_time = 0.5
    sim_time = 30
    
    
    # Initializing Lists
    # Data Collection
    data_log = []
    line_data = []
    
    def map(x, in_min, in_max, out_min, out_max):
        return (((x - in_min) * (out_max - out_min))/(in_max - in_min)) + out_min
        
    # Establishing Serial Connection
    connection = serial.Serial(portPath,baud)
    
    # Calculating the length of data to collect based on the
    # sample time and simulation time (set by user)
    max_length = sim_time/sample_time
    
    # Collecting the data from the serial port
    while True:
        data_log.append(connection.readline())
        if len(data_log) > max_length - 1:
            break
                
    # Cleaning the data_log and storing it in data.csv
    with open('data.csv','wb') as csvfile:
        for line in data_log:
            line_data = re.findall('\d*\.\d*',line) # Find all digits
            line_data = filter(None,line_data)    # Filter out empty strings
            line_data = [float(x) for x in line_data] # Convert Strings to float
            
            for i in range(1,len(line_data)):
                line_data[i]=map(line_data[i],0,1023,0,5)
                
            csvwrite = csv.writer(csvfile)
            csvwrite.writerow(line_data)
            
            
    
    plt.clf()
    plt.close()
    plt.plotfile('data.csv',(0,1,2),names=['time (s)','voltage2 (V)','voltage1 (V)'],newfig=True)
    plt.show()


I'd appreciate any help/tips you can offer.



More information about the Python-list mailing list