加速度计数据写入文件,然后绘图Matplotlib(3个子图[x, y, z])



我不是很精通编程,所以请原谅我。业余爱好编程项目(我学的是物理专业)。无论如何,尝试接收串行数据,然后使用matplotlib从Arduino Uno使用ADXL345断路行程轴加速度计绘图。我不需要它是动态的(实时馈送)。下面是我的代码,用于将串行数据写入执行良好的文件。

import serial
filepath = 'C:/Users/Josh/Documents/Programming/'
outfilename =filepath + 'data.txt'
outfile = open(outfilename,"w")
numpoints = 1000
ser = serial.Serial('COM4',9600)
for i in range(numpoints):
    inString=ser.readline()
    print inString
    outfile.write(inString)
ser.close()
outfile.close()

这是一个相当可访问的文本文件,我想转换为包含每个轴(x, y, z)的三个子图的matplotlib图。我从python得到一个文件IO errno 2,说它找不到文件(不存在),但它确实和路径是正确的我有限的知识。任何帮助都非常感谢。这是我失败尝试的相关部分:

import numpy as npy
import matplotlib.pyplot as plt
global y0,y1,y2
increment_size = 8000
datasample_size = 16000
filepath = ("C:UsersJoshDocumentsProgrammingdata.txt")
infile = filepath + 'data.txt'
infile = open("data.txt","r")
singleline = infile.readline()
asciidata = singleline.split()
asciidata[0]=asciidata[0][3:]  #strip three bytes of extraneous info
y0=[int(asciidata[0])]
y1=[int(asciidata[1])]
y2=[int(asciidata[2])]

您的文件路径是完整的文件路径,而不是目录。然后将'data.txt'添加到其中,您需要更改代码为:

filepath = 'C:\Users\Josh\Documents\Programming\'
infile = filepath + 'data.txt'
infile = open(infile,"r")

在python中''用于转义字符,所以要有一个实际的'',你必须使用'\'。

或者您可以(通常应该)使用os.path.join将目录和文件连接在一起。在这种情况下,你的代码变成:

from os.path import join
filepath = 'C:\Users\Josh\Documents\Programming'
infile = join(filepath, 'data.txt')
infile = open(infile,"r")

如果您对绘制ADXL345的实时读数感兴趣,这里是我的代码。我使用pyqtgraph快速绘图

    from pyqtgraph.Qt import QtGui, QtCore
    import numpy as np
    import pyqtgraph as pg
    import serial
    app = QtGui.QApplication([])
    xdata = [0]
    ydata = [0]
    zdata = [0]
    # set up a plot window
    graph = pg.plot()
    graph.setWindowTitle("ADXL345 realtime data")
    graph.setInteractive(True)
    xcurve = graph.plot(pen=(255,0,0), name="X axis")
    ycurve = graph.plot(pen=(0,255,0), name="Y axis")
    zcurve = graph.plot(pen=(0,0,255), name="Z axis")
    # open serial port
    ser = serial.Serial("COM4", 115200, timeout=1)
    def update():
        global xcurve, ycurve, zcurve, xdata, ydata, zdata
        # serial read
        dataRead = ser.readline().split()
        # append to data list
        xdata.append(float(dataRead[0]))
        ydata.append(float(dataRead[1]))
        zdata.append(float(dataRead[2]))
        # plot 
        xcurve.setData(xdata)
        ycurve.setData(ydata)
        zcurve.setData(zdata)
        app.processEvents()  
    # Qt timer
    timer = QtCore.QTimer()
    timer.timeout.connect(update)
    timer.start(0)

    if __name__ == '__main__':
        import sys
        if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'):
            QtGui.QApplication.instance().exec_() 

最新更新