Search code examples
pythonraspberry-pi3delayi2cdownsampling

Is it possible to increase the sampling rate of ADXL345 on a Raspberry Pi with Python?


I have a Raspberry Pi with 2 ADXL345 accelerometers, and I want to maximize the data sampling rate from them both. As I was searching the internet, I became intrigued to find someone on the Raspberry Pi forum (https://www.raspberrypi.org/forums/viewtopic.php?t=254552) displaying this code in which he uses two accelerometers in this example:

import time
import Adafruit_ADXL345


accel1 = Adafruit_ADXL345.ADXL345()
accel2 = Adafruit_ADXL345.ADXL345(address=0x1d, busnum=1)


print('Printing X, Y, Z axis values, press Ctrl-C to quit...')
cordinates = []

import time
start_time = time.time()
NUM_OF_SEC_TO_RUN = 10 

while time.time()<=start_time+NUM_OF_SEC_TO_RUN:

    x1, y1, z1 = accel1.read()
    x2, y2, z2 = accel2.read()
    cordinates.append([x1,y1,z1,x2,y2,z2,time.time()])

import csv
with open('02.txt', 'a') as csvFile:
    writer = csv.writer(csvFile)
    writer.writerows(cordinates)

Later in the post, he says that the segment

x1, y1, z1 = accel1.read()
x2, y2, z2 = accel2.read()
cordinates.append([x1,y1,z1,x2,y2,z2,time.time()])

was the most likely reason why the accelerometers are downsampling, thus lowering the read rate and delaying the data acquisition.

He says,

The average time for execution of the above 3 lines of code is 0.002121 seconds. Does this mean than the reading capability is limited because of i2c and Raspberry pi, not the sensor? Or is it because of my code?

I also wonder the same question, but I am going to pose it differently. Is there a way to make the segment above shortened so it could potentially reduce the delay and increase the data sampling rate? That is, can there be a way to make it into one line? As far as I can tell, there hasn't been a response to this guy's thread nor any conclusive ones that have helped me.

If there isn't a way to answer this question, then I pose this one: is there a way to speed up the data sampling speed of I2C on the Raspberry Pi 3 B+, or is it possible to replicate this code for SPI communication? I know for a fact that SPI communication is faster than I2C, but I am not sure how to implement it on Python in the Raspberry Pi. I apologize if this post is too long.


Solution

  • The ADXL345 data sheet says the fastest sampling rate using fast i2c is 800Hz. SPI is needed to get faster sampling rates--up to 3200Hz.

    It looks like the Adafruit_ADXL345 library only supports i2c. And it's deprecated. The Adafruit Blinka library supports SPI, but you'll have to roll your own ADXL345 interface.