如何绘制串行数据

时间:2019-11-19 18:48:49

标签: python csv plot arduino

我想从Arduino绘制数据,类似于从Arduino IDE绘制功能。最好的方法是现场绘制。

import serial as sl
import time
from datetime import datetime 
import serial.tools.list_ports
import csv

import matplotlib.pyplot as plt

x = []
y = []

runtime = 20 #10sec --> 31.6 fps 20sec --> 35.25sek 40sec --> 37.075
csvname = "test.csv" #name of the csv

counter = 0 #used tu count the entrys in the frame
count = 0
lock = True #used to start the "recording"
ports = serial.tools.list_ports.comports() #scann all avalable serial coms
data = [[], [], [], [], [], [], [], [], [], [], [], [0]] #List to save the data in
y = []
for port, desc, hwid in sorted(ports):
        print("{}: {} [{}]".format(port, desc, hwid))

        if port.startswith("/dev/cu.usbmodem") == True:  #only insert start of the com port, because number can change if usb port changes
            ser = sl.Serial(port,115200)  #start serial connetion witz baudrate of pc

def animate(i):
    x_values.append(next(index))
    y_values.append(data[0][-1])
    plt.cla()
    plt.plot(x_values, y_values)


t_end = time.time() + runtime 
while time.time() < t_end: #run loop for x seconds defined above
    ser_out = ser.readline()     #read out the serial data
    values = ser_out.decode().split(",") #split the data accordingly
    data[11][0] = data[11][0] + 1 #count the amount of entrys 
    for value in values:
        value = value.replace("\r\n","") #clear up data
        if value == "package end":      #command for frame end
            print("packages recieved") 
            lock = True
            counter = 0

        if lock == False:
            data[counter].append(value) #write every data to the list
            counter = counter + 1 
            print(data)

            #ani = animation.FuncAnimation(fig, animate)
            #plt.show()

        if value == "package start":        #command for frame start
            print("packages recieving")
            data[10].append(datetime.now().strftime("%Y-%m-%d-%H_%M_%S_%f"))
            lock = False
print("Numer of frames: ") 
print(data[11])
print("Numer of seconds: ") 
print(runtime)
print("Frames per second: ") 
print(data[11][0]/runtime)
print("Name of csv: "+csvname)

with open(csvname, "w", newline="") as f:  #write .csv !csv gets overwritten
    writer = csv.writer(f)
    writer.writerows(data) 

关于代码的一件事:我目前获得10个不同的测量值,并且我还保存了1个时间戳和一个“帧”计数的索引。

我希望有人可以提供帮助,因为我对matlab等并不熟悉。

0 个答案:

没有答案