Accelerometer Sample

Last updated on: November 16, 2020

Introduction

The "Accelerometer Sample" initializes the LIS2DH accelerometer on the Icarus IoT Board and reads the acceleration values 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_SENSOR=y
CONFIG_LIS2DH=y
CONFIG_LIS2DH_ACCEL_RANGE_8G=y
CONFIG_LIS2DH_ODR_2=y

These enable the I2C and accelerometer driver and sets a default value for the range and sampling rate. More settings to configure can be found on Zephyr's documentation portal.

Code explanation

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

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

then reads the acceleration values in a loop and prints them:

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.