This post is older than 2 years and might not be relevant anymore
More Info: Consider searching for newer posts

BMI160 sample on custom nRF9160

I'm trying to get the bmi160 sample to work with my custom nRF9160 board. I think the sample is quite old and not maintained. Unmodified (except fixing pure compilation errors, like k_sleep(300) / s32_t etc.), it does not automatically configure SPI to find my BMI160 (printing out ctx->config->cs->gpio_pin in spi_context.h gives some random number). I had to hard-code the chip select pin in the top of the driver .c-file and pass it as a pointer to the instantiation macro (a hacky way to make sure I at least can communicate with the chip to rule out hardware faults). Any elegant way of doing this more generic?

The bigger problem is, it crashes sometime after it ends the function bmi160_init(). My board has a switchable secondary 3.3V power rail (where the bmi160 is powered from). This rail is enabled early in the application. Since the bmi160 is initiated at boot (before the application runs) it has no power, and it hangs forever. I had to turn on the regulator in the beginning of the driver in bmi160_init() (another hacky way to get things going). I'm not sure if this would cause any problems? And what's would be the best way to configure pins and their default state at boot (perhaps as early as possible)?

Regarding the crash, I think it could have something to do with how SPI is hooked to the chip and which settings are passes around, or even set in the beginning. I see the chip select is ok throughout, but operation setting shows as 256, yet i've explicitly set it to SPI_WORD_SET(8), butspi_nrfx_spim complains about Only single line mode is supported. Sometimes it complains about Word sizes other than 8 bits are not supported. Another thought is that I'm building it secure, but I read many places SPI needs non-secure (but I can do simple miso-mosi loopback with success). The problem is, that many of my applications (not all), just builds the zephyr.hex, not merged.hex (another ticket): nRF9160 and SPI (CS control inhibited (no GPIO device).

I'm on MacOS 10.15.7, Zephyr v2.5.0-352-gd96c517bab0d ,West v0.10.1. Building and flashing with west (not SES at the moment).

This is the crash:

[00:00:01.960,449] .[1;31m<err> spi_nrfx_spim: Only single line mode is supported.[0m
[00:00:01.960,479] .[0m<inf> spi_nrfx_spim: ctx->config->cs->gpio_dev: 536871256.[0m
[00:00:01.960,479] .[0m<inf> spi_nrfx_spim: ctx->config->cs->gpio_pin: 8.[0m
[00:00:01.960,479] .[0m<inf> spi_nrfx_spim: ctx->config->cs->gpio_dt_flags: 1.[0m
[00:00:01.960,479] .[0m<inf> spi_nrfx_spim: ctx->config->operation: 256.[0m
[00:00:01.960,998] .[1;31m<err> os: ***** MPU FAULT *****.[0m
[00:00:01.960,998] .[1;31m<err> os:   Instruction Access Violation.[0m
[00:00:01.960,998] .[1;31m<err> os: r0/a1:  0x20000170  r1/a2:  0x20000544  r2/a3:  0x00000001.[0m
[00:00:01.960,998] .[1;31m<err> os: r3/a4:  0x50008000 r12/ip:  0x200005e4 r14/lr:  0x00003f79.[0m
[00:00:01.961,029] .[1;31m<err> os:  xpsr:  0x28000000.[0m
[00:00:01.961,029] .[1;31m<err> os: Faulting instruction address (r15/pc): 0x50008000.[0m
[00:00:01.961,029] .[1;31m<err> os: >>> ZEPHYR FATAL ERROR 0: CPU exception on CPU 0.[0m
[00:00:01.961,029] .[1;31m<err> os: Current thread: 0x20000368 (unknown).[0m
[00:00:02.103,790] .[1;31m<err> os: Halting system.[0m

Here is my main.c:

/*
 * Copyright (c) 2016 Intel Corporation
 *
 * SPDX-License-Identifier: Apache-2.0
 */


#include <zephyr.h>
#include <stdio.h>
#include <device.h>
#include <drivers/sensor.h>
#include <sys/printk.h>


#define MAX_TEST_TIME	15000
#define SLEEPTIME	300


/* uncomment next line for setting offsets manually */
// #define PERFORM_MANUAL_CALIBRATION

/* uncomment the next line for auto calibration */
//#define PERFORM_AUTO_CALIBRATION




#ifdef PERFORM_MANUAL_CALIBRATION
/*
 * Offset map needed for manual accelerometer calibration. These values are
 * deduced by holding the device perpendicular on one axis (usually that's Z if
 * the device lies flat on the table) and compute the difference so that the
 * values on the 3 axis look like this: X: 0, Y: 0; Z: 9.80665. Due to
 * accelerometer noise, the values will vary around these values.
 *
 * For example if the accelerometer output, without offset compensation, is :
 *
 *   Acc (m/s^2): X=-2.349435, Y=-0.488070, Z=11.158620
 *
 * then the offsets necessary to compensate the read values are:
 *   X = +2.349435, Y = +0.488070. Z = -1.351970
 */
static struct sensor_value accel_offsets[] = {
	{2, 349435},   /* X */
	{0, 488070},   /* Y */
	{-1, -351970}, /* Z */
};

/*
 * The same goes for gyro offsets but, in gyro's case, the values should
 * converge to 0 (with the device standing still).
 */
static struct sensor_value gyro_offsets[] = {
	{0, 3195}, /* X */
	{0, 3195}, /* Y */
	{0, -4260},/* Z */
};

static int manual_calibration(struct device *bmi160)
{
#if !defined(CONFIG_BMI160_ACCEL_PMU_SUSPEND)
	/* set accelerometer offsets */
	if (sensor_attr_set(bmi160, SENSOR_CHAN_ACCEL_XYZ,
			    SENSOR_ATTR_OFFSET, accel_offsets) < 0) {
		return -EIO;
	}
#endif

#if !defined(CONFIG_BMI160_GYRO_PMU_SUSPEND)
	/* set gyroscope offsets */
	if (sensor_attr_set(bmi160, SENSOR_CHAN_GYRO_XYZ,
			    SENSOR_ATTR_OFFSET, gyro_offsets) < 0) {
		return -EIO;
	}
#endif

	return 0;
}
#endif

#ifdef PERFORM_AUTO_CALIBRATION
/*
 * The values in the following map are the expected values that the
 * accelerometer needs to converge to if the device lies flat on the table. The
 * device has to stay still for about 500ms = 250ms(accel) + 250ms(gyro).
 */
struct sensor_value acc_calib[] = {
	{0, 0},      /* X */
	{0, 0},      /* Y */
	{9, 806650}, /* Z */
};
static int auto_calibration(struct device *bmi160)
{
#if !defined(CONFIG_BMI160_ACCEL_PMU_SUSPEND)
	/* calibrate accelerometer */
	if (sensor_attr_set(bmi160, SENSOR_CHAN_ACCEL_XYZ,
			      SENSOR_ATTR_CALIB_TARGET, acc_calib) < 0) {
		return -EIO;
	}
#endif

#if !defined(CONFIG_BMI160_GYRO_PMU_SUSPEND)
	/*
	 * Calibrate gyro. No calibration value needs to be passed to BMI160 as
	 * the target on all axis is set internally to 0. This is used just to
	 * trigger a gyro calibration.
	 */
	if (sensor_attr_set(bmi160, SENSOR_CHAN_GYRO_XYZ,
			      SENSOR_ATTR_CALIB_TARGET, NULL) < 0) {
		return -EIO;
	}
#endif

	return 0;
}
#endif

/**
 * @brief Helper function for printing a sensor value to a buffer
 *
 * @param buf A pointer to the buffer to which the printing is done.
 * @param len Size of buffer in bytes.
 * @param val A pointer to a sensor_value struct holding the value
 *            to be printed.
 *
 * @return The number of characters printed to the buffer.
 */
static inline int sensor_value_snprintf(char *buf, size_t len,
					const struct sensor_value *val)
{
	int32_t val1, val2;

	if (val->val2 == 0) {
		return snprintf(buf, len, "%d", val->val1);
	}

	/* normalize value */
	if (val->val1 < 0 && val->val2 > 0) {
		val1 = val->val1 + 1;
		val2 = val->val2 - 1000000;
	} else {
		val1 = val->val1;
		val2 = val->val2;
	}

	/* print value to buffer */
	if (val1 > 0 || (val1 == 0 && val2 > 0)) {
		return snprintf(buf, len, "%d.%06d", val1, val2);
	} else if (val1 == 0 && val2 < 0) {
		return snprintf(buf, len, "-0.%06d", -val2);
	} else {
		return snprintf(buf, len, "%d.%06d", val1, -val2);
	}
}

#if !defined(CONFIG_BMI160_GYRO_PMU_SUSPEND)
static void print_gyro_data(struct device *bmi160)
{
	struct sensor_value val[3];
	char buf_x[18], buf_y[18], buf_z[18];

	if (sensor_channel_get(bmi160, SENSOR_CHAN_GYRO_XYZ, val) < 0) {
		printk("Cannot read bmi160 gyro channels.\n");
		return;
	}

	sensor_value_snprintf(buf_x, sizeof(buf_x), &val[0]);
	sensor_value_snprintf(buf_y, sizeof(buf_y), &val[1]);
	sensor_value_snprintf(buf_z, sizeof(buf_z), &val[2]);

	printk("Gyro (rad/s): X=%s, Y=%s, Z=%s\n", buf_x, buf_y, buf_z);
}
#endif

#if !defined(CONFIG_BMI160_ACCEL_PMU_SUSPEND)
static void print_accel_data(struct device *bmi160)
{
	struct sensor_value val[3];
	char buf_x[18], buf_y[18], buf_z[18];

	if (sensor_channel_get(bmi160,
			       SENSOR_CHAN_ACCEL_XYZ, val) < 0) {
		printk("Cannot read bmi160 accel channels.\n");
		return;
	}

	sensor_value_snprintf(buf_x, sizeof(buf_x), &val[0]);
	sensor_value_snprintf(buf_y, sizeof(buf_y), &val[1]);
	sensor_value_snprintf(buf_z, sizeof(buf_z), &val[2]);

	printk("Acc (m/s^2): X=%s, Y=%s, Z=%s\n", buf_x, buf_y, buf_z);
}
#endif

static void print_temp_data(struct device *bmi160)
{
	struct sensor_value val;
	char buf[18];

	if (sensor_channel_get(bmi160, SENSOR_CHAN_DIE_TEMP, &val) < 0) {
		printk("Temperature channel read error.\n");
		return;
	}

	sensor_value_snprintf(buf, sizeof(buf), &val);

	printk("Temperature (Celsius): %s\n", buf);
}

static void test_polling_mode(struct device *bmi160)
{
	int32_t remaining_test_time = MAX_TEST_TIME;
	struct sensor_value attr;

#if defined(CONFIG_BMI160_ACCEL_ODR_RUNTIME)
	/* set sampling frequency to 100Hz for accel */
	attr.val1 = 100;
	attr.val2 = 0;

	if (sensor_attr_set(bmi160, SENSOR_CHAN_ACCEL_XYZ,
			    SENSOR_ATTR_SAMPLING_FREQUENCY, &attr) < 0) {
		printk("Cannot set sampling frequency for accelerometer.\n");
		return;
	}
#endif

#if defined(CONFIG_BMI160_GYRO_ODR_RUNTIME)
	/* set sampling frequency to 3200Hz for gyro */
	attr.val1 = 3200;
	attr.val2 = 0;

	if (sensor_attr_set(bmi160, SENSOR_CHAN_GYRO_XYZ,
			    SENSOR_ATTR_SAMPLING_FREQUENCY, &attr) < 0) {
		printk("Cannot set sampling frequency for gyroscope.\n");
		return;
	}
#endif
	/* wait for the change to take effect */
	k_sleep(K_MSEC(SLEEPTIME));

	/* poll the data and print it */
	do {
		if (sensor_sample_fetch(bmi160) < 0) {
			printk("Sample update error.\n");
			return;
		}

#if !defined(CONFIG_BMI160_GYRO_PMU_SUSPEND)
		print_gyro_data(bmi160);
#endif
#if !defined(CONFIG_BMI160_ACCEL_PMU_SUSPEND)
		print_accel_data(bmi160);
#endif
		print_temp_data(bmi160);

		/* wait a while */
		k_sleep(K_MSEC(SLEEPTIME));

		remaining_test_time -= SLEEPTIME;
	} while (remaining_test_time > 0);
}

#ifdef CONFIG_BMI160_TRIGGER
static void trigger_hdlr(struct device *bmi160,
			 struct sensor_trigger *trigger)
{
	if (trigger->type != SENSOR_TRIG_DELTA &&
	    trigger->type != SENSOR_TRIG_DATA_READY) {
		return;
	}

	if (sensor_sample_fetch(bmi160) < 0) {
		printk("Sample update error.\n");
		return;
	}

#if !defined(CONFIG_BMI160_GYRO_PMU_SUSPEND)
	if (trigger->chan == SENSOR_CHAN_GYRO_XYZ) {
		print_gyro_data(bmi160);
	}
#endif

#if !defined(CONFIG_BMI160_ACCEL_PMU_SUSPEND)
	if (trigger->chan == SENSOR_CHAN_ACCEL_XYZ) {
		print_accel_data(bmi160);
	}
#endif
}

static void test_anymotion_trigger(struct device *bmi160)
{
	int32_t remaining_test_time = MAX_TEST_TIME;
	struct sensor_value attr;
	struct sensor_trigger trig;

	/* set up anymotion trigger */

	/*
	 * Set slope threshold to 0.1G (0.1 * 9.80665 = 4.903325 m/s^2).
	 * This depends on the chosen range. One cannot choose a threshold
	 * bigger than half the range. For example, for a 16G range, the
	 * threshold must not exceed 8G.
	 */
	attr.val1 = 0;
	attr.val2 = 980665;
	if (sensor_attr_set(bmi160, SENSOR_CHAN_ACCEL_XYZ,
			    SENSOR_ATTR_SLOPE_TH, &attr) < 0) {
		printk("Cannot set anymotion slope threshold.\n");
		return;
	}

	/*
	 * Set slope duration to 2 consecutive samples (after which the
	 * anymotion interrupt will trigger.
	 *
	 * Allowed values are from 1 to 4.
	 */
	attr.val1 = 2;
	attr.val2 = 0;
	if (sensor_attr_set(bmi160, SENSOR_CHAN_ACCEL_XYZ,
			    SENSOR_ATTR_SLOPE_DUR, &attr) < 0) {
		printk("Cannot set anymotion slope duration.\n");
		return;
	}

	/* enable anymotion trigger */
	trig.type = SENSOR_TRIG_DELTA;
	trig.chan = SENSOR_CHAN_ACCEL_XYZ;

	if (sensor_trigger_set(bmi160, &trig, trigger_hdlr) < 0) {
		printk("Cannot enable anymotion trigger.\n");
		return;
	}

	printk("Anymotion test: shake the device to get anymotion events.\n");
	do {
		/* wait a while */
		k_sleep(K_MSEC(SLEEPTIME));
		remaining_test_time -= SLEEPTIME;

	} while (remaining_test_time > 0);

	printk("Anymotion test: finished, removing anymotion trigger...\n");

	if (sensor_trigger_set(bmi160, &trig, NULL) < 0) {
		printk("Cannot remove anymotion trigger.\n");
		return;
	}
}

static void test_data_ready_trigger(struct device *bmi160)
{
	int32_t remaining_test_time = MAX_TEST_TIME;
	struct sensor_trigger trig;

	/* enable data ready trigger */
	trig.type = SENSOR_TRIG_DATA_READY;
	trig.chan = SENSOR_CHAN_ACCEL_XYZ;

	if (sensor_trigger_set(bmi160, &trig, trigger_hdlr) < 0) {
		printk("Cannot enable data ready trigger.\n");
		return;
	}

	printk("Data ready test:\n");
	do {
		/* wait a while */
		k_sleep(K_MSEC(SLEEPTIME));
		remaining_test_time -= SLEEPTIME;

	} while (remaining_test_time > 0);

	printk("Data ready test: finished, removing data ready trigger...\n");

	if (sensor_trigger_set(bmi160, &trig, NULL) < 0) {
		printk("Cannot remove data ready trigger.\n");
		return;
	}
}

static void test_trigger_mode(struct device *bmi160)
{
	struct sensor_value attr;

#if defined(CONFIG_BMI160_ACCEL_ODR_RUNTIME)
	/* set sampling frequency to 100Hz for accel */
	attr.val1 = 100;
	attr.val2 = 0;

	if (sensor_attr_set(bmi160, SENSOR_CHAN_ACCEL_XYZ,
			    SENSOR_ATTR_SAMPLING_FREQUENCY, &attr) < 0) {
		printk("Cannot set sampling frequency for accelerometer.\n");
		return;
	}
#endif

#if defined(CONFIG_BMI160_GYRO_ODR_RUNTIME)
	/* set sampling frequency to 100Hz for gyro */
	attr.val1 = 100;
	attr.val2 = 0;

	if (sensor_attr_set(bmi160, SENSOR_CHAN_GYRO_XYZ,
			    SENSOR_ATTR_SAMPLING_FREQUENCY, &attr) < 0) {
		printk("Cannot set sampling frequency for gyroscope.\n");
		return;
	}
#endif

	test_anymotion_trigger(bmi160);

	test_data_ready_trigger(bmi160);
}
#endif /* CONFIG_BMI160_TRIGGER */




extern uint8_t pbuf[1024];
extern uint8_t *pos;
void main(void)
{


	struct device *bmi160;
#if defined(CONFIG_BMI160_ACCEL_RANGE_RUNTIME) ||\
		defined(CONFIG_BMI160_GYRO_RANGE_RUNTIME)
	struct sensor_value attr;
#endif
	printk("IMU: Binding...\n");
	bmi160 = device_get_binding("SPI_1");
	if (!bmi160) {
		printk("Gyro: Device not found.\n");
		return;
	}
	else{
			printk("Gyro: Device found.\n");
		}

#if defined(CONFIG_BMI160_ACCEL_RANGE_RUNTIME)
	/*
	 * Set accelerometer range to +/- 16G. Since the sensor API needs SI
	 * units, convert the range to m/s^2.
	 */
	sensor_g_to_ms2(16, &attr);

	if (sensor_attr_set(bmi160, SENSOR_CHAN_ACCEL_XYZ,
			    SENSOR_ATTR_FULL_SCALE, &attr) < 0) {
		printk("Cannot set accelerometer range.\n");
		return;
	}
#endif

#if defined(CONFIG_BMI160_GYRO_RANGE_RUNTIME)
	/*
	 * Set gyro range to +/- 250 degrees/s. Since the sensor API needs SI
	 * units, convert the range to rad/s.
	 */
	sensor_degrees_to_rad(250, &attr);

	if (sensor_attr_set(bmi160, SENSOR_CHAN_GYRO_XYZ,
			    SENSOR_ATTR_FULL_SCALE, &attr) < 0) {
		printk("Cannot set gyro range.\n");
		return;
	}
#endif

#ifdef PERFORM_MANUAL_CALIBRATION
	/* manually adjust accelerometer and gyro offsets */
	if (manual_calibration(bmi160) < 0) {
		printk("Manual calibration failed.\n");
		return;
	}
#endif

#ifdef PERFORM_AUTO_CALIBRATION
	/* auto calibrate accelerometer and gyro */
	if (auto_calibration(bmi160) < 0) {
		printk("HW calibration failed.\n");
		return;
	}
#endif

	printk("Testing the polling mode.\n");
	test_polling_mode(bmi160);
	printk("Testing the polling mode finished.\n");

#ifdef CONFIG_BMI160_TRIGGER
	printk("Testing the trigger mode.\n");
	test_trigger_mode(bmi160);
	printk("Testing the trigger mode finished.\n");
#endif
}

prj.conf:

CONFIG_SPI=y
CONFIG_SPI_1=y
CONFIG_GPIO=y
CONFIG_SENSOR=y
CONFIG_BMI160=y
#CONFIG_BMI160_TRIGGER_OWN_THREAD=y
#CONFIG_BMI160_TRIGGER=y

#Debug Specific
CONFIG_DEBUG=y
CONFIG_LOG=y
CONFIG_LOG_DEFAULT_LEVEL=4
CONFIG_LOG_MAX_LEVEL=4
¨

overlay:

&spi1 {
	compatible = "nordic,nrf-spim";
	status = "okay";
	sck-pin = <7>;
	mosi-pin = <5>;
	miso-pin = <6>;
	cs-gpios =	<&gpio0  8 GPIO_ACTIVE_LOW>;

	accelerometer: bmi160@0 {
		compatible = "bosch,bmi160";
		status = "okay";
		reg = <0>;
	        spi-max-frequency = <1000000>; //try low speed first, datasheet max: 10mhz
		label = "BMI160";
		int-gpios = <&gpio0 29 GPIO_ACTIVE_HIGH>;
	};
};

The driver...

bmi160.h:

/* Bosch BMI160 inertial measurement unit header
 *
 * Copyright (c) 2016 Intel Corporation
 *
 * SPDX-License-Identifier: Apache-2.0
 */

#ifndef ZEPHYR_DRIVERS_SENSOR_BMI160_BMI160_H_
#define ZEPHYR_DRIVERS_SENSOR_BMI160_BMI160_H_

#include <drivers/gpio.h>
#include <drivers/sensor.h>
#include <drivers/spi.h>
#include <sys/util.h>

/* registers */
#define BMI160_REG_CHIPID		0x00
#define BMI160_REG_ERR			0x02
#define BMI160_REG_PMU_STATUS		0x03
#define BMI160_REG_DATA_MAG_X		0x04
#define BMI160_REG_DATA_MAG_Y		0x06
#define BMI160_REG_DATA_MAG_Z		0x08
#define BMI160_REG_DATA_RHALL		0x0A
#define BMI160_REG_DATA_GYR_X		0x0C
#define BMI160_REG_DATA_GYR_Y		0x0E
#define BMI160_REG_DATA_GYR_Z		0x10
#define BMI160_REG_DATA_ACC_X		0x12
#define BMI160_REG_DATA_ACC_Y		0x14
#define BMI160_REG_DATA_ACC_Z		0x16
#define BMI160_REG_SENSORTIME0		0x18
#define BMI160_REG_SENSORTIME1		0x19
#define BMI160_REG_SENSORTIME2		0x1A
#define BMI160_REG_STATUS		0x1B
#define BMI160_REG_INT_STATUS0		0x1C
#define BMI160_REG_INT_STATUS1		0x1D
#define BMI160_REG_INT_STATUS2		0x1E
#define BMI160_REG_INT_STATUS3		0x1F
#define BMI160_REG_TEMPERATURE0		0x20
#define BMI160_REG_TEMPERATURE1		0x21
#define BMI160_REG_FIFO_LENGTH0		0x22
#define BMI160_REG_FIFO_LENGTH1		0x23
#define BMI160_REG_FIFO_DATA		0x24
#define BMI160_REG_ACC_CONF		0x40
#define BMI160_REG_ACC_RANGE		0x41
#define BMI160_REG_GYR_CONF		0x42
#define BMI160_REG_GYR_RANGE		0x43
#define BMI160_REG_MAG_CONF		0x44
#define BMI160_REG_FIFO_DOWNS		0x45
#define BMI160_REG_FIFO_CONFIG0		0x46
#define BMI160_REG_FIFO_CONFIG1		0x47
#define BMI160_REG_MAG_IF0		0x4B
#define BMI160_REG_MAG_IF1		0x4C
#define BMI160_REG_MAG_IF2		0x4D
#define BMI160_REG_MAG_IF3		0x4E
#define BMI160_REG_MAG_IF4		0x4F
#define BMI160_REG_INT_EN0		0x50
#define BMI160_REG_INT_EN1		0x51
#define BMI160_REG_INT_EN2		0x52
#define BMI160_REG_INT_OUT_CTRL		0x53
#define BMI160_REG_INT_LATCH		0x54
#define BMI160_REG_INT_MAP0		0x55
#define BMI160_REG_INT_MAP1		0x56
#define BMI160_REG_INT_MAP2		0x57
#define BMI160_REG_INT_DATA0		0x58
#define BMI160_REG_INT_DATA1		0x59
#define BMI160_REG_INT_LOWHIGH0		0x5A
#define BMI160_REG_INT_LOWHIGH1		0x5B
#define BMI160_REG_INT_LOWHIGH2		0x5C
#define BMI160_REG_INT_LOWHIGH3		0x5D
#define BMI160_REG_INT_LOWHIGH4		0x5E
#define BMI160_REG_INT_MOTION0		0x5F
#define BMI160_REG_INT_MOTION1		0x60
#define BMI160_REG_INT_MOTION2		0x61
#define BMI160_REG_INT_MOTION3		0x62
#define BMI160_REG_INT_TAP0		0x63
#define BMI160_REG_INT_TAP1		0x64
#define BMI160_REG_INT_ORIENT0		0x65
#define BMI160_REG_INT_ORIENT1		0x66
#define BMI160_REG_INT_FLAT0		0x67
#define BMI160_REG_INT_FLAT1		0x68
#define BMI160_REG_FOC_CONF		0x69
#define BMI160_REG_CONF			0x6A
#define BMI160_REG_IF_CONF		0x6B
#define BMI160_REG_PMU_TRIGGER		0x6C
#define BMI160_REG_SELF_TEST		0x6D
#define BMI160_REG_NV_CONF		0x70
#define BMI160_REG_OFFSET_ACC_X		0x71
#define BMI160_REG_OFFSET_ACC_Y		0x72
#define BMI160_REG_OFFSET_ACC_Z		0x73
#define BMI160_REG_OFFSET_GYR_X		0x74
#define BMI160_REG_OFFSET_GYR_Y		0x75
#define BMI160_REG_OFFSET_GYR_Z		0x76
#define BMI160_REG_OFFSET_EN		0x77
#define BMI160_REG_STEP_CNT0		0x78
#define BMI160_REG_STEP_CNT1		0x79
#define BMI160_REG_STEP_CONF0		0x7A
#define BMI160_REG_STEP_CONF1		0x7B
#define BMI160_REG_CMD			0x7E

/* This is not a real register; reading it activates SPI on the BMI160 */
#define BMI160_SPI_START		0x7F

#define BMI160_REG_COUNT		0x80

/* Indicates a read operation; bit 7 is clear on write s*/
#define BMI160_REG_READ			BIT(7)
#define BMI160_REG_MASK			0x7f

/* bitfields */

/* BMI160_REG_ERR */
#define BMI160_ERR_FATAL		BIT(0)
#define BMI160_ERR_CODE			BIT(1)
#define BMI160_ERR_CODE_MASK		(0xf << 1)
#define BMI160_ERR_I2C_FAIL		BIT(5)
#define BMI160_ERR_DROP_CMD		BIT(6)
#define BMI160_ERR_MAG_DRDY		BIT(7)

/* BMI160_REG_PMU_STATUS */
#define BMI160_PMU_STATUS_MAG_MASK	0x3
#define BMI160_PMU_STATUS_MAG_POS	0
#define BMI160_PMU_STATUS_GYR_POS	2
#define BMI160_PMU_STATUS_GYR_MASK	(0x3 << 2)
#define BMI160_PMU_STATUS_ACC_POS	4
#define BMI160_PMU_STATUS_ACC_MASK	(0x3 << 4)

#define BMI160_PMU_SUSPEND		0
#define BMI160_PMU_NORMAL		1
#define BMI160_PMU_LOW_POWER		2
#define BMI160_PMU_FAST_START		3

/* BMI160_REG_STATUS */
#define BMI160_STATUS_GYR_SELFTEST	BIT(1)
#define BMI160_STATUS_MAG_MAN_OP	BIT(2)
#define BMI160_STATUS_FOC_RDY		BIT(3)
#define BMI160_STATUS_NVM_RDY		BIT(4)
#define BMI160_STATUS_MAG_DRDY		BIT(5)
#define BMI160_STATUS_GYR_DRDY		BIT(6)
#define BMI160_STATUS_ACC_DRDY		BIT(7)

/* BMI160_REG_INT_STATUS0 */
#define BMI160_INT_STATUS0_STEP		BIT(0)
#define BMI160_INT_STATUS0_SIGMOT	BIT(1)
#define BMI160_INT_STATUS0_ANYM		BIT(2)
#define BMI160_INT_STATUS0_PMU_TRIG	BIT(3)
#define BMI160_INT_STATUS0_D_TAP	BIT(4)
#define BMI160_INT_STATUS0_S_TAP	BIT(5)
#define BMI160_INT_STATUS0_ORIENT	BIT(6)
#define BMI160_INT_STATUS0_FLAT		BIT(7)

/* BMI160_REG_INT_STATUS1 */
#define BMI160_INT_STATUS1_HIGHG	BIT(2)
#define BMI160_INT_STATUS1_LOWG		BIT(3)
#define BMI160_INT_STATUS1_DRDY		BIT(4)
#define BMI160_INT_STATUS1_FFULL	BIT(5)
#define BMI160_INT_STATUS1_FWM		BIT(6)
#define BMI160_INT_STATUS1_NOMO		BIT(7)

/* BMI160_REG_INT_STATUS2 */
#define BMI160_INT_STATUS2_ANYM_FIRST_X BIT(0)
#define BMI160_INT_STATUS2_ANYM_FIRST_Y BIT(1)
#define BMI160_INT_STATUS2_ANYM_FIRST_Z BIT(2)
#define BMI160_INT_STATUS2_ANYM_SIGN	BIT(3)
#define BMI160_INT_STATUS2_TAP_FIRST_X	BIT(4)
#define BMI160_INT_STATUS2_TAP_FIRST_Y	BIT(5)
#define BMI160_INT_STATUS2_TAP_FIRST_Z	BIT(6)
#define BMI160_INT_STATUS2_TAP_SIGN	BIT(7)

/* BMI160_REG_INT_STATUS3 */
#define BMI160_INT_STATUS3_HIGH_FIRST_X BIT(0)
#define BMI160_INT_STATUS3_HIGH_FIRST_Y BIT(1)
#define BMI160_INT_STATUS3_HIGH_FIRST_Z BIT(2)
#define BMI160_INT_STATUS3_HIGH_SIGN	BIT(3)
#define BMI160_INT_STATUS3_ORIENT_1_0	BIT(4)
#define BMI160_INT_STATUS3_ORIENT_2	BIT(6)
#define BMI160_INT_STATUS3_FLAT		BIT(7)

/* BMI160_REG_ACC_CONF */
#define BMI160_ACC_CONF_ODR_POS		0
#define BMI160_ACC_CONF_ODR_MASK	0xF
#define BMI160_ACC_CONF_BWP_POS		4
#define BMI160_ACC_CONF_BWP_MASK	(0x7 << 4)
#define BMI160_ACC_CONF_US_POS		7
#define BMI160_ACC_CONF_US_MASK		BIT(7)

/* BMI160_REG_GYRO_CONF */
#define BMI160_GYR_CONF_ODR_POS	0
#define BMI160_GYR_CONF_ODR_MASK	0xF
#define BMI160_GYR_CONF_BWP_POS	4
#define BMI160_GYR_CONF_BWP_MASK	(0x3 << 4)

/* BMI160_REG_OFFSET_EN */
#define BMI160_GYR_OFS_EN_POS		7
#define BMI160_ACC_OFS_EN_POS		6
#define BMI160_GYR_MSB_OFS_Z_POS	4
#define BMI160_GYR_MSB_OFS_Z_MASK	(BIT(4) | BIT(5))
#define BMI160_GYR_MSB_OFS_Y_POS	2
#define BMI160_GYR_MSB_OFS_Y_MASK	(BIT(2) | BIT(3))
#define BMI160_GYR_MSB_OFS_X_POS	0
#define BMI160_GYR_MSB_OFS_X_MASK	(BIT(0) | BIT(1))

/* BMI160_REG_CMD */
#define BMI160_CMD_START_FOC		3
#define BMI160_CMD_PMU_ACC		0x10
#define BMI160_CMD_PMU_GYR		0x14
#define BMI160_CMD_PMU_MAG		0x18
#define BMI160_CMD_SOFT_RESET		0xB6

#define BMI160_CMD_PMU_BIT		0x10
#define BMI160_CMD_PMU_MASK		0x0c
#define BMI160_CMD_PMU_SHIFT		2
#define BMI160_CMD_PMU_VAL_MASK		0x3

/* BMI160_REG_FOC_CONF */
#define BMI160_FOC_ACC_Z_POS		0
#define BMI160_FOC_ACC_Y_POS		2
#define BMI160_FOC_ACC_X_POS		4
#define BMI160_FOC_GYR_EN_POS		6

/* BMI160_REG_INT_MOTION0 */
#define BMI160_ANYM_DUR_POS		0
#define BMI160_ANYM_DUR_MASK		0x3

/* BMI160_REG_INT_EN0 */
#define BMI160_INT_FLAT_EN		BIT(7)
#define BMI160_INT_ORIENT_EN		BIT(6)
#define BMI160_INT_S_TAP_EN		BIT(5)
#define BMI160_INT_D_TAP_EN		BIT(4)
#define BMI160_INT_ANYM_Z_EN		BIT(2)
#define BMI160_INT_ANYM_Y_EN		BIT(1)
#define BMI160_INT_ANYM_X_EN		BIT(0)
#define BMI160_INT_ANYM_MASK		(BIT(0) | BIT(1) | BIT(2))

/* BMI160_REG_INT_EN1 */
#define BMI160_INT_FWM_EN		BIT(6)
#define BMI160_INT_FFULL_EN		BIT(5)
#define BMI160_INT_DRDY_EN		BIT(4)
#define BMI160_INT_LOWG_EN		BIT(3)
#define BMI160_INT_HIGHG_Z_EN		BIT(2)
#define BMI160_INT_HIGHG_Y_EN		BIT(1)
#define BMI160_INT_HIGHG_X_EN		BIT(0)
#define BMI160_INT_HIGHG_MASK		(BIT(0) | BIT(1) | BIT(2))

/* BMI160_REG_INT_EN2 */
#define BMI160_INT_STEP_DET_EN		BIT(3)
#define BMI160_INT_STEP_NOMO_Z_EN	BIT(2)
#define BMI160_INT_STEP_NOMO_Y_EN	BIT(1)
#define BMI160_INT_STEP_NOMO_X_EN	BIT(0)
#define BMI160_INT_STEP_NOMO_MASK	(BIT(0) | BIT(1) | BIT(2))

/* BMI160_REG_INT_OUT_CTRL */
#define BMI160_INT2_OUT_EN		BIT(7)
#define BMI160_INT2_OD			BIT(6)
#define BMI160_INT2_LVL			BIT(5)
#define BMI160_INT2_EDGE_CTRL		BIT(4)
#define BMI160_INT1_OUT_EN		BIT(3)
#define BMI160_INT1_OD			BIT(2)
#define BMI160_INT1_LVL			BIT(1)
#define BMI160_INT1_EDGE_CTRL		BIT(0)

/* other */
#define BMI160_CHIP_ID			0xD1
#define BMI160_TEMP_OFFSET		23

/* allowed ODR values */
enum bmi160_odr {
	BMI160_ODR_25_32 = 1,
	BMI160_ODR_25_16,
	BMI160_ODR_25_8,
	BMI160_ODR_25_4,
	BMI160_ODR_25_2,
	BMI160_ODR_25,
	BMI160_ODR_50,
	BMI160_ODR_100,
	BMI160_ODR_200,
	BMI160_ODR_400,
	BMI160_ODR_800,
	BMI160_ODR_1600,
	BMI160_ODR_3200,
};

/* Range values for accelerometer */
#define BMI160_ACC_RANGE_2G		0x3
#define BMI160_ACC_RANGE_4G		0x5
#define BMI160_ACC_RANGE_8G		0x8
#define BMI160_ACC_RANGE_16G		0xC

/* Range values for gyro */
#define BMI160_GYR_RANGE_2000DPS	0
#define BMI160_GYR_RANGE_1000DPS	1
#define BMI160_GYR_RANGE_500DPS		2
#define BMI160_GYR_RANGE_250DPS		3
#define BMI160_GYR_RANGE_125DPS		4

#define BMI160_ACC_SCALE(range_g)	((2 * range_g * SENSOR_G) / 65536LL)
#define BMI160_GYR_SCALE(range_dps)\
				((2 * range_dps * SENSOR_PI) / 180LL / 65536LL)

/* default settings, based on menuconfig options */

/* make sure at least one sensor is active */
#if defined(CONFIG_BMI160_ACCEL_PMU_SUSPEND) &&\
		defined(CONFIG_BMI160_GYRO_PMU_SUSPEND)
#error "Error: You need to activate at least one sensor!"
#endif

#if defined(CONFIG_BMI160_ACCEL_PMU_RUNTIME) ||\
		defined(CONFIG_BMI160_ACCEL_PMU_NORMAL)
#	define BMI160_DEFAULT_PMU_ACC		BMI160_PMU_NORMAL
#elif defined(CONFIG_BMI160_ACCEL_PMU_SUSPEND)
#	define BMI160_DEFAULT_PMU_ACC		BMI160_PMU_SUSPEND
#else
#	define BMI160_DEFAULT_PMU_ACC		BMI160_PMU_LOW_POWER
#endif

#if defined(CONFIG_BMI160_GYRO_PMU_RUNTIME) ||\
		defined(CONFIG_BMI160_GYRO_PMU_NORMAL)
#	define BMI160_DEFAULT_PMU_GYR		BMI160_PMU_NORMAL
#elif defined(CONFIG_BMI160_GYRO_PMU_SUSPEND)
#	define BMI160_DEFAULT_PMU_GYR		BMI160_PMU_SUSPEND
#else
#	define BMI160_DEFAULT_PMU_GYR		BMI160_PMU_FAST_START
#endif

#if defined(CONFIG_BMI160_ACCEL_RANGE_RUNTIME) ||\
		defined(CONFIG_BMI160_ACCEL_RANGE_2G)
#	define BMI160_DEFAULT_RANGE_ACC		BMI160_ACC_RANGE_2G
#elif defined(CONFIG_BMI160_ACCEL_RANGE_4G)
#	define BMI160_DEFAULT_RANGE_ACC		BMI160_ACC_RANGE_4G
#elif defined(CONFIG_BMI160_ACCEL_RANGE_8G)
#	define BMI160_DEFAULT_RANGE_ACC		BMI160_ACC_RANGE_8G
#else
#	define BMI160_DEFAULT_RANGE_ACC		BMI160_ACC_RANGE_16G
#endif

#if defined(CONFIG_BMI160_GYRO_RANGE_RUNTIME) ||\
		defined(CONFIG_BMI160_GYRO_RANGE_2000DPS)
#	define BMI160_DEFAULT_RANGE_GYR		BMI160_GYR_RANGE_2000DPS
#elif defined(CONFIG_BMI160_GYRO_RANGE_1000DPS)
#	define BMI160_DEFAULT_RANGE_GYR		BMI160_GYR_RANGE_1000DPS
#elif defined(CONFIG_BMI160_GYRO_RANGE_500DPS)
#	define BMI160_DEFAULT_RANGE_GYR		BMI160_GYR_RANGE_500DPS
#elif defined(CONFIG_BMI160_GYRO_RANGE_250DPS)
#	define BMI160_DEFAULT_RANGE_GYR		BMI160_GYR_RANGE_250DPS
#else
#	define BMI160_DEFAULT_RANGE_GYR		BMI160_GYR_RANGE_125DPS
#endif

#if defined(CONFIG_BMI160_ACCEL_ODR_RUNTIME) ||\
		defined(CONFIG_BMI160_ACCEL_ODR_100)
#	define BMI160_DEFAULT_ODR_ACC		8
#elif defined(CONFIG_BMI160_ACCEL_ODR_25_32)
#	define BMI160_DEFAULT_ODR_ACC		1
#elif defined(CONFIG_BMI160_ACCEL_ODR_25_16)
#	define BMI160_DEFAULT_ODR_ACC		2
#elif defined(CONFIG_BMI160_ACCEL_ODR_25_8)
#	define BMI160_DEFAULT_ODR_ACC		3
#elif defined(CONFIG_BMI160_ACCEL_ODR_25_4)
#	define BMI160_DEFAULT_ODR_ACC		4
#elif defined(CONFIG_BMI160_ACCEL_ODR_25_2)
#	define BMI160_DEFAULT_ODR_ACC		5
#elif defined(CONFIG_BMI160_ACCEL_ODR_25)
#	define BMI160_DEFAULT_ODR_ACC		6
#elif defined(CONFIG_BMI160_ACCEL_ODR_50)
#	define BMI160_DEFAULT_ODR_ACC		7
#elif defined(CONFIG_BMI160_ACCEL_ODR_200)
#	define BMI160_DEFAULT_ODR_ACC		9
#elif defined(CONFIG_BMI160_ACCEL_ODR_400)
#	define BMI160_DEFAULT_ODR_ACC		10
#elif defined(CONFIG_BMI160_ACCEL_ODR_800)
#	define BMI160_DEFAULT_ODR_ACC		11
#else
#	define BMI160_DEFAULT_ODR_ACC		12
#endif

#if defined(CONFIG_BMI160_GYRO_ODR_RUNTIME) ||\
		defined(CONFIG_BMI160_GYRO_ODR_100)
#	define BMI160_DEFAULT_ODR_GYR		8
#elif defined(CONFIG_BMI160_GYRO_ODR_25)
#	define BMI160_DEFAULT_ODR_GYR		6
#elif defined(CONFIG_BMI160_GYRO_ODR_50)
#	define BMI160_DEFAULT_ODR_GYR		7
#elif defined(CONFIG_BMI160_GYRO_ODR_200)
#	define BMI160_DEFAULT_ODR_GYR		9
#elif defined(CONFIG_BMI160_GYRO_ODR_400)
#	define BMI160_DEFAULT_ODR_GYR		10
#elif defined(CONFIG_BMI160_GYRO_ODR_800)
#	define BMI160_DEFAULT_ODR_GYR		11
#elif defined(CONFIG_BMI160_GYRO_ODR_1600)
#	define BMI160_DEFAULT_ODR_GYR		12
#else
#	define BMI160_DEFAULT_ODR_GYR		13
#endif

/* end of default settings */

struct bmi160_range {
	uint16_t range;
	uint8_t reg_val;
};

#define BMI160_BUS_SPI		DT_ANY_INST_ON_BUS_STATUS_OKAY(spi)
#define BMI160_BUS_I2C		DT_ANY_INST_ON_BUS_STATUS_OKAY(i2c)

struct bmi160_bus_cfg {
	union {
#if BMI160_BUS_SPI
		const struct spi_config *spi_cfg;
#endif
#if BMI160_BUS_I2C
		uint16_t i2c_addr;
#endif
	};
};

typedef int (*bmi160_reg_read_fn)(const struct device *bus,
				  const struct bmi160_bus_cfg *bus_cfg,
				  uint8_t reg_addr, void *data, uint8_t len);
typedef int (*bmi160_reg_write_fn)(const struct device *bus,
				   const struct bmi160_bus_cfg *bus_cfg,
				   uint8_t reg_addr, void *data, uint8_t len);

struct bmi160_reg_io {
	bmi160_reg_read_fn read;
	bmi160_reg_write_fn write;
};

struct bmi160_cfg {
	struct bmi160_bus_cfg bus_cfg;
	const struct bmi160_reg_io *reg_io;
	const char *bus_label;
#if defined(CONFIG_BMI160_TRIGGER)
	const char *gpio_port;
	gpio_pin_t int_pin;
	gpio_dt_flags_t int_flags;
#endif
};

union bmi160_pmu_status {
	uint8_t raw;
	struct {
		uint8_t mag : 2;
		uint8_t gyr : 2;
		uint8_t acc : 2;
		uint8_t res : 2;
	};
};

#define BMI160_AXES			3

#if !defined(CONFIG_BMI160_GYRO_PMU_SUSPEND) && \
		!defined(CONFIG_BMI160_ACCEL_PMU_SUSPEND)
#	define BMI160_SAMPLE_SIZE	(2 * BMI160_AXES * sizeof(uint16_t))
#else
#	define BMI160_SAMPLE_SIZE	(BMI160_AXES * sizeof(uint16_t))
#endif

#if defined(CONFIG_BMI160_GYRO_PMU_SUSPEND)
#	define BMI160_SAMPLE_BURST_READ_ADDR	BMI160_REG_DATA_ACC_X
#	define BMI160_DATA_READY_BIT_MASK	(1 << 7)
#else
#	define BMI160_SAMPLE_BURST_READ_ADDR	BMI160_REG_DATA_GYR_X
#	define BMI160_DATA_READY_BIT_MASK	(1 << 6)
#endif

#define BMI160_BUF_SIZE			(BMI160_SAMPLE_SIZE)

/* Each sample has X, Y and Z */
union bmi160_sample {
	uint8_t raw[BMI160_BUF_SIZE];
	struct {
#if !defined(CONFIG_BMI160_GYRO_PMU_SUSPEND)
		uint16_t gyr[BMI160_AXES];
#endif
#if !defined(CONFIG_BMI160_ACCEL_PMU_SUSPEND)
		uint16_t acc[BMI160_AXES];
#endif
	} __packed;
};

struct bmi160_scale {
	uint16_t acc; /* micro m/s^2/lsb */
	uint16_t gyr; /* micro radians/s/lsb */
};

struct bmi160_data {
	const struct device *bus;
#if defined(CONFIG_BMI160_TRIGGER)
	const struct device *dev;
	const struct device *gpio;
	struct gpio_callback gpio_cb;
#endif
	union bmi160_pmu_status pmu_sts;
	union bmi160_sample sample;
	struct bmi160_scale scale;

#ifdef CONFIG_BMI160_TRIGGER_OWN_THREAD
	struct k_sem sem;
#endif

#ifdef CONFIG_BMI160_TRIGGER_GLOBAL_THREAD
	struct k_work work;
#endif

#ifdef CONFIG_BMI160_TRIGGER
#if !defined(CONFIG_BMI160_ACCEL_PMU_SUSPEND)
	sensor_trigger_handler_t handler_drdy_acc;
	sensor_trigger_handler_t handler_anymotion;
#endif
#if !defined(CONFIG_BMI160_GYRO_PMU_SUSPEND)
	sensor_trigger_handler_t handler_drdy_gyr;
#endif
#endif /* CONFIG_BMI160_TRIGGER */
};

static inline struct bmi160_data *to_data(const struct device *dev)
{
	return dev->data;
}

static inline const struct bmi160_cfg *to_config(const struct device *dev)
{
	return dev->config;
}

int bmi160_read(const struct device *dev, uint8_t reg_addr,
		void *data, uint8_t len);
int bmi160_byte_read(const struct device *dev, uint8_t reg_addr,
		     uint8_t *byte);
int bmi160_byte_write(const struct device *dev, uint8_t reg_addr,
		      uint8_t byte);
int bmi160_word_write(const struct device *dev, uint8_t reg_addr,
		      uint16_t word);
int bmi160_reg_field_update(const struct device *dev, uint8_t reg_addr,
			    uint8_t pos, uint8_t mask, uint8_t val);
static inline int bmi160_reg_update(const struct device *dev,
				    uint8_t reg_addr,
				    uint8_t mask, uint8_t val)
{
	return bmi160_reg_field_update(dev, reg_addr, 0, mask, val);
}
int bmi160_trigger_mode_init(const struct device *dev);
int bmi160_trigger_set(const struct device *dev,
		       const struct sensor_trigger *trig,
		       sensor_trigger_handler_t handler);
int bmi160_acc_slope_config(const struct device *dev,
			    enum sensor_attribute attr,
			    const struct sensor_value *val);
int32_t bmi160_acc_reg_val_to_range(uint8_t reg_val);
int32_t bmi160_gyr_reg_val_to_range(uint8_t reg_val);

#endif /* ZEPHYR_DRIVERS_SENSOR_BMI160_BMI160_H_ */

bmi160.c:

/* Bosch BMI160 inertial measurement unit driver
 *
 * Copyright (c) 2016 Intel Corporation
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Datasheet:
 * http://ae-bst.resource.bosch.com/media/_tech/media/datasheets/BST-BMI160-DS000-07.pdf
 */

#define DT_DRV_COMPAT bosch_bmi160

#include <init.h>
#include <drivers/i2c.h>
#include <drivers/sensor.h>
#include <sys/byteorder.h>
#include <kernel.h>
#include <sys/__assert.h>
#include <logging/log.h>

#include "bmi160.h"

//Quick and dirty fix to confirm communication with chip:
#define NRF91_BMI160_SPI_CS     8

struct spi_cs_control spi_cs = {
                .gpio_dev = DEVICE_DT_GET(DT_NODELABEL(gpio0)),
                .delay = 2,
                .gpio_pin = NRF91_BMI160_SPI_CS,
                .gpio_dt_flags = GPIO_ACTIVE_LOW
        };

LOG_MODULE_REGISTER(BMI160, CONFIG_SENSOR_LOG_LEVEL);

#if DT_NUM_INST_STATUS_OKAY(DT_DRV_COMPAT) == 0
#warning "BMI160 driver enabled without any devices"
#endif

#if BMI160_BUS_SPI
static int bmi160_transceive(const struct device *dev, uint8_t reg,
			     bool write, void *buf, size_t length)
{
	const struct bmi160_cfg *cfg = to_config(dev);
	struct bmi160_data *data = to_data(dev);
	const struct spi_buf tx_buf[2] = {
		{
			.buf = &reg,
			.len = 1
		},
		{
			.buf = buf,
			.len = length
		}
	};
	const struct spi_buf_set tx = {
		.buffers = tx_buf,
		.count = buf ? 2 : 1
	};

	if (!write) {
		const struct spi_buf_set rx = {
			.buffers = tx_buf,
			.count = 2
		};

		return spi_transceive(data->bus, cfg->bus_cfg.spi_cfg, &tx,
				      &rx);
	}

	return spi_write(data->bus, cfg->bus_cfg.spi_cfg, &tx);
}

int bmi160_read_spi(const struct device *dev,
		    const struct bmi160_bus_cfg *bus_config, uint8_t reg_addr,
		    void *buf, uint8_t len)
{
	return bmi160_transceive(dev, reg_addr | BMI160_REG_READ, false,
				 buf, len);
}

int bmi160_write_spi(const struct device *dev,
		     const struct bmi160_bus_cfg *bus_config,
		     uint8_t reg_addr, void *buf, uint8_t len)
{
	return bmi160_transceive(dev, reg_addr & BMI160_REG_MASK, true,
				 buf, len);
}

static const struct bmi160_reg_io bmi160_reg_io_spi = {
	.read = bmi160_read_spi,
	.write = bmi160_write_spi,
};
#endif /* BMI160_BUS_SPI */

#if BMI160_BUS_I2C
int bmi160_read_i2c(const struct device *dev,
		    const struct bmi160_bus_cfg *bus_config, uint8_t reg_addr,
		    void *buf, uint8_t len)
{
	struct bmi160_data *data = to_data(dev);

	return i2c_burst_read(data->bus, bus_config->i2c_addr, reg_addr, buf,
			      len);
}

int bmi160_write_i2c(const struct device *dev,
		     const struct bmi160_bus_cfg *bus_config,
		     uint8_t reg_addr, void *buf, uint8_t len)
{
	struct bmi160_data *data = to_data(dev);

	return i2c_burst_write(data->bus, bus_config->i2c_addr, reg_addr, buf,
			       len);
}

static const struct bmi160_reg_io bmi160_reg_io_i2c = {
	.read = bmi160_read_i2c,
	.write = bmi160_write_i2c,
};
#endif

int bmi160_read(const struct device *dev, uint8_t reg_addr, void *buf,
		uint8_t len)
{
	const struct bmi160_cfg *cfg = to_config(dev);

	return cfg->reg_io->read(dev, &cfg->bus_cfg, reg_addr, buf, len);
}

int bmi160_byte_read(const struct device *dev, uint8_t reg_addr, uint8_t *byte)
{
	return bmi160_read(dev, reg_addr, byte, 1);
}

static int bmi160_word_read(const struct device *dev, uint8_t reg_addr,
			    uint16_t *word)
{
	int rc;

	rc = bmi160_read(dev, reg_addr, word, 2);
	if (rc != 0) {
		return rc;
	}

	*word = sys_le16_to_cpu(*word);

	return 0;
}

int bmi160_write(const struct device *dev, uint8_t reg_addr, void *buf,
		 uint8_t len)
{
	const struct bmi160_cfg *cfg = to_config(dev);

	return cfg->reg_io->write(dev, &cfg->bus_cfg, reg_addr, buf, len);
}

int bmi160_byte_write(const struct device *dev, uint8_t reg_addr,
		      uint8_t byte)
{
	return bmi160_write(dev, reg_addr & BMI160_REG_MASK, &byte, 1);
}

int bmi160_word_write(const struct device *dev, uint8_t reg_addr,
		      uint16_t word)
{
	uint8_t tx_word[2] = {
		(uint8_t)(word & 0xff),
		(uint8_t)(word >> 8)
	};

	return bmi160_write(dev, reg_addr & BMI160_REG_MASK, tx_word, 2);
}

int bmi160_reg_field_update(const struct device *dev, uint8_t reg_addr,
			    uint8_t pos, uint8_t mask, uint8_t val)
{
	uint8_t old_val;

	if (bmi160_byte_read(dev, reg_addr, &old_val) < 0) {
		return -EIO;
	}

	return bmi160_byte_write(dev, reg_addr,
				 (old_val & ~mask) | ((val << pos) & mask));
}

static int bmi160_pmu_set(const struct device *dev,
			  union bmi160_pmu_status *pmu_sts)
{
	struct {
		uint8_t cmd;
		uint16_t delay_us; /* values taken from page 82 */
	} cmds[] = {
		{BMI160_CMD_PMU_MAG | pmu_sts->mag, 350},
		{BMI160_CMD_PMU_ACC | pmu_sts->acc, 3200},
		{BMI160_CMD_PMU_GYR | pmu_sts->gyr, 55000}
	};
	size_t i;

	for (i = 0; i < ARRAY_SIZE(cmds); i++) {
		union bmi160_pmu_status sts;
		bool pmu_set = false;

		if (bmi160_byte_write(dev, BMI160_REG_CMD, cmds[i].cmd) < 0) {
			return -EIO;
		}

		/*
		 * Cannot use a timer here since this is called from the
		 * init function and the timeouts were not initialized yet.
		 */
		k_busy_wait(cmds[i].delay_us);

		/* make sure the PMU_STATUS was set, though */
		do {
			if (bmi160_byte_read(dev, BMI160_REG_PMU_STATUS,
					     &sts.raw) < 0) {
				return -EIO;
			}

			if (i == 0) {
				pmu_set = (pmu_sts->mag == sts.mag);
			} else if (i == 1) {
				pmu_set = (pmu_sts->acc == sts.acc);
			} else {
				pmu_set = (pmu_sts->gyr == sts.gyr);
			}

		} while (!pmu_set);
	}

	/* set the undersampling flag for accelerometer */
	return bmi160_reg_field_update(dev, BMI160_REG_ACC_CONF,
				       BMI160_ACC_CONF_US_POS, BMI160_ACC_CONF_US_MASK,
				       pmu_sts->acc != BMI160_PMU_NORMAL);
}

#if defined(CONFIG_BMI160_GYRO_ODR_RUNTIME) ||\
	defined(CONFIG_BMI160_ACCEL_ODR_RUNTIME)
/*
 * Output data rate map with allowed frequencies:
 * freq = freq_int + freq_milli / 1000
 *
 * Since we don't need a finer frequency resolution than milliHz, use uint16_t
 * to save some flash.
 */
struct {
	uint16_t freq_int;
	uint16_t freq_milli; /* User should convert to uHz before setting the
			      * SENSOR_ATTR_SAMPLING_FREQUENCY attribute.
			      */
} bmi160_odr_map[] = {
	{0,    0  }, {0,     780}, {1,     562}, {3,    120}, {6,   250},
	{12,   500}, {25,    0  }, {50,    0  }, {100,  0  }, {200, 0  },
	{400,  0  }, {800,   0  }, {1600,  0  }, {3200, 0  },
};

static int bmi160_freq_to_odr_val(uint16_t freq_int, uint16_t freq_milli)
{
	size_t i;

	/* An ODR of 0 Hz is not allowed */
	if (freq_int == 0U && freq_milli == 0U) {
		return -EINVAL;
	}

	for (i = 0; i < ARRAY_SIZE(bmi160_odr_map); i++) {
		if (freq_int < bmi160_odr_map[i].freq_int ||
		    (freq_int == bmi160_odr_map[i].freq_int &&
		     freq_milli <= bmi160_odr_map[i].freq_milli)) {
			return i;
		}
	}

	return -EINVAL;
}
#endif

#if defined(CONFIG_BMI160_ACCEL_ODR_RUNTIME)
static int bmi160_acc_odr_set(const struct device *dev, uint16_t freq_int,
			      uint16_t freq_milli)
{
	struct bmi160_data *data = to_data(dev);
	int odr = bmi160_freq_to_odr_val(freq_int, freq_milli);

	if (odr < 0) {
		return odr;
	}

	/* some odr values cannot be set in certain power modes */
	if ((data->pmu_sts.acc == BMI160_PMU_NORMAL &&
	     odr < BMI160_ODR_25_2) ||
	    (data->pmu_sts.acc == BMI160_PMU_LOW_POWER &&
	    odr < BMI160_ODR_25_32) || odr > BMI160_ODR_1600) {
		return -ENOTSUP;
	}

	return bmi160_reg_field_update(dev, BMI160_REG_ACC_CONF,
				       BMI160_ACC_CONF_ODR_POS,
				       BMI160_ACC_CONF_ODR_MASK,
				       (uint8_t) odr);
}
#endif

static const struct bmi160_range bmi160_acc_range_map[] = {
	{2,	BMI160_ACC_RANGE_2G},
	{4,	BMI160_ACC_RANGE_4G},
	{8,	BMI160_ACC_RANGE_8G},
	{16,	BMI160_ACC_RANGE_16G},
};
#define BMI160_ACC_RANGE_MAP_SIZE	ARRAY_SIZE(bmi160_acc_range_map)

static const struct bmi160_range bmi160_gyr_range_map[] = {
	{2000,	BMI160_GYR_RANGE_2000DPS},
	{1000,	BMI160_GYR_RANGE_1000DPS},
	{500,	BMI160_GYR_RANGE_500DPS},
	{250,	BMI160_GYR_RANGE_250DPS},
	{125,	BMI160_GYR_RANGE_125DPS},
};
#define BMI160_GYR_RANGE_MAP_SIZE	ARRAY_SIZE(bmi160_gyr_range_map)

#if defined(CONFIG_BMI160_ACCEL_RANGE_RUNTIME) ||\
	defined(CONFIG_BMI160_GYRO_RANGE_RUNTIME)
static int32_t bmi160_range_to_reg_val(uint16_t range,
				       const struct bmi160_range *range_map,
				       uint16_t range_map_size)
{
	int i;

	for (i = 0; i < range_map_size; i++) {
		if (range <= range_map[i].range) {
			return range_map[i].reg_val;
		}
	}

	return -EINVAL;
}
#endif

static int32_t bmi160_reg_val_to_range(uint8_t reg_val,
				       const struct bmi160_range *range_map,
				       uint16_t range_map_size)
{
	int i;

	for (i = 0; i < range_map_size; i++) {
		if (reg_val == range_map[i].reg_val) {
			return range_map[i].range;
		}
	}

	return -EINVAL;
}

int32_t bmi160_acc_reg_val_to_range(uint8_t reg_val)
{
	return bmi160_reg_val_to_range(reg_val, bmi160_acc_range_map,
				       BMI160_ACC_RANGE_MAP_SIZE);
}

int32_t bmi160_gyr_reg_val_to_range(uint8_t reg_val)
{
	return bmi160_reg_val_to_range(reg_val, bmi160_gyr_range_map,
				       BMI160_GYR_RANGE_MAP_SIZE);
}

static int bmi160_do_calibration(const struct device *dev, uint8_t foc_conf)
{
	if (bmi160_byte_write(dev, BMI160_REG_FOC_CONF, foc_conf) < 0) {
		return -EIO;
	}

	if (bmi160_byte_write(dev, BMI160_REG_CMD, BMI160_CMD_START_FOC) < 0) {
		return -EIO;
	}

	k_busy_wait(250000); /* calibration takes a maximum of 250ms */

	return 0;
}

#if defined(CONFIG_BMI160_ACCEL_RANGE_RUNTIME)
static int bmi160_acc_range_set(const struct device *dev, int32_t range)
{
	struct bmi160_data *data = to_data(dev);
	int32_t reg_val = bmi160_range_to_reg_val(range,
						  bmi160_acc_range_map,
						  BMI160_ACC_RANGE_MAP_SIZE);

	if (reg_val < 0) {
		return reg_val;
	}

	if (bmi160_byte_write(dev, BMI160_REG_ACC_RANGE, reg_val & 0xff) < 0) {
		return -EIO;
	}

	data->scale.acc = BMI160_ACC_SCALE(range);

	return 0;
}
#endif

#if !defined(CONFIG_BMI160_ACCEL_PMU_SUSPEND)
/*
 * Accelerometer offset scale, taken from pg. 79, converted to micro m/s^2:
 *	3.9 * 9.80665 * 1000
 */
#define BMI160_ACC_OFS_LSB		38246
static int bmi160_acc_ofs_set(const struct device *dev,
			      enum sensor_channel chan,
			      const struct sensor_value *ofs)
{
	uint8_t reg_addr[] = {
		BMI160_REG_OFFSET_ACC_X,
		BMI160_REG_OFFSET_ACC_Y,
		BMI160_REG_OFFSET_ACC_Z
	};
	int i;
	int32_t ofs_u;
	int8_t reg_val;

	/* we need the offsets for all axis */
	if (chan != SENSOR_CHAN_ACCEL_XYZ) {
		return -ENOTSUP;
	}

	for (i = 0; i < BMI160_AXES; i++, ofs++) {
		/* convert ofset to micro m/s^2 */
		ofs_u = ofs->val1 * 1000000ULL + ofs->val2;
		reg_val = ofs_u / BMI160_ACC_OFS_LSB;

		if (bmi160_byte_write(dev, reg_addr[i], reg_val) < 0) {
			return -EIO;
		}
	}

	/* activate accel HW compensation */
	return bmi160_reg_field_update(dev, BMI160_REG_OFFSET_EN,
				       BMI160_ACC_OFS_EN_POS,
				       BIT(BMI160_ACC_OFS_EN_POS), 1);
}

static int  bmi160_acc_calibrate(const struct device *dev,
				 enum sensor_channel chan,
				 const struct sensor_value *xyz_calib_value)
{
	struct bmi160_data *data = to_data(dev);
	uint8_t foc_pos[] = {
		BMI160_FOC_ACC_X_POS,
		BMI160_FOC_ACC_Y_POS,
		BMI160_FOC_ACC_Z_POS,
	};
	int i;
	uint8_t reg_val = 0U;

	/* Calibration has to be done in normal mode. */
	if (data->pmu_sts.acc != BMI160_PMU_NORMAL) {
		return -ENOTSUP;
	}

	/*
	 * Hardware calibration is done knowing the expected values on all axis.
	 */
	if (chan != SENSOR_CHAN_ACCEL_XYZ) {
		return -ENOTSUP;
	}

	for (i = 0; i < BMI160_AXES; i++, xyz_calib_value++) {
		int32_t accel_g;
		uint8_t accel_val;

		accel_g = sensor_ms2_to_g(xyz_calib_value);
		if (accel_g == 0) {
			accel_val = 3U;
		} else if (accel_g == 1) {
			accel_val = 1U;
		} else if (accel_g == -1) {
			accel_val = 2U;
		} else {
			accel_val = 0U;
		}
		reg_val |= (accel_val << foc_pos[i]);
	}

	if (bmi160_do_calibration(dev, reg_val) < 0) {
		return -EIO;
	}

	/* activate accel HW compensation */
	return bmi160_reg_field_update(dev, BMI160_REG_OFFSET_EN,
				       BMI160_ACC_OFS_EN_POS,
				       BIT(BMI160_ACC_OFS_EN_POS), 1);
}

static int bmi160_acc_config(const struct device *dev,
			     enum sensor_channel chan,
			     enum sensor_attribute attr,
			     const struct sensor_value *val)
{
	switch (attr) {
#if defined(CONFIG_BMI160_ACCEL_RANGE_RUNTIME)
	case SENSOR_ATTR_FULL_SCALE:
		return bmi160_acc_range_set(dev, sensor_ms2_to_g(val));
#endif
#if defined(CONFIG_BMI160_ACCEL_ODR_RUNTIME)
	case SENSOR_ATTR_SAMPLING_FREQUENCY:
		return bmi160_acc_odr_set(dev, val->val1, val->val2 / 1000);
#endif
	case SENSOR_ATTR_OFFSET:
		return bmi160_acc_ofs_set(dev, chan, val);
	case SENSOR_ATTR_CALIB_TARGET:
		return bmi160_acc_calibrate(dev, chan, val);
#if defined(CONFIG_BMI160_TRIGGER)
	case SENSOR_ATTR_SLOPE_TH:
	case SENSOR_ATTR_SLOPE_DUR:
		return bmi160_acc_slope_config(dev, attr, val);
#endif
	default:
		LOG_DBG("Accel attribute not supported.");
		return -ENOTSUP;
	}

	return 0;
}
#endif /* !defined(CONFIG_BMI160_ACCEL_PMU_SUSPEND) */

#if defined(CONFIG_BMI160_GYRO_ODR_RUNTIME)
static int bmi160_gyr_odr_set(const struct device *dev, uint16_t freq_int,
			      uint16_t freq_milli)
{
	int odr = bmi160_freq_to_odr_val(freq_int, freq_milli);

	if (odr < 0) {
		return odr;
	}

	if (odr < BMI160_ODR_25 || odr > BMI160_ODR_3200) {
		return -ENOTSUP;
	}

	return bmi160_reg_field_update(dev, BMI160_REG_GYR_CONF,
				       BMI160_GYR_CONF_ODR_POS,
				       BMI160_GYR_CONF_ODR_MASK,
				       (uint8_t) odr);
}
#endif

#if defined(CONFIG_BMI160_GYRO_RANGE_RUNTIME)
static int bmi160_gyr_range_set(const struct device *dev, uint16_t range)
{
	struct bmi160_data *data = to_data(dev);
	int32_t reg_val = bmi160_range_to_reg_val(range,
						bmi160_gyr_range_map,
						BMI160_GYR_RANGE_MAP_SIZE);

	if (reg_val < 0) {
		return reg_val;
	}

	if (bmi160_byte_write(dev, BMI160_REG_GYR_RANGE, reg_val) < 0) {
		return -EIO;
	}

	data->scale.gyr = BMI160_GYR_SCALE(range);

	return 0;
}
#endif

#if !defined(CONFIG_BMI160_GYRO_PMU_SUSPEND)
/*
 * Gyro offset scale, taken from pg. 79, converted to micro rad/s:
 *		0.061 * (pi / 180) * 1000000, where pi = 3.141592
 */
#define BMI160_GYR_OFS_LSB		1065
static int bmi160_gyr_ofs_set(const struct device *dev,
			      enum sensor_channel chan,
			      const struct sensor_value *ofs)
{
	struct {
		uint8_t lsb_addr;
		uint8_t msb_pos;
	} ofs_desc[] = {
		{BMI160_REG_OFFSET_GYR_X, BMI160_GYR_MSB_OFS_X_POS},
		{BMI160_REG_OFFSET_GYR_Y, BMI160_GYR_MSB_OFS_Y_POS},
		{BMI160_REG_OFFSET_GYR_Z, BMI160_GYR_MSB_OFS_Z_POS},
	};
	int i;
	int32_t ofs_u;
	int16_t val;

	/* we need the offsets for all axis */
	if (chan != SENSOR_CHAN_GYRO_XYZ) {
		return -ENOTSUP;
	}

	for (i = 0; i < BMI160_AXES; i++, ofs++) {
		/* convert offset to micro rad/s */
		ofs_u = ofs->val1 * 1000000ULL + ofs->val2;

		val = ofs_u / BMI160_GYR_OFS_LSB;

		/*
		 * The gyro offset is a 10 bit two-complement value. Make sure
		 * the passed value is within limits.
		 */
		if (val < -512 || val > 512) {
			return -EINVAL;
		}

		/* write the LSB */
		if (bmi160_byte_write(dev, ofs_desc[i].lsb_addr,
				      val & 0xff) < 0) {
			return -EIO;
		}

		/* write the MSB */
		if (bmi160_reg_field_update(dev, BMI160_REG_OFFSET_EN,
					    ofs_desc[i].msb_pos,
					    0x3 << ofs_desc[i].msb_pos,
					    (val >> 8) & 0x3) < 0) {
			return -EIO;
		}
	}

	/* activate gyro HW compensation */
	return bmi160_reg_field_update(dev, BMI160_REG_OFFSET_EN,
				       BMI160_GYR_OFS_EN_POS,
				       BIT(BMI160_GYR_OFS_EN_POS), 1);
}

static int bmi160_gyr_calibrate(const struct device *dev,
				enum sensor_channel chan)
{
	struct bmi160_data *data = to_data(dev);

	ARG_UNUSED(chan);

	/* Calibration has to be done in normal mode. */
	if (data->pmu_sts.gyr != BMI160_PMU_NORMAL) {
		return -ENOTSUP;
	}

	if (bmi160_do_calibration(dev, BIT(BMI160_FOC_GYR_EN_POS)) < 0) {
		return -EIO;
	}

	/* activate gyro HW compensation */
	return bmi160_reg_field_update(dev, BMI160_REG_OFFSET_EN,
				       BMI160_GYR_OFS_EN_POS,
				       BIT(BMI160_GYR_OFS_EN_POS), 1);
}

static int bmi160_gyr_config(const struct device *dev,
			     enum sensor_channel chan,
			     enum sensor_attribute attr,
			     const struct sensor_value *val)
{
	switch (attr) {
#if defined(CONFIG_BMI160_GYRO_RANGE_RUNTIME)
	case SENSOR_ATTR_FULL_SCALE:
		return bmi160_gyr_range_set(dev, sensor_rad_to_degrees(val));
#endif
#if defined(CONFIG_BMI160_GYRO_ODR_RUNTIME)
	case SENSOR_ATTR_SAMPLING_FREQUENCY:
		return bmi160_gyr_odr_set(dev, val->val1, val->val2 / 1000);
#endif
	case SENSOR_ATTR_OFFSET:
		return bmi160_gyr_ofs_set(dev, chan, val);

	case SENSOR_ATTR_CALIB_TARGET:
		return bmi160_gyr_calibrate(dev, chan);

	default:
		LOG_DBG("Gyro attribute not supported.");
		return -ENOTSUP;
	}

	return 0;
}
#endif /* !defined(CONFIG_BMI160_GYRO_PMU_SUSPEND) */

static int bmi160_attr_set(const struct device *dev, enum sensor_channel chan,
			   enum sensor_attribute attr,
			   const struct sensor_value *val)
{
	switch (chan) {
#if !defined(CONFIG_BMI160_GYRO_PMU_SUSPEND)
	case SENSOR_CHAN_GYRO_X:
	case SENSOR_CHAN_GYRO_Y:
	case SENSOR_CHAN_GYRO_Z:
	case SENSOR_CHAN_GYRO_XYZ:
		return bmi160_gyr_config(dev, chan, attr, val);
#endif
#if !defined(CONFIG_BMI160_ACCEL_PMU_SUSPEND)
	case SENSOR_CHAN_ACCEL_X:
	case SENSOR_CHAN_ACCEL_Y:
	case SENSOR_CHAN_ACCEL_Z:
	case SENSOR_CHAN_ACCEL_XYZ:
		return bmi160_acc_config(dev, chan, attr, val);
#endif
	default:
		LOG_DBG("attr_set() not supported on this channel.");
		return -ENOTSUP;
	}

	return 0;
}

static int bmi160_sample_fetch(const struct device *dev,
			       enum sensor_channel chan)
{
	struct bmi160_data *data = to_data(dev);
	uint8_t status;
	size_t i;

	__ASSERT_NO_MSG(chan == SENSOR_CHAN_ALL);

	status = 0;
	while ((status & BMI160_DATA_READY_BIT_MASK) == 0) {

		if (bmi160_byte_read(dev, BMI160_REG_STATUS, &status) < 0) {
			return -EIO;
		}
	}

	if (bmi160_read(dev, BMI160_SAMPLE_BURST_READ_ADDR, data->sample.raw,
			BMI160_BUF_SIZE) < 0) {
		return -EIO;
	}

	/* convert samples to cpu endianness */
	for (i = 0; i < BMI160_SAMPLE_SIZE; i += 2) {
		uint16_t *sample =
			(uint16_t *) &data->sample.raw[i];

		*sample = sys_le16_to_cpu(*sample);
	}

	return 0;
}

static void bmi160_to_fixed_point(int16_t raw_val, uint16_t scale,
				  struct sensor_value *val)
{
	int32_t converted_val;

	/*
	 * maximum converted value we can get is: max(raw_val) * max(scale)
	 *	max(raw_val) = +/- 2^15
	 *	max(scale) = 4785
	 *	max(converted_val) = 156794880 which is less than 2^31
	 */
	converted_val = raw_val * scale;
	val->val1 = converted_val / 1000000;
	val->val2 = converted_val % 1000000;
}

static void bmi160_channel_convert(enum sensor_channel chan,
				   uint16_t scale,
				   uint16_t *raw_xyz,
				   struct sensor_value *val)
{
	int i;
	uint8_t ofs_start, ofs_stop;

	switch (chan) {
	case SENSOR_CHAN_ACCEL_X:
	case SENSOR_CHAN_GYRO_X:
		ofs_start = ofs_stop = 0U;
		break;
	case SENSOR_CHAN_ACCEL_Y:
	case SENSOR_CHAN_GYRO_Y:
		ofs_start = ofs_stop = 1U;
		break;
	case SENSOR_CHAN_ACCEL_Z:
	case SENSOR_CHAN_GYRO_Z:
		ofs_start = ofs_stop = 2U;
		break;
	default:
		ofs_start = 0U; ofs_stop = 2U;
		break;
	}

	for (i = ofs_start; i <= ofs_stop ; i++, val++) {
		bmi160_to_fixed_point(raw_xyz[i], scale, val);
	}
}

#if !defined(CONFIG_BMI160_GYRO_PMU_SUSPEND)
static inline void bmi160_gyr_channel_get(const struct device *dev,
					  enum sensor_channel chan,
					  struct sensor_value *val)
{
	struct bmi160_data *data = to_data(dev);

	bmi160_channel_convert(chan, data->scale.gyr,
			       data->sample.gyr, val);
}
#endif

#if !defined(CONFIG_BMI160_ACCEL_PMU_SUSPEND)
static inline void bmi160_acc_channel_get(const struct device *dev,
					  enum sensor_channel chan,
					  struct sensor_value *val)
{
	struct bmi160_data *data = to_data(dev);

	bmi160_channel_convert(chan, data->scale.acc,
			       data->sample.acc, val);
}
#endif

static int bmi160_temp_channel_get(const struct device *dev,
				   struct sensor_value *val)
{
	uint16_t temp_raw = 0U;
	int32_t temp_micro = 0;
	struct bmi160_data *data = to_data(dev);

	if (data->pmu_sts.raw == 0U) {
		return -EINVAL;
	}

	if (bmi160_word_read(dev, BMI160_REG_TEMPERATURE0, &temp_raw) < 0) {
		return -EIO;
	}

	/* the scale is 1/2^9/LSB = 1953 micro degrees */
	temp_micro = BMI160_TEMP_OFFSET * 1000000ULL + temp_raw * 1953ULL;

	val->val1 = temp_micro / 1000000ULL;
	val->val2 = temp_micro % 1000000ULL;

	return 0;
}

static int bmi160_channel_get(const struct device *dev,
			      enum sensor_channel chan,
			      struct sensor_value *val)
{
	switch (chan) {
#if !defined(CONFIG_BMI160_GYRO_PMU_SUSPEND)
	case SENSOR_CHAN_GYRO_X:
	case SENSOR_CHAN_GYRO_Y:
	case SENSOR_CHAN_GYRO_Z:
	case SENSOR_CHAN_GYRO_XYZ:
		bmi160_gyr_channel_get(dev, chan, val);
		return 0;
#endif
#if !defined(CONFIG_BMI160_ACCEL_PMU_SUSPEND)
	case SENSOR_CHAN_ACCEL_X:
	case SENSOR_CHAN_ACCEL_Y:
	case SENSOR_CHAN_ACCEL_Z:
	case SENSOR_CHAN_ACCEL_XYZ:
		bmi160_acc_channel_get(dev, chan, val);
		return 0;
#endif
	case SENSOR_CHAN_DIE_TEMP:
		return bmi160_temp_channel_get(dev, val);
	default:
		LOG_DBG("Channel not supported.");
		return -ENOTSUP;
	}

	return 0;
}

static const struct sensor_driver_api bmi160_api = {
	.attr_set = bmi160_attr_set,
#ifdef CONFIG_BMI160_TRIGGER
	.trigger_set = bmi160_trigger_set,
#endif
	.sample_fetch = bmi160_sample_fetch,
	.channel_get = bmi160_channel_get,
};

int bmi160_init(const struct device *dev)
{

//turn on voltage regulator before bmi160 interaction:
const struct device *myPort;
minPort = device_get_binding(DT_LABEL(DT_NODELABEL(gpio0)));
gpio_pin_configure(minPort, 20, GPIO_OUTPUT_HIGH);

//stabilize power:
	k_sleep(K_MSEC(500));

	const struct bmi160_cfg *cfg = to_config(dev);
	struct bmi160_data *data = to_data(dev);
	uint8_t val = 0U;
	int32_t acc_range, gyr_range;


	data->bus = device_get_binding(cfg->bus_label);
	if (!data->bus) {
		LOG_DBG("SPI master controller not found: %s.", cfg->bus_label);
		return -EINVAL;
	}
	else{
		LOG_INF("SPI master controller found: %s.", cfg->bus_label);
	}

	/* reboot the chip */
	if (bmi160_byte_write(dev, BMI160_REG_CMD, BMI160_CMD_SOFT_RESET) < 0) {
		LOG_DBG("Cannot reboot chip.");
		return -EIO;
	}
	else{
		LOG_INF("reboot OK.");
	}

	k_busy_wait(1000);

	/* do a dummy read from 0x7F to activate SPI */
	if (bmi160_byte_read(dev, BMI160_SPI_START, &val) < 0) {
		LOG_DBG("Cannot read from 0x7F..");
		return -EIO;
	}
	else{
		LOG_INF("Can read from 0x7F..");
	}

	k_busy_wait(100);


	if (bmi160_byte_read(dev, BMI160_REG_CHIPID, &val) < 0) {
		LOG_DBG("Failed to read chip id.");
		return -EIO;
	}
	else{
		LOG_INF("Read chip OK.");
	}
	k_sleep(K_MSEC(100));

	if (val != BMI160_CHIP_ID) {
		LOG_DBG("Unsupported chip detected (0x%x)!", val);
		return -ENODEV;
	}
	else{
		LOG_INF("CHIP_ID OK (0x%x)!", val);
	}
	k_sleep(K_MSEC(100));

	/* set default PMU for gyro, accelerometer */
	data->pmu_sts.gyr = BMI160_DEFAULT_PMU_GYR;
	data->pmu_sts.acc = BMI160_DEFAULT_PMU_ACC;
	/* compass not supported, yet */
	data->pmu_sts.mag = BMI160_PMU_SUSPEND;

	/*
	 * The next command will take around 100ms (contains some necessary busy
	 * waits), but we cannot do it in a separate thread since we need to
	 * guarantee the BMI is up and running, before the app's main() is
	 * called.
	 */
	if (bmi160_pmu_set(dev, &data->pmu_sts) < 0) {
		LOG_DBG("Failed to set power mode.");
		return -EIO;
	}
	else{
		LOG_INF("set power mode ok.");
	}

	/* set accelerometer default range */
	if (bmi160_byte_write(dev, BMI160_REG_ACC_RANGE,
				BMI160_DEFAULT_RANGE_ACC) < 0) {
		LOG_DBG("Cannot set default range for accelerometer.");
		return -EIO;
	}
	else{
		LOG_INF("set default accelerometer range ok.");
	}

	acc_range = bmi160_acc_reg_val_to_range(BMI160_DEFAULT_RANGE_ACC);

	data->scale.acc = BMI160_ACC_SCALE(acc_range);

	/* set gyro default range */
	if (bmi160_byte_write(dev, BMI160_REG_GYR_RANGE,
			      BMI160_DEFAULT_RANGE_GYR) < 0) {
		LOG_DBG("Cannot set default range for gyroscope.");
		return -EIO;
	}
	else{
		LOG_INF("set default gyroscope range ok.");
	}

	gyr_range = bmi160_gyr_reg_val_to_range(BMI160_DEFAULT_RANGE_GYR);

	data->scale.gyr = BMI160_GYR_SCALE(gyr_range);

	if (bmi160_reg_field_update(dev, BMI160_REG_ACC_CONF,
				    BMI160_ACC_CONF_ODR_POS,
				    BMI160_ACC_CONF_ODR_MASK,
				    BMI160_DEFAULT_ODR_ACC) < 0) {
		LOG_DBG("Failed to set accel's default ODR.");
		return -EIO;
	}
	else{
		LOG_INF("set accel's default ODR ok.");
	}

	if (bmi160_reg_field_update(dev, BMI160_REG_GYR_CONF,
				    BMI160_GYR_CONF_ODR_POS,
				    BMI160_GYR_CONF_ODR_MASK,
				    BMI160_DEFAULT_ODR_GYR) < 0) {
		LOG_DBG("Failed to set gyro's default ODR.");
		return -EIO;
	}
	else{
		LOG_INF("set set gyro's default ODR ok.");
	}

#ifdef CONFIG_BMI160_TRIGGER
	if (bmi160_trigger_mode_init(dev) < 0) {
		LOG_DBG("Cannot set up trigger mode.");
		return -EINVAL;
	}
	else{
		LOG_INF("set trigger mode ok.");
	}
#endif

	return 0;
}

#if defined(CONFIG_BMI160_TRIGGER)
#define BMI160_TRIGGER_CFG(inst)					\
	.gpio_port = DT_INST_GPIO_LABEL(inst, int_gpios),		\
	.int_pin = DT_INST_GPIO_PIN(inst, int_gpios),			\
	.int_flags = DT_INST_GPIO_FLAGS(inst, int_gpios),
#else
#define BMI160_TRIGGER_CFG(inst)
#endif

#define BMI160_DEVICE_INIT(inst)					\
	DEVICE_DT_INST_DEFINE(inst, bmi160_init, device_pm_control_nop,	\
		&bmi160_data_##inst, &bmi160_cfg_##inst,		\
		POST_KERNEL, CONFIG_SENSOR_INIT_PRIORITY,		\
		&bmi160_api);

/* Instantiation macros used when a device is on a SPI bus */
#define BMI160_DEFINE_SPI(inst)						\
	static struct bmi160_data bmi160_data_##inst;			\
	static const struct bmi160_cfg bmi160_cfg_##inst = {		\
		BMI160_TRIGGER_CFG(inst)				\
		.reg_io = &bmi160_reg_io_spi,				\
		.bus_label = DT_INST_BUS_LABEL(inst),			\
		.bus_cfg = {						\
			.spi_cfg = (&(struct spi_config) {		\
				.operation = SPI_WORD_SET(8),		\
				.frequency = DT_INST_PROP(inst,		\
					spi_max_frequency),		\
				.slave = DT_INST_REG_ADDR(inst),	\
				.cs = &spi_cs,	                       \
			}),						\
		},							\
	};								\
	BMI160_DEVICE_INIT(inst)

/* Instantiation macros used when a device is on an I2C bus */
#define BMI160_CONFIG_I2C(inst)						\
	{								\
		.bus_label = DT_INST_BUS_LABEL(inst),			\
		.reg_io = &bmi160_reg_io_i2c,				\
		.bus_cfg =  { .i2c_addr = DT_INST_REG_ADDR(inst), }	\
	}

#define BMI160_DEFINE_I2C(inst)						\
	static struct bmi160_data bmi160_data_##inst;			\
	static const struct bmi160_cfg bmi160_cfg_##inst =	\
		BMI160_CONFIG_I2C(inst);				\
	BMI160_DEVICE_INIT(inst)

/*
 * Main instantiation macro. Use of COND_CODE_1() selects the right
 * bus-specific macro at preprocessor time.
 */
#define BMI160_DEFINE(inst)						\
	COND_CODE_1(DT_INST_ON_BUS(inst, spi),				\
		    (BMI160_DEFINE_SPI(inst)),				\
		    (BMI160_DEFINE_I2C(inst)))

DT_INST_FOREACH_STATUS_OKAY(BMI160_DEFINE)

bmi160_trigger.c:

/* Bosch BMI160 inertial measurement unit driver, trigger implementation
 *
 * Copyright (c) 2016 Intel Corporation
 *
 * SPDX-License-Identifier: Apache-2.0
 */

#include <kernel.h>
#include <drivers/sensor.h>
#include <drivers/gpio.h>

#include "bmi160.h"


#include <logging/log.h>
LOG_MODULE_DECLARE(BMI160, CONFIG_SENSOR_LOG_LEVEL);

static void bmi160_handle_anymotion(const struct device *dev)
{
	struct bmi160_data *data = to_data(dev);
	struct sensor_trigger anym_trigger = {
		.type = SENSOR_TRIG_DELTA,
		.chan = SENSOR_CHAN_ACCEL_XYZ,
	};

	if (data->handler_anymotion) {
		data->handler_anymotion(dev, &anym_trigger);
	}
}

static void bmi160_handle_drdy(const struct device *dev, uint8_t status)
{
	struct bmi160_data *data = to_data(dev);
	struct sensor_trigger drdy_trigger = {
		.type = SENSOR_TRIG_DATA_READY,
	};

#if !defined(CONFIG_BMI160_ACCEL_PMU_SUSPEND)
	if (data->handler_drdy_acc && (status & BMI160_STATUS_ACC_DRDY)) {
		drdy_trigger.chan = SENSOR_CHAN_ACCEL_XYZ;
		data->handler_drdy_acc(dev, &drdy_trigger);
	}
#endif

#if !defined(CONFIG_BMI160_GYRO_PMU_SUSPEND)
	if (data->handler_drdy_gyr && (status & BMI160_STATUS_GYR_DRDY)) {
		drdy_trigger.chan = SENSOR_CHAN_GYRO_XYZ;
		data->handler_drdy_gyr(dev, &drdy_trigger);
	}
#endif
}

static void bmi160_handle_interrupts(const struct device *dev)
{
	union {
		uint8_t raw[6];
		struct {
			uint8_t dummy; /* spi related dummy byte */
			uint8_t status;
			uint8_t int_status[4];
		};
	} buf;

	if (bmi160_read(dev, BMI160_REG_STATUS, buf.raw, sizeof(buf)) < 0) {
		return;
	}

	if ((buf.int_status[0] & BMI160_INT_STATUS0_ANYM) &&
	    (buf.int_status[2] & (BMI160_INT_STATUS2_ANYM_FIRST_X |
				  BMI160_INT_STATUS2_ANYM_FIRST_Y |
				  BMI160_INT_STATUS2_ANYM_FIRST_Z))) {
		bmi160_handle_anymotion(dev);
	}

	if (buf.int_status[1] & BMI160_INT_STATUS1_DRDY) {
		bmi160_handle_drdy(dev, buf.status);
	}

}

#ifdef CONFIG_BMI160_TRIGGER_OWN_THREAD
static K_KERNEL_STACK_DEFINE(bmi160_thread_stack, CONFIG_BMI160_THREAD_STACK_SIZE);
static struct k_thread bmi160_thread;

static void bmi160_thread_main(struct bmi160_data *data)
{
	while (1) {
		k_sem_take(&data->sem, K_FOREVER);
		bmi160_handle_interrupts(data->dev);
	}
}
#endif

#ifdef CONFIG_BMI160_TRIGGER_GLOBAL_THREAD
static void bmi160_work_handler(struct k_work *work)
{
	struct bmi160_data *data = CONTAINER_OF(work, struct bmi160_data, work);

	bmi160_handle_interrupts(data->dev);
}
#endif

extern struct bmi160_data bmi160_data;

static void bmi160_gpio_callback(const struct device *port,
				 struct gpio_callback *cb, uint32_t pin)
{
	struct bmi160_data *data =
		CONTAINER_OF(cb, struct bmi160_data, gpio_cb);

	ARG_UNUSED(port);
	ARG_UNUSED(pin);

#if defined(CONFIG_BMI160_TRIGGER_OWN_THREAD)
	k_sem_give(&data->sem);
#elif defined(CONFIG_BMI160_TRIGGER_GLOBAL_THREAD)
	k_work_submit(&data->work);
#endif
}

static int bmi160_trigger_drdy_set(const struct device *dev,
				   enum sensor_channel chan,
				   sensor_trigger_handler_t handler)
{
	struct bmi160_data *data = to_data(dev);
	uint8_t drdy_en = 0U;

#if !defined(CONFIG_BMI160_ACCEL_PMU_SUSPEND)
	if (chan == SENSOR_CHAN_ACCEL_XYZ) {
		data->handler_drdy_acc = handler;
	}

	if (data->handler_drdy_acc) {
		drdy_en = BMI160_INT_DRDY_EN;
	}
#endif

#if !defined(CONFIG_BMI160_GYRO_PMU_SUSPEND)
	if (chan == SENSOR_CHAN_GYRO_XYZ) {
		data->handler_drdy_gyr = handler;
	}

	if (data->handler_drdy_gyr) {
		drdy_en = BMI160_INT_DRDY_EN;
	}
#endif

	if (bmi160_reg_update(dev, BMI160_REG_INT_EN1,
			      BMI160_INT_DRDY_EN, drdy_en) < 0) {
		return -EIO;
	}

	return 0;
}

#if !defined(CONFIG_BMI160_ACCEL_PMU_SUSPEND)
static int bmi160_trigger_anym_set(const struct device *dev,
				   sensor_trigger_handler_t handler)
{
	struct bmi160_data *data = to_data(dev);
	uint8_t anym_en = 0U;

	data->handler_anymotion = handler;

	if (handler) {
		anym_en = BMI160_INT_ANYM_X_EN |
			  BMI160_INT_ANYM_Y_EN |
			  BMI160_INT_ANYM_Z_EN;
	}

	if (bmi160_reg_update(dev, BMI160_REG_INT_EN0,
			      BMI160_INT_ANYM_MASK, anym_en) < 0) {
		return -EIO;
	}

	return 0;
}

static int bmi160_trigger_set_acc(const struct device *dev,
				  const struct sensor_trigger *trig,
				  sensor_trigger_handler_t handler)
{
	if (trig->type == SENSOR_TRIG_DATA_READY) {
		return bmi160_trigger_drdy_set(dev, trig->chan, handler);
	} else if (trig->type == SENSOR_TRIG_DELTA) {
		return bmi160_trigger_anym_set(dev, handler);
	}

	return -ENOTSUP;
}

int bmi160_acc_slope_config(const struct device *dev,
			    enum sensor_attribute attr,
			    const struct sensor_value *val)
{
	uint8_t acc_range_g, reg_val;
	uint32_t slope_th_ums2;

	if (attr == SENSOR_ATTR_SLOPE_TH) {
		if (bmi160_byte_read(dev, BMI160_REG_ACC_RANGE, &reg_val) < 0) {
			return -EIO;
		}

		acc_range_g = bmi160_acc_reg_val_to_range(reg_val);

		slope_th_ums2 = val->val1 * 1000000 + val->val2;

		/* make sure the provided threshold does not exceed range / 2 */
		if (slope_th_ums2 > (acc_range_g / 2 * SENSOR_G)) {
			return -EINVAL;
		}

		reg_val = (slope_th_ums2 - 1) * 512U / (acc_range_g * SENSOR_G);

		if (bmi160_byte_write(dev, BMI160_REG_INT_MOTION1,
				      reg_val) < 0) {
			return -EIO;
		}
	} else { /* SENSOR_ATTR_SLOPE_DUR */
		/* slope duration is measured in number of samples */
		if (val->val1 < 1 || val->val1 > 4) {
			return -ENOTSUP;
		}

		if (bmi160_reg_field_update(dev, BMI160_REG_INT_MOTION0,
					    BMI160_ANYM_DUR_POS,
					    BMI160_ANYM_DUR_MASK,
					    val->val1) < 0) {
			return -EIO;
		}
	}

	return 0;
}
#endif

#if !defined(CONFIG_BMI160_GYRO_PMU_SUSPEND)
static int bmi160_trigger_set_gyr(const struct device *dev,
				  const struct sensor_trigger *trig,
				  sensor_trigger_handler_t handler)
{
	if (trig->type == SENSOR_TRIG_DATA_READY) {
		return bmi160_trigger_drdy_set(dev, trig->chan, handler);
	}

	return -ENOTSUP;
}
#endif

int bmi160_trigger_set(const struct device *dev,
		       const struct sensor_trigger *trig,
		       sensor_trigger_handler_t handler)
{
#if !defined(CONFIG_BMI160_ACCEL_PMU_SUSPEND)
	if (trig->chan == SENSOR_CHAN_ACCEL_XYZ) {
		return bmi160_trigger_set_acc(dev, trig, handler);
	}
#endif
#if !defined(CONFIG_BMI160_GYRO_PMU_SUSPEND)
	if (trig->chan == SENSOR_CHAN_GYRO_XYZ) {
		return bmi160_trigger_set_gyr(dev, trig, handler);
	}
#endif
	return -ENOTSUP;
}

int bmi160_trigger_mode_init(const struct device *dev)
{
	struct bmi160_data *data = to_data(dev);
	const struct bmi160_cfg *cfg = to_config(dev);

	data->gpio = device_get_binding((char *)cfg->gpio_port);
	if (!data->gpio) {
		LOG_DBG("Gpio controller %s not found.", cfg->gpio_port);
		return -EINVAL;
	}

	data->dev = dev;

#if defined(CONFIG_BMI160_TRIGGER_OWN_THREAD)
	k_sem_init(&data->sem, 0, K_SEM_MAX_LIMIT);
//	k_sem_init(&data->sem, 0, UINT_MAX);

	k_thread_create(&bmi160_thread, bmi160_thread_stack,
			CONFIG_BMI160_THREAD_STACK_SIZE,
			(k_thread_entry_t)bmi160_thread_main,
			data, NULL, NULL,
			K_PRIO_COOP(CONFIG_BMI160_THREAD_PRIORITY),
			 0, K_NO_WAIT);
#elif defined(CONFIG_BMI160_TRIGGER_GLOBAL_THREAD)
	data->work.handler = bmi160_work_handler;
#endif

	/* map all interrupts to INT1 pin */
	if (bmi160_word_write(dev, BMI160_REG_INT_MAP0, 0xf0ff) < 0) {
		LOG_DBG("Failed to map interrupts.");
		return -EIO;
	}

	gpio_pin_configure(data->gpio, cfg->int_pin,
			   GPIO_INPUT | cfg->int_flags);

	gpio_init_callback(&data->gpio_cb,
			   bmi160_gpio_callback,
			   BIT(cfg->int_pin));

	gpio_add_callback(data->gpio, &data->gpio_cb);
	gpio_pin_interrupt_configure(data->gpio, cfg->int_pin,
				     GPIO_INT_EDGE_TO_ACTIVE);

	return bmi160_byte_write(dev, BMI160_REG_INT_OUT_CTRL,
				 BMI160_INT1_OUT_EN | BMI160_INT1_EDGE_CTRL);
}

Kconfig:

 # Bosch BMI160 inertial measurement configuration options

# Copyright (c) 2016 Intel Corporation
# SPDX-License-Identifier: Apache-2.0

menuconfig BMI160
	bool "Bosch BMI160 inertial measurement unit"
	depends on SPI
	help
	  Enable Bosch BMI160 inertial measurement unit that provides acceleration
	  and angular rate measurements.

if BMI160

choice
	prompt "Trigger mode"
	default BMI160_TRIGGER_GLOBAL_THREAD
	help
	  Specify the type of triggering to be used by the driver.

config BMI160_TRIGGER_NONE
	bool "No trigger"

config BMI160_TRIGGER_GLOBAL_THREAD
	bool "Use global thread"
	select BMI160_TRIGGER

config BMI160_TRIGGER_OWN_THREAD
	bool "Use own thread"
	select BMI160_TRIGGER
endchoice

config BMI160_TRIGGER
	bool

config BMI160_THREAD_PRIORITY
	int "Own thread priority"
	depends on BMI160_TRIGGER_OWN_THREAD
	default 10
	help
	  The priority of the thread used for handling interrupts.

config BMI160_THREAD_STACK_SIZE
	int "Own thread stack size"
	depends on BMI160_TRIGGER_OWN_THREAD
	default 1024
	help
	  The thread stack size.

choice
	prompt "Accelerometer power mode"
	default BMI160_ACCEL_PMU_RUNTIME

config BMI160_ACCEL_PMU_RUNTIME
	bool "Set at runtime."

config BMI160_ACCEL_PMU_SUSPEND
	bool "suspended/not used"

config BMI160_ACCEL_PMU_NORMAL
	bool "normal"

config BMI160_ACCEL_PMU_LOW_POWER
	bool "low power"
endchoice

choice
	prompt "Accelerometer range setting"
	depends on BMI160_ACCEL_PMU_RUNTIME || BMI160_ACCEL_PMU_NORMAL || BMI160_ACCEL_PMU_LOW_POWER
	default BMI160_ACCEL_RANGE_RUNTIME

config BMI160_ACCEL_RANGE_RUNTIME
	bool "Set at runtime."

config BMI160_ACCEL_RANGE_2G
	bool "2G"

config BMI160_ACCEL_RANGE_4G
	bool "4G"

config BMI160_ACCEL_RANGE_8G
	bool "8G"

config BMI160_ACCEL_RANGE_16G
	bool "16G"
endchoice

choice
	prompt "Accelerometer sampling frequency."
	depends on BMI160_ACCEL_PMU_RUNTIME || BMI160_ACCEL_PMU_NORMAL || BMI160_ACCEL_PMU_LOW_POWER
	default BMI160_ACCEL_ODR_RUNTIME

config BMI160_ACCEL_ODR_RUNTIME
	bool "Set at runtime."

config BMI160_ACCEL_ODR_25_32
	depends on BMI160_ACCEL_PMU_LOW_POWER
	bool "0.78 Hz"

config BMI160_ACCEL_ODR_25_16
	depends on BMI160_ACCEL_PMU_LOW_POWER
	bool "1.56 Hz"

config BMI160_ACCEL_ODR_25_8
	depends on BMI160_ACCEL_PMU_LOW_POWER
	bool "3.125 Hz"

config BMI160_ACCEL_ODR_25_4
	depends on BMI160_ACCEL_PMU_LOW_POWER
	bool "6.25 Hz"

config BMI160_ACCEL_ODR_25_2
	bool "12.5 Hz"

config BMI160_ACCEL_ODR_25
	bool "25 Hz"

config BMI160_ACCEL_ODR_50
	bool "50 Hz"

config BMI160_ACCEL_ODR_100
	bool "100 Hz"

config BMI160_ACCEL_ODR_200
	bool "200 Hz"

config BMI160_ACCEL_ODR_400
	bool "400 Hz"

config BMI160_ACCEL_ODR_800
	bool "800 Hz"

config BMI160_ACCEL_ODR_1600
	bool "1600 Hz"
endchoice

choice
	prompt "Gyroscope power mode"
	default BMI160_GYRO_PMU_RUNTIME

config BMI160_GYRO_PMU_RUNTIME
	bool "Set at runtime."

config BMI160_GYRO_PMU_SUSPEND
	bool "suspended/not used"

config BMI160_GYRO_PMU_NORMAL
	bool "normal"

config BMI160_GYRO_PMU_FAST_STARTUP
	bool "fast start-up"
endchoice

choice
	prompt "Gyroscope range setting."
	depends on BMI160_GYRO_PMU_RUNTIME || BMI160_GYRO_PMU_NORMAL || BMI160_GYRO_PMU_FAST_STARTUP
	default BMI160_GYRO_RANGE_RUNTIME

config BMI160_GYRO_RANGE_RUNTIME
	bool "Set at runtime."

config BMI160_GYRO_RANGE_2000DPS
	bool "2000 DPS"

config BMI160_GYRO_RANGE_1000DPS
	bool "1000 DPS"

config BMI160_GYRO_RANGE_500DPS
	bool "500 DPS"

config BMI160_GYRO_RANGE_250DPS
	bool "250 DPS"

config BMI160_GYRO_RANGE_125DPS
	bool "125 DPS"
endchoice

choice
	prompt "Gyroscope sampling frequency."
	depends on BMI160_GYRO_PMU_RUNTIME || BMI160_GYRO_PMU_NORMAL || BMI160_GYRO_PMU_FAST_STARTUP
	default BMI160_GYRO_ODR_RUNTIME

config BMI160_GYRO_ODR_RUNTIME
	bool "Set at runtime."

config BMI160_GYRO_ODR_25
	bool "25 Hz"

config BMI160_GYRO_ODR_50
	bool "50 Hz"

config BMI160_GYRO_ODR_100
	bool "100 Hz"

config BMI160_GYRO_ODR_200
	bool "200 Hz"

config BMI160_GYRO_ODR_400
	bool "400 Hz"

config BMI160_GYRO_ODR_800
	bool "800 Hz"

config BMI160_GYRO_ODR_1600
	bool "1600 Hz"

config BMI160_GYRO_ODR_3200
	bool "3200 Hz"
endchoice

endif # BMI160

Parents Reply Children
  • That didn't help...

    [00:00:00.754,821] .[0m<inf> BMI160: SPI master controller found: SPI_1..[0m
    [00:00:00.754,913] .[0m<inf> BMI160: reboot OK..[0m
    [00:00:00.755,981] .[0m<inf> BMI160: Can read from 0x7F...[0m
    [00:00:00.756,134] .[0m<inf> BMI160: Read chip OK..[0m
    [00:00:00.856,262] .[0m<inf> BMI160: CHIP_ID OK (0xd1)!.[0m
    [00:00:01.014,953] .[0m<inf> BMI160: set power mode ok..[0m
    [00:00:01.015,014] .[0m<inf> BMI160: set default accelerometer range ok..[0m
    [00:00:01.015,075] .[0m<inf> BMI160: set default gyroscope range ok..[0m
    [00:00:01.015,228] .[0m<inf> BMI160: set accel's default ODR ok..[0m
    [00:00:01.015,350] .[0m<inf> BMI160: set set gyro's default ODR ok..[0m
    [00:00:01.015,441] .[1;31m<err> spi_nrfx_spim: Slave mode is not supported on SPI_1.[0m
    [00:00:01.015,441] .[1;31m<err> os: ***** MPU FAULT *****.[0m
    [00:00:01.015,441] .[1;31m<err> os:   Instruction Access Violation.[0m
    [00:00:01.015,472] .[1;31m<err> os: r0/a1:  0x20000140  r1/a2:  0x20000518  r2/a3:  0x00000001.[0m
    [00:00:01.015,472] .[1;31m<err> os: r3/a4:  0x43204950 r12/ip:  0x00000000 r14/lr:  0x00004ea9.[0m
    [00:00:01.015,472] .[1;31m<err> os:  xpsr:  0x08000000.[0m
    [00:00:01.015,472] .[1;31m<err> os: Faulting instruction address (r15/pc): 0x43204950.[0m
    [00:00:01.015,472] .[1;31m<err> os: >>> ZEPHYR FATAL ERROR 0: CPU exception on CPU 0.[0m
    [00:00:01.015,502] .[1;31m<err> os: Current thread: 0x200002b8 (unknown).[0m
    [00:00:01.137,115] .[1;31m<err> os: Halting system.[0m
    

  • I completely re-wrote the SPI part of the bmi160 library to accept chip select based on the "lis2dh" driver, and now it completes the initiation and startup, and tries to read (fetch_sample), but it only gets static temp/acc/gyro data (doesn't change with movement). And same exact readings for three boards. I'm suspecting the link between my driver and the sensor API.

    [00:00:00.402,191] [0m<inf> BMI160: Compiled: Apr  6 2021 05:40:23[0m
    [00:00:00.402,191] [0m<inf> BMI160: master found: SPI_1[0m
    [00:00:00.402,221] [0m<dbg> BMI160.bmi160_spi_init: SPI GPIO CS configured on GPIO_0:8[0m
    [00:00:00.402,221] [1;31m<err> BMI160: gpio conf ok...[0m
    [00:00:00.402,221] [0m<inf> BMI160: pins sat[0m
    [00:00:00.502,349] [0m<dbg> BMI160.bmi160_init: reboot chip ok..[0m
    [00:00:00.503,417] [0m<dbg> BMI160.bmi160_init: read from 0x7F ok..[0m
    [00:00:00.503,570] [0m<dbg> BMI160.bmi160_init: read chip id ok..[0m
    [00:00:00.503,570] [0m<dbg> BMI160.bmi160_init: chip id: d1[0m
    [00:00:00.561,859] [0m<dbg> BMI160.bmi160_init: set power mode ok...[0m
    [00:00:00.561,920] [0m<dbg> BMI160.bmi160_init: set default range for accelerometer ok...[0m
    [00:00:00.561,981] [0m<dbg> BMI160.bmi160_init: set default range for gyroscope ok...[0m
    [00:00:00.562,103] [0m<dbg> BMI160.bmi160_init: set accel's default ODR ok...[0m
    [00:00:00.562,225] [0m<dbg> BMI160.bmi160_init: set gyro's default ODR ok...[0m
    *** Booting Zephyr OS build zephyr-v2.5.0-352-gd96c517bab0d  ***
    
    BMI160 driver/sample...
    
    Gyro: Device found.
    
    set accelerometer range ok.
    
    set gyro range ok.
    
    HW calibration ok.
    
    Testing the polling mode.
    
    Gyro (rad/s): X=2.596426, Y=0, Z=0
    
    Acc (m/s^2): X=0, Y=0, Z=0
    
    Temperature (Celsius): 33.038420
    
    Gyro (rad/s): X=2.596426, Y=0, Z=0
    
    Acc (m/s^2): X=0, Y=0, Z=0
    
    Temperature (Celsius): 33.038420
    
    Gyro (rad/s): X=2.596426, Y=0, Z=0
    
    Acc (m/s^2): X=0, Y=0, Z=0
    
    Temperature (Celsius): 33.038420

    What would you think is the best route? To continue troubleshooting the driver I've enclosed above (which is a part of zephyr), or post the new driver and get help correcting the driver/sensor api link?

  • okwestern said:
    What would you think is the best route? To continue troubleshooting the driver I've enclosed above (which is a part of zephyr), or post the new driver and get help correcting the driver/sensor api link?

     I think you should keep debugging the original code and try figuring out why it triggers MPU fault. There are a couple of things you can try.

    You should include the following lines in prj.conf

    CONFIG_DEBUG=y
    CONFIG_THREAD_NAME=y
    CONFIG_EXTRA_EXCEPTION_INFO=y

    for more detailed debug information.

    You can also look up the faulting instruction address, by running the command below,

    arm-none-eabi-addr2line 0x43204950 -e zephyr.elf

Related