Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
change the first comments
# Simple demo of the ADXL345 accelerometer library. Will output the X, Y, Z
# axis acceleration values and its FFT values as csv files.
# Author: Tatsuya Sasaki
# License: Public Domain
# Import the ADXL345 module.
import Adafruit_ADXL345
import csv
import pandas as pd
import time
import sys
import math
import scipy
from datetime import datetime
from scipy.fftpack import fft
SAMPLES = 1024
# Max resolution value ( 3.9mg / LSB )
RESOLUTION = 3.9
accel = Adafruit_ADXL345.ADXL345(address=0x53, busnum=2)
accel.set_range(Adafruit_ADXL345.ADXL345_RANGE_16_G)
accel.set_data_rate(Adafruit_ADXL345.ADXL345_DATARATE_3200_HZ)
l = [None] * SAMPLES
# start measurement
start_time = datetime.now()
for i in xrange(SAMPLES):
l[i] = accel.read()
end_time = datetime.now()
# end of measurement
time_diff = end_time - start_time
duration_sec = time_diff.seconds + (time_diff.microseconds / float(10**6))
sys.stdout.write('Number of samples: ')
sys.stdout.write(str(SAMPLES))
print
sys.stdout.write('measurement takes ')
sys.stdout.write(str(duration_sec))
sys.stdout.write(' sec')
print
sps = SAMPLES / duration_sec
# raw data output
df = pd.DataFrame(l)
df.columns = ['x', 'y', 'z']
df *= RESOLUTION
df['time'] = pd.Series(scipy.array(range(SAMPLES))*duration_sec/SAMPLES)
df = df[['time', 'x', 'y', 'z']]
df.to_csv("rawoutput.csv")
# FFT output
start_time = datetime.now()
d = {'x': fft(df['x']), 'y': fft(df['y']), 'z':fft(df['z'])}
df_fft = pd.DataFrame(data=d)
end_time = datetime.now()
df_fft['frequency'] = pd.Series(scipy.array(range(SAMPLES))*sps/SAMPLES)
df_fft = df_fft[['frequency', 'x', 'y', 'z']]
df_fft.to_csv("fftoutput.csv")
time_diff = end_time - start_time
duration_sec = time_diff.seconds + (time_diff.microseconds / float(10**6))
sys.stdout.write("FFT takes: ")
sys.stdout.write(str(duration_sec))
sys.stdout.write(" sec")
print
sys.stdout.write("Sampling frequency: ")
sys.stdout.write(str(sps))
sys.stdout.write(" Hz")
print
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment