Program to read from ADXL345 sensor

Connect the ADXL345 module to BeagleBone as shown in the diagram. Type the following program in Cloud9, save it as ADXL345.py and run it. You should see a three-axis coordinates list printed after every 2 seconds. If you move the sensor, you will see a change in coordinates.

from Adafruit_I2C import Adafruit_I2C
import time

ADXL345_I2C_ID           = 0x53 # I2C bus id
ADXL345_REG_POWER_CTL    = 0x2D # Power-saving control
ADXL345_REG_DATAX0       = 0x32 # X-axis data 0

accel = Adafruit_I2C(ADXL345_I2C_ID,debug=False)
accel.write8(ADXL345_REG_POWER_CTL, 0x08)

while True:
    raw = accel.readList(ADXL345_REG_DATAX0, 6)
    result = []
    for i in range(0, 6, 2):
        g = raw[i] | (raw[i+1] << 8)
        if g > 32767: g -= 65536
        result.append(g)
    print "result = " + str(result)
    time.sleep(2)

Explanation

I2C implementation in the Adafruit_BBIO library is a simple Python file. It has a class named Adafruit_I2C and a few functions defined in it. These functions are mostly about reading and writing in bytes/words to and from the I2C device. In order to communicate with ADXL345, we need to read its datasheet. The datasheet states that the sensor starts in standby mode by default. It goes to normal measurement mode by setting the third bit in POWER_CTRL register (address 0x2D). Then you can read X, Y, Z coordinates from the data register with address 0x32, 0x34 and 0x36 respectively. You can even read 6 bytes from the DATAX (address 0x32) register and break it into two bytes each to get X, Y, and Z axis coordinates.

In our program, we first called constructor Adafruit_I2C() with the parameter "0x53" which is the I2C address of ADXL345. Then we wrote 0x8 on the POWER_CTRL register of the sensor, which also means we set the third bit of the register to get it out of standby mode. We read 6 bytes starting from the DATAX register using function readList(). Then we copied 2 bytes into a single element of the result list in a loop and printed it.

Troubleshooting

  • Linux provides excellent tools for I2C device communication under package "i2c-tools." ADXL345 has the I2C address 0x53. When you connect it to BeagleBone, run the following command on the BeagleBone shell. This command shows the addresses of all I2C devices connected to the I2C2 bus of BeagleBone. Confirm that the fifth row and third column have the value "53."
    i2cdetect –y –r 1
    
  • You can turn on debugging by providing the parameter "debug=True" to the constructor Adafruit_I2C().
  • ADXL345 supports both I2C and SPI modes. Only one mode can be active at a time. Most of the time, the I2C mode is enabled by default. If you cannot see it detected using the "i2cdetect" command above, attach the CS pin of ADXL345 to 3.3V.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.141.28.107