从 Arduino 传感器获取的数据将数组转换为 CSV

问题描述 投票:0回答:0

我想将从 Arduino 传感器捕获的数据保存到带有标题和索引的 csv 中。但是做不到。

我正在使用 Arduino Uno 和 MQ7 以及 MQ135 来捕获数据。然后用 Python 显示实时绘图。

我想转换我保存为

f
的数组,但问题是在我关闭pyplot gui后它没有保存为csv。

错在哪里?这是我的代码:

import serial 
import numpy as np
import pandas as pd 
import matplotlib.pyplot as plt 
from drawnow import *

PPMCO2=[]
MQ7CO= []

arduinoData = serial.Serial('/dev/ttyACM0', 115200) 
plt.ion() 
cnt=0

def makeFig(): 
    plt.subplot(2,1,1)
    plt.ylim(200,1000)                              
    plt.title('MQ7 and MQ135 Live Streaming Sensor Data')     
    plt.grid(True)                                      
    plt.plot(PPMCO2, 'ro-', label='CO2 (from MQ135)')    
    plt.legend(loc='upper left')                    
                                
    plt.subplot(2,1,2)
    plt.ylim(100,1000)                     
    plt.grid(True)  
    plt.plot(MQ7CO, 'b^-', label='CO (from MQ7)')                  
    plt.ticklabel_format(useOffset=False)         
    plt.legend(loc='upper right')                 

while True: 
    while (arduinoData.inWaiting()==0): 
        pass 
    arduinoString = arduinoData.readline()
    #print(arduinoString)   
    s = str(arduinoString)
    s = s.replace('b\'','')
    s = s.replace('\\r\\n\'','')
    f = str(arduinoString)
    f = f.replace('b\'','[')
    f = f.replace('\\r\\n\'','],')
    print(s) 
    print(f)     
    dataArray = s.split(',')
    co2 = float(dataArray[0])            
    co = float(dataArray[1])  
    PPMCO2.append(co2)            
    MQ7CO.append(co)                
    drawnow(makeFig)                      
    plt.pause(.000001)     
    cnt=cnt+1
    
if(cnt>50):
    PPMCO2.pop(0)
    MQ7CO.pop(0)
arr = np.asarray([f])
pd.DataFrame(arr).to_csv('sample.csv', index_label = 'Index')   

显示了 pyplot GUI,我可以将

f
制作为具有以下格式的数组:

1

python pandas matplotlib
© www.soinside.com 2019 - 2024. All rights reserved.