Accelerometer数据写入文件然后图形Matplotlib(3个子图[x,y,z])

时间:2014-03-18 19:19:29

标签: python matplotlib accelerometer

我不熟悉编程所以请耐心等待。编程项目是一种业余爱好(我是一名物理专业)。无论如何,尝试接收串行数据,然后使用ADXL345分线跳闸加速度计从Arduino Uno使用matplotlib进行图形化。我现在不需要它是动态的(实时馈送)。这是我将代码数据写入文件的代码。

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

这是一个相当容易访问的文本文件,我想将其转换为matplotlib图,其中包含每个轴(x,y,z)的三个子图。我从python获得了一个File IO errno 2,说它无法找到该文件(不存在),但确实如此,并且路径对我有限的知识是正确的。任何帮助都非常感谢。这是我做得不好的尝试的相关部分:

import numpy as npy
import matplotlib.pyplot as plt
global y0,y1,y2
increment_size = 8000
datasample_size = 16000

filepath = ("C:\Users\Josh\Documents\Programming\data.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])]

2 个答案:

答案 0 :(得分: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")

答案 1 :(得分:0)

如果您对从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_()