1 /* Bosch BMI160 inertial measurement unit driver
2  *
3  * Copyright (c) 2016 Intel Corporation
4  *
5  * SPDX-License-Identifier: Apache-2.0
6  *
7  * Datasheet:
8  * http://ae-bst.resource.bosch.com/media/_tech/media/datasheets/BST-BMI160-DS000-07.pdf
9  */
10 
11 #include <zephyr/init.h>
12 #include <zephyr/drivers/i2c.h>
13 #include <zephyr/drivers/sensor.h>
14 #include <zephyr/sys/byteorder.h>
15 #include <zephyr/kernel.h>
16 #include <zephyr/sys/__assert.h>
17 #include <zephyr/pm/pm.h>
18 #include <zephyr/pm/device.h>
19 #include <zephyr/pm/device_runtime.h>
20 #include <zephyr/logging/log.h>
21 
22 #include "bmi160.h"
23 
24 LOG_MODULE_REGISTER(BMI160, CONFIG_SENSOR_LOG_LEVEL);
25 
26 #if DT_NUM_INST_STATUS_OKAY(DT_DRV_COMPAT) == 0
27 #warning "BMI160 driver enabled without any devices"
28 #endif
29 
30 #if BMI160_BUS_SPI
bmi160_transceive(const struct device * dev,uint8_t reg,bool write,void * buf,size_t length)31 static int bmi160_transceive(const struct device *dev, uint8_t reg,
32 			     bool write, void *buf, size_t length)
33 {
34 	const struct bmi160_cfg *cfg = dev->config;
35 	const struct spi_buf tx_buf[2] = {
36 		{
37 			.buf = &reg,
38 			.len = 1
39 		},
40 		{
41 			.buf = buf,
42 			.len = length
43 		}
44 	};
45 	const struct spi_buf_set tx = {
46 		.buffers = tx_buf,
47 		.count = buf ? 2 : 1
48 	};
49 
50 	if (!write) {
51 		const struct spi_buf_set rx = {
52 			.buffers = tx_buf,
53 			.count = 2
54 		};
55 
56 		return spi_transceive_dt(&cfg->bus.spi, &tx, &rx);
57 	}
58 
59 	return spi_write_dt(&cfg->bus.spi, &tx);
60 }
61 
bmi160_bus_ready_spi(const struct device * dev)62 bool bmi160_bus_ready_spi(const struct device *dev)
63 {
64 	const struct bmi160_cfg *cfg = dev->config;
65 
66 	return spi_is_ready_dt(&cfg->bus.spi);
67 }
68 
bmi160_read_spi(const struct device * dev,uint8_t reg_addr,void * buf,uint8_t len)69 int bmi160_read_spi(const struct device *dev,
70 		    uint8_t reg_addr, void *buf, uint8_t len)
71 {
72 	return bmi160_transceive(dev, reg_addr | BMI160_REG_READ, false,
73 				 buf, len);
74 }
75 
bmi160_write_spi(const struct device * dev,uint8_t reg_addr,void * buf,uint8_t len)76 int bmi160_write_spi(const struct device *dev,
77 		     uint8_t reg_addr, void *buf, uint8_t len)
78 {
79 	return bmi160_transceive(dev, reg_addr & BMI160_REG_MASK, true,
80 				 buf, len);
81 }
82 
83 static const struct bmi160_bus_io bmi160_bus_io_spi = {
84 	.ready = bmi160_bus_ready_spi,
85 	.read = bmi160_read_spi,
86 	.write = bmi160_write_spi,
87 };
88 #endif /* BMI160_BUS_SPI */
89 
90 #if BMI160_BUS_I2C
91 
bmi160_bus_ready_i2c(const struct device * dev)92 bool bmi160_bus_ready_i2c(const struct device *dev)
93 {
94 	const struct bmi160_cfg *cfg = dev->config;
95 
96 	return device_is_ready(cfg->bus.i2c.bus);
97 }
98 
bmi160_read_i2c(const struct device * dev,uint8_t reg_addr,void * buf,uint8_t len)99 int bmi160_read_i2c(const struct device *dev,
100 		    uint8_t reg_addr, void *buf, uint8_t len)
101 {
102 	const struct bmi160_cfg *cfg = dev->config;
103 
104 	return i2c_burst_read_dt(&cfg->bus.i2c, reg_addr, buf, len);
105 }
106 
bmi160_write_i2c(const struct device * dev,uint8_t reg_addr,void * buf,uint8_t len)107 int bmi160_write_i2c(const struct device *dev,
108 		     uint8_t reg_addr, void *buf, uint8_t len)
109 {
110 	const struct bmi160_cfg *cfg = dev->config;
111 
112 	return i2c_burst_write_dt(&cfg->bus.i2c, reg_addr, buf, len);
113 }
114 
115 static const struct bmi160_bus_io bmi160_bus_io_i2c = {
116 	.ready = bmi160_bus_ready_i2c,
117 	.read = bmi160_read_i2c,
118 	.write = bmi160_write_i2c,
119 };
120 #endif
121 
bmi160_read(const struct device * dev,uint8_t reg_addr,void * buf,uint8_t len)122 int bmi160_read(const struct device *dev, uint8_t reg_addr, void *buf,
123 		uint8_t len)
124 {
125 	const struct bmi160_cfg *cfg = dev->config;
126 
127 	return cfg->bus_io->read(dev, reg_addr, buf, len);
128 }
129 
bmi160_byte_read(const struct device * dev,uint8_t reg_addr,uint8_t * byte)130 int bmi160_byte_read(const struct device *dev, uint8_t reg_addr, uint8_t *byte)
131 {
132 	return bmi160_read(dev, reg_addr, byte, 1);
133 }
134 
bmi160_word_read(const struct device * dev,uint8_t reg_addr,uint16_t * word)135 static int bmi160_word_read(const struct device *dev, uint8_t reg_addr,
136 			    uint16_t *word)
137 {
138 	int rc;
139 
140 	rc = bmi160_read(dev, reg_addr, word, 2);
141 	if (rc != 0) {
142 		return rc;
143 	}
144 
145 	*word = sys_le16_to_cpu(*word);
146 
147 	return 0;
148 }
149 
bmi160_write(const struct device * dev,uint8_t reg_addr,void * buf,uint8_t len)150 int bmi160_write(const struct device *dev, uint8_t reg_addr, void *buf,
151 		 uint8_t len)
152 {
153 	const struct bmi160_cfg *cfg = dev->config;
154 
155 	return cfg->bus_io->write(dev, reg_addr, buf, len);
156 }
157 
bmi160_byte_write(const struct device * dev,uint8_t reg_addr,uint8_t byte)158 int bmi160_byte_write(const struct device *dev, uint8_t reg_addr,
159 		      uint8_t byte)
160 {
161 	return bmi160_write(dev, reg_addr & BMI160_REG_MASK, &byte, 1);
162 }
163 
bmi160_word_write(const struct device * dev,uint8_t reg_addr,uint16_t word)164 int bmi160_word_write(const struct device *dev, uint8_t reg_addr,
165 		      uint16_t word)
166 {
167 	uint8_t tx_word[2] = {
168 		(uint8_t)(word & 0xff),
169 		(uint8_t)(word >> 8)
170 	};
171 
172 	return bmi160_write(dev, reg_addr & BMI160_REG_MASK, tx_word, 2);
173 }
174 
bmi160_reg_field_update(const struct device * dev,uint8_t reg_addr,uint8_t pos,uint8_t mask,uint8_t val)175 int bmi160_reg_field_update(const struct device *dev, uint8_t reg_addr,
176 			    uint8_t pos, uint8_t mask, uint8_t val)
177 {
178 	uint8_t old_val;
179 
180 	if (bmi160_byte_read(dev, reg_addr, &old_val) < 0) {
181 		return -EIO;
182 	}
183 
184 	return bmi160_byte_write(dev, reg_addr,
185 				 (old_val & ~mask) | ((val << pos) & mask));
186 }
187 
bmi160_pmu_set(const struct device * dev,union bmi160_pmu_status * pmu_sts)188 static int bmi160_pmu_set(const struct device *dev,
189 			  union bmi160_pmu_status *pmu_sts)
190 {
191 	struct {
192 		uint8_t cmd;
193 		uint16_t delay_us; /* values taken from page 82 */
194 	} cmds[] = {
195 		{BMI160_CMD_PMU_MAG | pmu_sts->mag, 350},
196 		{BMI160_CMD_PMU_ACC | pmu_sts->acc, 3200},
197 		{BMI160_CMD_PMU_GYR | pmu_sts->gyr, 55000}
198 	};
199 	size_t i;
200 
201 	for (i = 0; i < ARRAY_SIZE(cmds); i++) {
202 		union bmi160_pmu_status sts;
203 		bool pmu_set = false;
204 
205 		if (bmi160_byte_write(dev, BMI160_REG_CMD, cmds[i].cmd) < 0) {
206 			return -EIO;
207 		}
208 
209 		/*
210 		 * Cannot use a timer here since this is called from the
211 		 * init function and the timeouts were not initialized yet.
212 		 */
213 		k_busy_wait(cmds[i].delay_us);
214 
215 		/* make sure the PMU_STATUS was set, though */
216 		do {
217 			if (bmi160_byte_read(dev, BMI160_REG_PMU_STATUS,
218 					     &sts.raw) < 0) {
219 				return -EIO;
220 			}
221 
222 			if (i == 0) {
223 				pmu_set = (pmu_sts->mag == sts.mag);
224 			} else if (i == 1) {
225 				pmu_set = (pmu_sts->acc == sts.acc);
226 			} else {
227 				pmu_set = (pmu_sts->gyr == sts.gyr);
228 			}
229 
230 		} while (!pmu_set);
231 	}
232 
233 	/* set the undersampling flag for accelerometer */
234 	return bmi160_reg_field_update(dev, BMI160_REG_ACC_CONF,
235 				       BMI160_ACC_CONF_US_POS, BMI160_ACC_CONF_US_MASK,
236 				       pmu_sts->acc != BMI160_PMU_NORMAL);
237 }
238 
239 #if defined(CONFIG_BMI160_GYRO_ODR_RUNTIME) ||\
240 	defined(CONFIG_BMI160_ACCEL_ODR_RUNTIME)
241 /*
242  * Output data rate map with allowed frequencies:
243  * freq = freq_int + freq_milli / 1000
244  *
245  * Since we don't need a finer frequency resolution than milliHz, use uint16_t
246  * to save some flash.
247  */
248 struct {
249 	uint16_t freq_int;
250 	uint16_t freq_milli; /* User should convert to uHz before setting the
251 			      * SENSOR_ATTR_SAMPLING_FREQUENCY attribute.
252 			      */
253 } bmi160_odr_map[] = {
254 	{0,    0  }, {0,     780}, {1,     562}, {3,    120}, {6,   250},
255 	{12,   500}, {25,    0  }, {50,    0  }, {100,  0  }, {200, 0  },
256 	{400,  0  }, {800,   0  }, {1600,  0  }, {3200, 0  },
257 };
258 
bmi160_freq_to_odr_val(uint16_t freq_int,uint16_t freq_milli)259 static int bmi160_freq_to_odr_val(uint16_t freq_int, uint16_t freq_milli)
260 {
261 	size_t i;
262 
263 	/* An ODR of 0 Hz is not allowed */
264 	if (freq_int == 0U && freq_milli == 0U) {
265 		return -EINVAL;
266 	}
267 
268 	for (i = 0; i < ARRAY_SIZE(bmi160_odr_map); i++) {
269 		if (freq_int < bmi160_odr_map[i].freq_int ||
270 		    (freq_int == bmi160_odr_map[i].freq_int &&
271 		     freq_milli <= bmi160_odr_map[i].freq_milli)) {
272 			return i;
273 		}
274 	}
275 
276 	return -EINVAL;
277 }
278 #endif
279 
280 #if defined(CONFIG_BMI160_ACCEL_ODR_RUNTIME)
bmi160_acc_odr_set(const struct device * dev,uint16_t freq_int,uint16_t freq_milli)281 static int bmi160_acc_odr_set(const struct device *dev, uint16_t freq_int,
282 			      uint16_t freq_milli)
283 {
284 	struct bmi160_data *data = dev->data;
285 	int odr = bmi160_freq_to_odr_val(freq_int, freq_milli);
286 
287 	if (odr < 0) {
288 		return odr;
289 	}
290 
291 	/* some odr values cannot be set in certain power modes */
292 	if ((data->pmu_sts.acc == BMI160_PMU_NORMAL &&
293 	     odr < BMI160_ODR_25_2) ||
294 	    (data->pmu_sts.acc == BMI160_PMU_LOW_POWER &&
295 	    odr < BMI160_ODR_25_32) || odr > BMI160_ODR_1600) {
296 		return -ENOTSUP;
297 	}
298 
299 	return bmi160_reg_field_update(dev, BMI160_REG_ACC_CONF,
300 				       BMI160_ACC_CONF_ODR_POS,
301 				       BMI160_ACC_CONF_ODR_MASK,
302 				       (uint8_t) odr);
303 }
304 #endif
305 
306 static const struct bmi160_range bmi160_acc_range_map[] = {
307 	{2,	BMI160_ACC_RANGE_2G},
308 	{4,	BMI160_ACC_RANGE_4G},
309 	{8,	BMI160_ACC_RANGE_8G},
310 	{16,	BMI160_ACC_RANGE_16G},
311 };
312 #define BMI160_ACC_RANGE_MAP_SIZE	ARRAY_SIZE(bmi160_acc_range_map)
313 
314 static const struct bmi160_range bmi160_gyr_range_map[] = {
315 	{2000,	BMI160_GYR_RANGE_2000DPS},
316 	{1000,	BMI160_GYR_RANGE_1000DPS},
317 	{500,	BMI160_GYR_RANGE_500DPS},
318 	{250,	BMI160_GYR_RANGE_250DPS},
319 	{125,	BMI160_GYR_RANGE_125DPS},
320 };
321 #define BMI160_GYR_RANGE_MAP_SIZE	ARRAY_SIZE(bmi160_gyr_range_map)
322 
323 #if defined(CONFIG_BMI160_ACCEL_RANGE_RUNTIME) ||\
324 	defined(CONFIG_BMI160_GYRO_RANGE_RUNTIME)
bmi160_range_to_reg_val(uint16_t range,const struct bmi160_range * range_map,uint16_t range_map_size)325 static int32_t bmi160_range_to_reg_val(uint16_t range,
326 				       const struct bmi160_range *range_map,
327 				       uint16_t range_map_size)
328 {
329 	int i;
330 
331 	for (i = 0; i < range_map_size; i++) {
332 		if (range <= range_map[i].range) {
333 			return range_map[i].reg_val;
334 		}
335 	}
336 
337 	return -EINVAL;
338 }
339 #endif
340 
bmi160_reg_val_to_range(uint8_t reg_val,const struct bmi160_range * range_map,uint16_t range_map_size)341 static int32_t bmi160_reg_val_to_range(uint8_t reg_val,
342 				       const struct bmi160_range *range_map,
343 				       uint16_t range_map_size)
344 {
345 	int i;
346 
347 	for (i = 0; i < range_map_size; i++) {
348 		if (reg_val == range_map[i].reg_val) {
349 			return range_map[i].range;
350 		}
351 	}
352 
353 	return -EINVAL;
354 }
355 
bmi160_acc_reg_val_to_range(uint8_t reg_val)356 int32_t bmi160_acc_reg_val_to_range(uint8_t reg_val)
357 {
358 	return bmi160_reg_val_to_range(reg_val, bmi160_acc_range_map,
359 				       BMI160_ACC_RANGE_MAP_SIZE);
360 }
361 
bmi160_gyr_reg_val_to_range(uint8_t reg_val)362 int32_t bmi160_gyr_reg_val_to_range(uint8_t reg_val)
363 {
364 	return bmi160_reg_val_to_range(reg_val, bmi160_gyr_range_map,
365 				       BMI160_GYR_RANGE_MAP_SIZE);
366 }
367 
bmi160_do_calibration(const struct device * dev,uint8_t foc_conf)368 static int bmi160_do_calibration(const struct device *dev, uint8_t foc_conf)
369 {
370 	if (bmi160_byte_write(dev, BMI160_REG_FOC_CONF, foc_conf) < 0) {
371 		return -EIO;
372 	}
373 
374 	if (bmi160_byte_write(dev, BMI160_REG_CMD, BMI160_CMD_START_FOC) < 0) {
375 		return -EIO;
376 	}
377 
378 	k_busy_wait(250000); /* calibration takes a maximum of 250ms */
379 
380 	return 0;
381 }
382 
383 #if defined(CONFIG_BMI160_ACCEL_RANGE_RUNTIME)
bmi160_acc_range_set(const struct device * dev,int32_t range)384 static int bmi160_acc_range_set(const struct device *dev, int32_t range)
385 {
386 	struct bmi160_data *data = dev->data;
387 	int32_t reg_val = bmi160_range_to_reg_val(range,
388 						  bmi160_acc_range_map,
389 						  BMI160_ACC_RANGE_MAP_SIZE);
390 
391 	if (reg_val < 0) {
392 		return reg_val;
393 	}
394 
395 	if (bmi160_byte_write(dev, BMI160_REG_ACC_RANGE, reg_val & 0xff) < 0) {
396 		return -EIO;
397 	}
398 
399 	data->scale.acc = BMI160_ACC_SCALE(range);
400 
401 	return 0;
402 }
403 #endif
404 
405 #if !defined(CONFIG_BMI160_ACCEL_PMU_SUSPEND)
406 /*
407  * Accelerometer offset scale, taken from pg. 79, converted to micro m/s^2:
408  *	3.9 * 9.80665 * 1000
409  */
410 #define BMI160_ACC_OFS_LSB		38246
bmi160_acc_ofs_set(const struct device * dev,enum sensor_channel chan,const struct sensor_value * ofs)411 static int bmi160_acc_ofs_set(const struct device *dev,
412 			      enum sensor_channel chan,
413 			      const struct sensor_value *ofs)
414 {
415 	uint8_t reg_addr[] = {
416 		BMI160_REG_OFFSET_ACC_X,
417 		BMI160_REG_OFFSET_ACC_Y,
418 		BMI160_REG_OFFSET_ACC_Z
419 	};
420 	int i;
421 	int32_t ofs_u;
422 	int8_t reg_val;
423 
424 	/* we need the offsets for all axis */
425 	if (chan != SENSOR_CHAN_ACCEL_XYZ) {
426 		return -ENOTSUP;
427 	}
428 
429 	for (i = 0; i < BMI160_AXES; i++, ofs++) {
430 		/* convert offset to micro m/s^2 */
431 		ofs_u = ofs->val1 * 1000000ULL + ofs->val2;
432 		reg_val = ofs_u / BMI160_ACC_OFS_LSB;
433 
434 		if (bmi160_byte_write(dev, reg_addr[i], reg_val) < 0) {
435 			return -EIO;
436 		}
437 	}
438 
439 	/* activate accel HW compensation */
440 	return bmi160_reg_field_update(dev, BMI160_REG_OFFSET_EN,
441 				       BMI160_ACC_OFS_EN_POS,
442 				       BIT(BMI160_ACC_OFS_EN_POS), 1);
443 }
444 
bmi160_acc_calibrate(const struct device * dev,enum sensor_channel chan,const struct sensor_value * xyz_calib_value)445 static int  bmi160_acc_calibrate(const struct device *dev,
446 				 enum sensor_channel chan,
447 				 const struct sensor_value *xyz_calib_value)
448 {
449 	struct bmi160_data *data = dev->data;
450 	uint8_t foc_pos[] = {
451 		BMI160_FOC_ACC_X_POS,
452 		BMI160_FOC_ACC_Y_POS,
453 		BMI160_FOC_ACC_Z_POS,
454 	};
455 	int i;
456 	uint8_t reg_val = 0U;
457 
458 	/* Calibration has to be done in normal mode. */
459 	if (data->pmu_sts.acc != BMI160_PMU_NORMAL) {
460 		return -ENOTSUP;
461 	}
462 
463 	/*
464 	 * Hardware calibration is done knowing the expected values on all axis.
465 	 */
466 	if (chan != SENSOR_CHAN_ACCEL_XYZ) {
467 		return -ENOTSUP;
468 	}
469 
470 	for (i = 0; i < BMI160_AXES; i++, xyz_calib_value++) {
471 		int32_t accel_g;
472 		uint8_t accel_val;
473 
474 		accel_g = sensor_ms2_to_g(xyz_calib_value);
475 		if (accel_g == 0) {
476 			accel_val = 3U;
477 		} else if (accel_g == 1) {
478 			accel_val = 1U;
479 		} else if (accel_g == -1) {
480 			accel_val = 2U;
481 		} else {
482 			accel_val = 0U;
483 		}
484 		reg_val |= (accel_val << foc_pos[i]);
485 	}
486 
487 	if (bmi160_do_calibration(dev, reg_val) < 0) {
488 		return -EIO;
489 	}
490 
491 	/* activate accel HW compensation */
492 	return bmi160_reg_field_update(dev, BMI160_REG_OFFSET_EN,
493 				       BMI160_ACC_OFS_EN_POS,
494 				       BIT(BMI160_ACC_OFS_EN_POS), 1);
495 }
496 
bmi160_acc_config(const struct device * dev,enum sensor_channel chan,enum sensor_attribute attr,const struct sensor_value * val)497 static int bmi160_acc_config(const struct device *dev,
498 			     enum sensor_channel chan,
499 			     enum sensor_attribute attr,
500 			     const struct sensor_value *val)
501 {
502 	switch (attr) {
503 #if defined(CONFIG_BMI160_ACCEL_RANGE_RUNTIME)
504 	case SENSOR_ATTR_FULL_SCALE:
505 		return bmi160_acc_range_set(dev, sensor_ms2_to_g(val));
506 #endif
507 #if defined(CONFIG_BMI160_ACCEL_ODR_RUNTIME)
508 	case SENSOR_ATTR_SAMPLING_FREQUENCY:
509 		return bmi160_acc_odr_set(dev, val->val1, val->val2 / 1000);
510 #endif
511 	case SENSOR_ATTR_OFFSET:
512 		return bmi160_acc_ofs_set(dev, chan, val);
513 	case SENSOR_ATTR_CALIB_TARGET:
514 		return bmi160_acc_calibrate(dev, chan, val);
515 #if defined(CONFIG_BMI160_TRIGGER)
516 	case SENSOR_ATTR_SLOPE_TH:
517 	case SENSOR_ATTR_SLOPE_DUR:
518 		return bmi160_acc_slope_config(dev, attr, val);
519 #endif
520 	default:
521 		LOG_DBG("Accel attribute not supported.");
522 		return -ENOTSUP;
523 	}
524 
525 	return 0;
526 }
527 #endif /* !defined(CONFIG_BMI160_ACCEL_PMU_SUSPEND) */
528 
529 #if defined(CONFIG_BMI160_GYRO_ODR_RUNTIME)
bmi160_gyr_odr_set(const struct device * dev,uint16_t freq_int,uint16_t freq_milli)530 static int bmi160_gyr_odr_set(const struct device *dev, uint16_t freq_int,
531 			      uint16_t freq_milli)
532 {
533 	int odr = bmi160_freq_to_odr_val(freq_int, freq_milli);
534 
535 	if (odr < 0) {
536 		return odr;
537 	}
538 
539 	if (odr < BMI160_ODR_25 || odr > BMI160_ODR_3200) {
540 		return -ENOTSUP;
541 	}
542 
543 	return bmi160_reg_field_update(dev, BMI160_REG_GYR_CONF,
544 				       BMI160_GYR_CONF_ODR_POS,
545 				       BMI160_GYR_CONF_ODR_MASK,
546 				       (uint8_t) odr);
547 }
548 #endif
549 
550 #if defined(CONFIG_BMI160_GYRO_RANGE_RUNTIME)
bmi160_gyr_range_set(const struct device * dev,uint16_t range)551 static int bmi160_gyr_range_set(const struct device *dev, uint16_t range)
552 {
553 	struct bmi160_data *data = dev->data;
554 	int32_t reg_val = bmi160_range_to_reg_val(range,
555 						bmi160_gyr_range_map,
556 						BMI160_GYR_RANGE_MAP_SIZE);
557 
558 	if (reg_val < 0) {
559 		return reg_val;
560 	}
561 
562 	if (bmi160_byte_write(dev, BMI160_REG_GYR_RANGE, reg_val) < 0) {
563 		return -EIO;
564 	}
565 
566 	data->scale.gyr = BMI160_GYR_SCALE(range);
567 
568 	return 0;
569 }
570 #endif
571 
572 #if !defined(CONFIG_BMI160_GYRO_PMU_SUSPEND)
573 /*
574  * Gyro offset scale, taken from pg. 79, converted to micro rad/s:
575  *		0.061 * (pi / 180) * 1000000, where pi = 3.141592
576  */
577 #define BMI160_GYR_OFS_LSB		1065
bmi160_gyr_ofs_set(const struct device * dev,enum sensor_channel chan,const struct sensor_value * ofs)578 static int bmi160_gyr_ofs_set(const struct device *dev,
579 			      enum sensor_channel chan,
580 			      const struct sensor_value *ofs)
581 {
582 	struct {
583 		uint8_t lsb_addr;
584 		uint8_t msb_pos;
585 	} ofs_desc[] = {
586 		{BMI160_REG_OFFSET_GYR_X, BMI160_GYR_MSB_OFS_X_POS},
587 		{BMI160_REG_OFFSET_GYR_Y, BMI160_GYR_MSB_OFS_Y_POS},
588 		{BMI160_REG_OFFSET_GYR_Z, BMI160_GYR_MSB_OFS_Z_POS},
589 	};
590 	int i;
591 	int32_t ofs_u;
592 	int16_t val;
593 
594 	/* we need the offsets for all axis */
595 	if (chan != SENSOR_CHAN_GYRO_XYZ) {
596 		return -ENOTSUP;
597 	}
598 
599 	for (i = 0; i < BMI160_AXES; i++, ofs++) {
600 		/* convert offset to micro rad/s */
601 		ofs_u = ofs->val1 * 1000000ULL + ofs->val2;
602 
603 		val = ofs_u / BMI160_GYR_OFS_LSB;
604 
605 		/*
606 		 * The gyro offset is a 10 bit two-complement value. Make sure
607 		 * the passed value is within limits.
608 		 */
609 		if (val < -512 || val > 512) {
610 			return -EINVAL;
611 		}
612 
613 		/* write the LSB */
614 		if (bmi160_byte_write(dev, ofs_desc[i].lsb_addr,
615 				      val & 0xff) < 0) {
616 			return -EIO;
617 		}
618 
619 		/* write the MSB */
620 		if (bmi160_reg_field_update(dev, BMI160_REG_OFFSET_EN,
621 					    ofs_desc[i].msb_pos,
622 					    0x3 << ofs_desc[i].msb_pos,
623 					    (val >> 8) & 0x3) < 0) {
624 			return -EIO;
625 		}
626 	}
627 
628 	/* activate gyro HW compensation */
629 	return bmi160_reg_field_update(dev, BMI160_REG_OFFSET_EN,
630 				       BMI160_GYR_OFS_EN_POS,
631 				       BIT(BMI160_GYR_OFS_EN_POS), 1);
632 }
633 
bmi160_gyr_calibrate(const struct device * dev,enum sensor_channel chan)634 static int bmi160_gyr_calibrate(const struct device *dev,
635 				enum sensor_channel chan)
636 {
637 	struct bmi160_data *data = dev->data;
638 
639 	ARG_UNUSED(chan);
640 
641 	/* Calibration has to be done in normal mode. */
642 	if (data->pmu_sts.gyr != BMI160_PMU_NORMAL) {
643 		return -ENOTSUP;
644 	}
645 
646 	if (bmi160_do_calibration(dev, BIT(BMI160_FOC_GYR_EN_POS)) < 0) {
647 		return -EIO;
648 	}
649 
650 	/* activate gyro HW compensation */
651 	return bmi160_reg_field_update(dev, BMI160_REG_OFFSET_EN,
652 				       BMI160_GYR_OFS_EN_POS,
653 				       BIT(BMI160_GYR_OFS_EN_POS), 1);
654 }
655 
bmi160_gyr_config(const struct device * dev,enum sensor_channel chan,enum sensor_attribute attr,const struct sensor_value * val)656 static int bmi160_gyr_config(const struct device *dev,
657 			     enum sensor_channel chan,
658 			     enum sensor_attribute attr,
659 			     const struct sensor_value *val)
660 {
661 	switch (attr) {
662 #if defined(CONFIG_BMI160_GYRO_RANGE_RUNTIME)
663 	case SENSOR_ATTR_FULL_SCALE:
664 		return bmi160_gyr_range_set(dev, sensor_rad_to_degrees(val));
665 #endif
666 #if defined(CONFIG_BMI160_GYRO_ODR_RUNTIME)
667 	case SENSOR_ATTR_SAMPLING_FREQUENCY:
668 		return bmi160_gyr_odr_set(dev, val->val1, val->val2 / 1000);
669 #endif
670 	case SENSOR_ATTR_OFFSET:
671 		return bmi160_gyr_ofs_set(dev, chan, val);
672 
673 	case SENSOR_ATTR_CALIB_TARGET:
674 		return bmi160_gyr_calibrate(dev, chan);
675 
676 	default:
677 		LOG_DBG("Gyro attribute not supported.");
678 		return -ENOTSUP;
679 	}
680 
681 	return 0;
682 }
683 #endif /* !defined(CONFIG_BMI160_GYRO_PMU_SUSPEND) */
684 
bmi160_attr_set(const struct device * dev,enum sensor_channel chan,enum sensor_attribute attr,const struct sensor_value * val)685 static int bmi160_attr_set(const struct device *dev, enum sensor_channel chan,
686 			   enum sensor_attribute attr,
687 			   const struct sensor_value *val)
688 {
689 	switch (chan) {
690 #if !defined(CONFIG_BMI160_GYRO_PMU_SUSPEND)
691 	case SENSOR_CHAN_GYRO_X:
692 	case SENSOR_CHAN_GYRO_Y:
693 	case SENSOR_CHAN_GYRO_Z:
694 	case SENSOR_CHAN_GYRO_XYZ:
695 		return bmi160_gyr_config(dev, chan, attr, val);
696 #endif
697 #if !defined(CONFIG_BMI160_ACCEL_PMU_SUSPEND)
698 	case SENSOR_CHAN_ACCEL_X:
699 	case SENSOR_CHAN_ACCEL_Y:
700 	case SENSOR_CHAN_ACCEL_Z:
701 	case SENSOR_CHAN_ACCEL_XYZ:
702 		return bmi160_acc_config(dev, chan, attr, val);
703 #endif
704 	default:
705 		LOG_DBG("attr_set() not supported on this channel.");
706 		return -ENOTSUP;
707 	}
708 
709 	return 0;
710 }
711 
bmi160_sample_fetch(const struct device * dev,enum sensor_channel chan)712 static int bmi160_sample_fetch(const struct device *dev,
713 			       enum sensor_channel chan)
714 {
715 	struct bmi160_data *data = dev->data;
716 	uint8_t status;
717 	size_t i;
718 	int ret = 0;
719 	enum pm_device_state pm_state;
720 
721 	(void)pm_device_state_get(dev, &pm_state);
722 	if (pm_state != PM_DEVICE_STATE_ACTIVE) {
723 		LOG_DBG("Device is suspended, fetch is unavailable");
724 		ret = -EIO;
725 		goto out;
726 	}
727 
728 	__ASSERT_NO_MSG(chan == SENSOR_CHAN_ALL);
729 
730 	status = 0;
731 	while ((status & BMI160_DATA_READY_BIT_MASK) == 0) {
732 
733 		if (bmi160_byte_read(dev, BMI160_REG_STATUS, &status) < 0) {
734 			ret = -EIO;
735 			goto out;
736 		}
737 	}
738 
739 	if (bmi160_read(dev, BMI160_SAMPLE_BURST_READ_ADDR, data->sample.raw,
740 			BMI160_BUF_SIZE) < 0) {
741 		ret = -EIO;
742 		goto out;
743 	}
744 
745 	/* convert samples to cpu endianness */
746 	for (i = 0; i < BMI160_SAMPLE_SIZE; i += 2) {
747 		uint16_t *sample =
748 			(uint16_t *) &data->sample.raw[i];
749 
750 		*sample = sys_le16_to_cpu(*sample);
751 	}
752 
753 out:
754 	return ret;
755 }
756 
bmi160_to_fixed_point(int16_t raw_val,uint16_t scale,struct sensor_value * val)757 static void bmi160_to_fixed_point(int16_t raw_val, uint16_t scale,
758 				  struct sensor_value *val)
759 {
760 	int32_t converted_val;
761 
762 	/*
763 	 * maximum converted value we can get is: max(raw_val) * max(scale)
764 	 *	max(raw_val) = +/- 2^15
765 	 *	max(scale) = 4785
766 	 *	max(converted_val) = 156794880 which is less than 2^31
767 	 */
768 	converted_val = raw_val * scale;
769 	val->val1 = converted_val / 1000000;
770 	val->val2 = converted_val % 1000000;
771 }
772 
bmi160_channel_convert(enum sensor_channel chan,uint16_t scale,uint16_t * raw_xyz,struct sensor_value * val)773 static void bmi160_channel_convert(enum sensor_channel chan,
774 				   uint16_t scale,
775 				   uint16_t *raw_xyz,
776 				   struct sensor_value *val)
777 {
778 	int i;
779 	uint8_t ofs_start, ofs_stop;
780 
781 	switch (chan) {
782 	case SENSOR_CHAN_ACCEL_X:
783 	case SENSOR_CHAN_GYRO_X:
784 		ofs_start = ofs_stop = 0U;
785 		break;
786 	case SENSOR_CHAN_ACCEL_Y:
787 	case SENSOR_CHAN_GYRO_Y:
788 		ofs_start = ofs_stop = 1U;
789 		break;
790 	case SENSOR_CHAN_ACCEL_Z:
791 	case SENSOR_CHAN_GYRO_Z:
792 		ofs_start = ofs_stop = 2U;
793 		break;
794 	default:
795 		ofs_start = 0U; ofs_stop = 2U;
796 		break;
797 	}
798 
799 	for (i = ofs_start; i <= ofs_stop ; i++, val++) {
800 		bmi160_to_fixed_point(raw_xyz[i], scale, val);
801 	}
802 }
803 
804 #if !defined(CONFIG_BMI160_GYRO_PMU_SUSPEND)
bmi160_gyr_channel_get(const struct device * dev,enum sensor_channel chan,struct sensor_value * val)805 static inline void bmi160_gyr_channel_get(const struct device *dev,
806 					  enum sensor_channel chan,
807 					  struct sensor_value *val)
808 {
809 	struct bmi160_data *data = dev->data;
810 
811 	bmi160_channel_convert(chan, data->scale.gyr, data->sample.gyr, val);
812 }
813 #endif
814 
815 #if !defined(CONFIG_BMI160_ACCEL_PMU_SUSPEND)
bmi160_acc_channel_get(const struct device * dev,enum sensor_channel chan,struct sensor_value * val)816 static inline void bmi160_acc_channel_get(const struct device *dev,
817 					  enum sensor_channel chan,
818 					  struct sensor_value *val)
819 {
820 	struct bmi160_data *data = dev->data;
821 
822 	bmi160_channel_convert(chan, data->scale.acc, data->sample.acc, val);
823 }
824 #endif
825 
bmi160_temp_channel_get(const struct device * dev,struct sensor_value * val)826 static int bmi160_temp_channel_get(const struct device *dev,
827 				   struct sensor_value *val)
828 {
829 	uint16_t temp_raw = 0U;
830 	int32_t temp_micro = 0;
831 	struct bmi160_data *data = dev->data;
832 
833 	if (data->pmu_sts.raw == 0U) {
834 		return -EINVAL;
835 	}
836 
837 	if (bmi160_word_read(dev, BMI160_REG_TEMPERATURE0, &temp_raw) < 0) {
838 		return -EIO;
839 	}
840 
841 	/* the scale is 1/2^9/LSB = 1953 micro degrees */
842 	temp_micro = BMI160_TEMP_OFFSET * 1000000ULL + temp_raw * 1953ULL;
843 
844 	val->val1 = temp_micro / 1000000ULL;
845 	val->val2 = temp_micro % 1000000ULL;
846 
847 	return 0;
848 }
849 
bmi160_channel_get(const struct device * dev,enum sensor_channel chan,struct sensor_value * val)850 static int bmi160_channel_get(const struct device *dev,
851 			      enum sensor_channel chan,
852 			      struct sensor_value *val)
853 {
854 	switch (chan) {
855 #if !defined(CONFIG_BMI160_GYRO_PMU_SUSPEND)
856 	case SENSOR_CHAN_GYRO_X:
857 	case SENSOR_CHAN_GYRO_Y:
858 	case SENSOR_CHAN_GYRO_Z:
859 	case SENSOR_CHAN_GYRO_XYZ:
860 		bmi160_gyr_channel_get(dev, chan, val);
861 		return 0;
862 #endif
863 #if !defined(CONFIG_BMI160_ACCEL_PMU_SUSPEND)
864 	case SENSOR_CHAN_ACCEL_X:
865 	case SENSOR_CHAN_ACCEL_Y:
866 	case SENSOR_CHAN_ACCEL_Z:
867 	case SENSOR_CHAN_ACCEL_XYZ:
868 		bmi160_acc_channel_get(dev, chan, val);
869 		return 0;
870 #endif
871 	case SENSOR_CHAN_DIE_TEMP:
872 		return bmi160_temp_channel_get(dev, val);
873 	default:
874 		LOG_DBG("Channel not supported.");
875 		return -ENOTSUP;
876 	}
877 
878 	return 0;
879 }
880 
881 static const struct sensor_driver_api bmi160_api = {
882 	.attr_set = bmi160_attr_set,
883 #ifdef CONFIG_BMI160_TRIGGER
884 	.trigger_set = bmi160_trigger_set,
885 #endif
886 	.sample_fetch = bmi160_sample_fetch,
887 	.channel_get = bmi160_channel_get,
888 };
889 
890 
bmi160_resume(const struct device * dev)891 static inline int bmi160_resume(const struct device *dev)
892 {
893 	struct bmi160_data *data = dev->data;
894 
895 	return bmi160_pmu_set(dev, &data->pmu_sts);
896 }
897 
bmi160_suspend(const struct device * dev)898 static inline int bmi160_suspend(const struct device *dev)
899 {
900 	struct bmi160_data *data = dev->data;
901 
902 	/* Suspend everything */
903 	union bmi160_pmu_status st = {
904 		.acc = BMI160_PMU_SUSPEND,
905 		.gyr = BMI160_PMU_SUSPEND,
906 		.mag = BMI160_PMU_SUSPEND,
907 	};
908 
909 	int ret = bmi160_pmu_set(dev, &st);
910 
911 	if (ret == 0) {
912 		memset(data->sample.raw, 0, sizeof(data->sample.raw));
913 	}
914 	return ret;
915 }
916 
bmi160_init(const struct device * dev)917 int bmi160_init(const struct device *dev)
918 {
919 	const struct bmi160_cfg *cfg = dev->config;
920 	struct bmi160_data *data = dev->data;
921 	uint8_t val = 0U;
922 	int32_t acc_range, gyr_range;
923 
924 	if (!cfg->bus_io->ready(dev)) {
925 		LOG_ERR("Bus not ready");
926 		return -EINVAL;
927 	}
928 
929 	/* reboot the chip */
930 	if (bmi160_byte_write(dev, BMI160_REG_CMD, BMI160_CMD_SOFT_RESET) < 0) {
931 		LOG_DBG("Cannot reboot chip.");
932 		return -EIO;
933 	}
934 
935 	k_busy_wait(1000);
936 
937 	/* do a dummy read from 0x7F to activate SPI */
938 	if (bmi160_byte_read(dev, BMI160_SPI_START, &val) < 0) {
939 		LOG_DBG("Cannot read from 0x7F..");
940 		return -EIO;
941 	}
942 
943 	k_busy_wait(150);
944 
945 	if (bmi160_byte_read(dev, BMI160_REG_CHIPID, &val) < 0) {
946 		LOG_DBG("Failed to read chip id.");
947 		return -EIO;
948 	}
949 
950 	if (val != BMI160_CHIP_ID) {
951 		LOG_DBG("Unsupported chip detected (0x%x)!", val);
952 		return -ENODEV;
953 	}
954 
955 	/* set default PMU for gyro, accelerometer */
956 	data->pmu_sts.gyr = BMI160_DEFAULT_PMU_GYR;
957 	data->pmu_sts.acc = BMI160_DEFAULT_PMU_ACC;
958 
959 	/* compass not supported, yet */
960 	data->pmu_sts.mag = BMI160_PMU_SUSPEND;
961 
962 	/* Start in a suspended state (never turning on the mems sensors) if
963 	 * PM_DEVICE_RUNTIME is enabled.
964 	 */
965 #ifdef CONFIG_PM_DEVICE_RUNTIME
966 	pm_device_init_suspended(dev);
967 
968 	int ret = pm_device_runtime_enable(dev);
969 
970 	if (ret < 0 && ret != -ENOSYS) {
971 		LOG_ERR("Failed to enabled runtime power management");
972 		return -EIO;
973 	}
974 #else
975 
976 	/*
977 	 * The next command will take around 100ms (contains some necessary busy
978 	 * waits), but we cannot do it in a separate thread since we need to
979 	 * guarantee the BMI is up and running, before the app's main() is
980 	 * called.
981 	 */
982 	if (bmi160_pmu_set(dev, &data->pmu_sts) < 0) {
983 		LOG_DBG("Failed to set power mode.");
984 		return -EIO;
985 	}
986 #endif
987 
988 	/* set accelerometer default range */
989 	if (bmi160_byte_write(dev, BMI160_REG_ACC_RANGE,
990 				BMI160_DEFAULT_RANGE_ACC) < 0) {
991 		LOG_DBG("Cannot set default range for accelerometer.");
992 		return -EIO;
993 	}
994 
995 	acc_range = bmi160_acc_reg_val_to_range(BMI160_DEFAULT_RANGE_ACC);
996 
997 	data->scale.acc = BMI160_ACC_SCALE(acc_range);
998 
999 	/* set gyro default range */
1000 	if (bmi160_byte_write(dev, BMI160_REG_GYR_RANGE,
1001 			      BMI160_DEFAULT_RANGE_GYR) < 0) {
1002 		LOG_DBG("Cannot set default range for gyroscope.");
1003 		return -EIO;
1004 	}
1005 
1006 	gyr_range = bmi160_gyr_reg_val_to_range(BMI160_DEFAULT_RANGE_GYR);
1007 
1008 	data->scale.gyr = BMI160_GYR_SCALE(gyr_range);
1009 
1010 	if (bmi160_reg_field_update(dev, BMI160_REG_ACC_CONF,
1011 				    BMI160_ACC_CONF_ODR_POS,
1012 				    BMI160_ACC_CONF_ODR_MASK,
1013 				    BMI160_DEFAULT_ODR_ACC) < 0) {
1014 		LOG_DBG("Failed to set accel's default ODR.");
1015 		return -EIO;
1016 	}
1017 
1018 	if (bmi160_reg_field_update(dev, BMI160_REG_GYR_CONF,
1019 				    BMI160_GYR_CONF_ODR_POS,
1020 				    BMI160_GYR_CONF_ODR_MASK,
1021 				    BMI160_DEFAULT_ODR_GYR) < 0) {
1022 		LOG_DBG("Failed to set gyro's default ODR.");
1023 		return -EIO;
1024 	}
1025 
1026 #ifdef CONFIG_BMI160_TRIGGER
1027 	if (bmi160_trigger_mode_init(dev) < 0) {
1028 		LOG_DBG("Cannot set up trigger mode.");
1029 		return -EINVAL;
1030 	}
1031 #endif
1032 
1033 	return 0;
1034 }
1035 
bmi160_pm(const struct device * dev,enum pm_device_action action)1036 int bmi160_pm(const struct device *dev, enum pm_device_action action)
1037 {
1038 	int ret = 0;
1039 
1040 	switch (action) {
1041 	case PM_DEVICE_ACTION_RESUME:
1042 		bmi160_resume(dev);
1043 		break;
1044 	case PM_DEVICE_ACTION_SUSPEND:
1045 		bmi160_suspend(dev);
1046 		break;
1047 	default:
1048 		ret = -ENOTSUP;
1049 	}
1050 
1051 	return ret;
1052 }
1053 
1054 #if defined(CONFIG_BMI160_TRIGGER)
1055 #define BMI160_TRIGGER_CFG(inst) \
1056 	.interrupt = GPIO_DT_SPEC_INST_GET(inst, int_gpios),
1057 #else
1058 #define BMI160_TRIGGER_CFG(inst)
1059 #endif
1060 
1061 #define BMI160_DEVICE_INIT(inst)								\
1062 	IF_ENABLED(CONFIG_PM_DEVICE_RUNTIME, (PM_DEVICE_DT_INST_DEFINE(inst, bmi160_pm)));	\
1063 	SENSOR_DEVICE_DT_INST_DEFINE(inst, bmi160_init,						\
1064 		COND_CODE_1(CONFIG_PM_DEVICE_RUNTIME, (PM_DEVICE_DT_INST_GET(inst)), (NULL)),	\
1065 		&bmi160_data_##inst, &bmi160_cfg_##inst,					\
1066 		POST_KERNEL, CONFIG_SENSOR_INIT_PRIORITY,					\
1067 		&bmi160_api);
1068 
1069 /* Instantiation macros used when a device is on a SPI bus */
1070 #define BMI160_DEFINE_SPI(inst)						   \
1071 	static struct bmi160_data bmi160_data_##inst;			   \
1072 	static const struct bmi160_cfg bmi160_cfg_##inst = {		   \
1073 		.bus.spi = SPI_DT_SPEC_INST_GET(inst, SPI_WORD_SET(8), 0), \
1074 		.bus_io = &bmi160_bus_io_spi,				   \
1075 		BMI160_TRIGGER_CFG(inst)				   \
1076 	};								   \
1077 	BMI160_DEVICE_INIT(inst)
1078 
1079 /* Instantiation macros used when a device is on an I2C bus */
1080 #define BMI160_CONFIG_I2C(inst)			       \
1081 	{					       \
1082 		.bus.i2c = I2C_DT_SPEC_INST_GET(inst), \
1083 		.bus_io = &bmi160_bus_io_i2c,	       \
1084 		BMI160_TRIGGER_CFG(inst)	       \
1085 	}
1086 
1087 #define BMI160_DEFINE_I2C(inst)							    \
1088 	static struct bmi160_data bmi160_data_##inst;				    \
1089 	static const struct bmi160_cfg bmi160_cfg_##inst = BMI160_CONFIG_I2C(inst); \
1090 	BMI160_DEVICE_INIT(inst)
1091 
1092 /*
1093  * Main instantiation macro. Use of COND_CODE_1() selects the right
1094  * bus-specific macro at preprocessor time.
1095  */
1096 #define BMI160_DEFINE(inst)						\
1097 	COND_CODE_1(DT_INST_ON_BUS(inst, spi),				\
1098 		    (BMI160_DEFINE_SPI(inst)),				\
1099 		    (BMI160_DEFINE_I2C(inst)))
1100 
1101 DT_INST_FOREACH_STATUS_OKAY(BMI160_DEFINE)
1102