German English
Sensors

ADXL345 - Read values from the ADXL345 acceleration sensor

The microcontroller on the radio module Preon32 has several IO interfaces which allows accessing nearly each kind of sensor. The product VariSen which is designed for use with Preon32 contains some sensors, the ADXL345 included.

This examples shows how to access a ADXL345 sensor via the SPI interface. The program reads the acceleration sensor values each second and prints it out. Accessing this sensor is very easy because Virtenio provides a driver for it.
/*
 * Copyright (c) 2011., Virtenio GmbH
 * All rights reserved.
 */
package com.virtenio.webdemo.sensor;

import com.virtenio.drivers.gpio.GPIO;
import com.virtenio.drivers.gpio.NativeGPIO;
import com.virtenio.drivers.sensors.spi.ADXL345;
import com.virtenio.drivers.spi.NativeSPI;

import java.io.IOException;

public class AccelerationI2C {

    public static void main(String[] args) throws IOException, InterruptedException {

        NativeSPI spi = NativeSPI.getInstance(2);
        spi.close();
        spi.open(ADXL345.SPI_MODE, ADXL345.SPI_BIT_ORDER, ADXL345.SPI_MAX_SPEED);

        GPIO accelCs = NativeGPIO.getInstance(20);
        ADXL345 accelerationSensor = new ADXL345(spi, accelCs);
        accelerationSensor.setDataFormat(ADXL345.DATA_FORMAT_RANGE_2G);
        accelerationSensor.setDataRate(ADXL345.DATA_RATE_3200HZ);
        accelerationSensor.setPowerControl(ADXL345.POWER_CONTROL_MEASURE);

        while (true) {
            // capture measured value every 1000ms
            short[] ch = new short[3];
            int offset = 0;
            accelerationSensor.getValues(ch, offset);
            System.out.println("Acceleration " +
                               "CH[0]:" + ch[0] + " " +
                               "CH[1]:" + ch[1] + " " +
                               "CH[2]:" + ch[2]);
            Thread.sleep(1000);
        }
    }
}