Search code examples
pythonmatplotlibaccelerometer

Accelerometer Data write to file then graph Matplotlib (3 subplots [x, y, z])


I'm not very versed in programming so bear with me. Programming project as a hobby (I'm a Physics major). Anyways, trying to receive serial data and then graph using matplotlib from an Arduino Uno using an ADXL345 Breakout Trip-Axis Accelerometer. I don't need it to be dynamic (live feed) at the moment. Here's my code for writing serial data to file that performs well.

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

This made a fairly accessible text file that I want to convert to a matplotlib graph containing three subplots for each axis (x, y, z). I'm getting a File IO errno 2 from python saying that it cant find the file (doesn't exist) but it does and the path is correct to my limited knowledge. Any help at all much appreciated. This is relevant part of my poorly made attempt:

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

Solution

  • Your filepath is the full file path, not the directory. You are then adding 'data.txt' to that, you need to change your code to:

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

    In python '\' is used for escaping characters so to have an actual '\' you must use '\\'.

    Alternatively you can (and generally should) use os.path.join to join together directories and files. In that case your code becomes:

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