Accelerometer Sample

Last updated on: May 16, 2020

Introduction

The accelerometer sample sets up the LIS2DH accelerometer on the Icarus board and reads the acceleration values from the accelerometer in a loop.

Download sample from Icarus - Accelerometer Sample

Project configuration

In order to use the accelerometer the sample enables the following settings in the prj.conf file:

CONFIG_I2C=y
CONFIG_I2C_NRFX=y
CONFIG_I2C_2=y
CONFIG_I2C_2_NRF_TWIM=y

These include and enable the I2C driver.

Additionally the sample configures the following accelerometer settings in the prj.conf (note that there are more settings you could set. Please check Zephyr docs to learn about all of them):

CONFIG_SENSOR=y
CONFIG_SENSOR_LOG_LEVEL_OFF=y
CONFIG_LIS2DH=y
CONFIG_LIS2DH_TRIGGER=y
CONFIG_LIS2DH_TRIGGER_OWN_THREAD=y
CONFIG_LIS2DH_ACCEL_RANGE_8G=y
CONFIG_LIS2DH_ODR_2=y

These enable the sensor driver, the accelerometer driver, sets up the accelerometer interrupts and configures the accelerometer value range and ODR.

Code explanation

The sample initializes the accelerometer getting the device binding from the Icarus device tree:

struct device* accel = device_get_binding("LIS2DH12-ACCEL");

then reads the acceleration values in a loop using the Zephyr sensor library and prints them.

The following code shows how the acceleration values are retrieved from the accelerometer:

sensor_sample_fetch(accel);
struct sensor_value value_x;
sensor_channel_get(accel, SENSOR_CHAN_ACCEL_X, &value_x);
struct sensor_value value_y;
sensor_channel_get(accel, SENSOR_CHAN_ACCEL_Y, &value_y);
struct sensor_value value_z;
sensor_channel_get(accel, SENSOR_CHAN_ACCEL_Z, &value_z);

In order to convert the value returned from the sensor to a double, the sensor library provides a helper method:

double x_accel = sensor_value_to_double(&value_x);

The unit of measurement is m/s^2.