1 /* ST Microelectronics IIS2DH 3-axis accelerometer driver
2  *
3  * Copyright (c) 2020 STMicroelectronics
4  *
5  * SPDX-License-Identifier: Apache-2.0
6  *
7  * Datasheet:
8  * https://www.st.com/resource/en/datasheet/iis2dh.pdf
9  */
10 
11 #ifndef ZEPHYR_DRIVERS_SENSOR_IIS2DH_IIS2DH_H_
12 #define ZEPHYR_DRIVERS_SENSOR_IIS2DH_IIS2DH_H_
13 
14 #include <zephyr/drivers/i2c.h>
15 #include <zephyr/drivers/spi.h>
16 #include <zephyr/drivers/gpio.h>
17 #include <zephyr/sys/util.h>
18 #include <zephyr/drivers/sensor.h>
19 #include <zephyr/kernel.h>
20 #include <stmemsc.h>
21 #include "iis2dh_reg.h"
22 
23 /*
24  * Return ODR reg value based on data rate set
25  */
26 #define IIS2DH_ODR_TO_REG_HR(_lp, _odr) \
27 	((_odr == 0) ? IIS2DH_POWER_DOWN : \
28 	((_odr < 10) ? IIS2DH_ODR_1Hz : \
29 	((_odr < 25) ? IIS2DH_ODR_10Hz : \
30 	((_lp == IIS2DH_LP_8bit) && (_odr >= 5376) ? IIS2DH_ODR_5kHz376_LP_1kHz344_NM_HP : \
31 	((_lp != IIS2DH_LP_8bit) && (_odr >= 1344) ? IIS2DH_ODR_5kHz376_LP_1kHz344_NM_HP : \
32 	((_lp == IIS2DH_LP_8bit) && (_odr >= 1600) ? IIS2DH_ODR_1kHz620_LP : \
33 	((_lp != IIS2DH_LP_8bit) && (_odr >= 800) ? IIS2DH_ODR_400Hz : \
34 	((31 - __builtin_clz(_odr / 25))) + 3)))))))
35 
36 /* FS reg value from Full Scale */
37 #define IIS2DH_FS_TO_REG(_fs)	(30 - __builtin_clz(_fs))
38 
39 /**
40  * struct iis2dh_device_config - iis2dh hw configuration
41  * @spi: SPI bus spec.
42  * @i2c: I2C bus spec.
43  * @pm: Power mode (lis2dh_powermode).
44  * @int_gpio: GPIO spec for sensor pin interrupt.
45  */
46 struct iis2dh_device_config {
47 #if DT_ANY_INST_ON_BUS_STATUS_OKAY(spi)
48 	struct spi_dt_spec spi;
49 #endif
50 #if DT_ANY_INST_ON_BUS_STATUS_OKAY(i2c)
51 	struct i2c_dt_spec i2c;
52 #endif
53 	uint8_t pm;
54 #ifdef CONFIG_IIS2DH_TRIGGER
55 	struct gpio_dt_spec int_gpio;
56 #endif /* CONFIG_IIS2DH_TRIGGER */
57 };
58 
59 /* sensor data */
60 struct iis2dh_data {
61 	int16_t acc[3];
62 	uint32_t gain;
63 
64 	stmdev_ctx_t *ctx;
65 #ifdef CONFIG_IIS2DH_TRIGGER
66 	const struct device *dev;
67 	struct gpio_callback gpio_cb;
68 	sensor_trigger_handler_t drdy_handler;
69 	const struct sensor_trigger *drdy_trig;
70 #if defined(CONFIG_IIS2DH_TRIGGER_OWN_THREAD)
71 	K_KERNEL_STACK_MEMBER(thread_stack, CONFIG_IIS2DH_THREAD_STACK_SIZE);
72 	struct k_thread thread;
73 	struct k_sem gpio_sem;
74 #elif defined(CONFIG_IIS2DH_TRIGGER_GLOBAL_THREAD)
75 	struct k_work work;
76 #endif /* CONFIG_IIS2DH_TRIGGER_GLOBAL_THREAD */
77 #endif /* CONFIG_IIS2DH_TRIGGER */
78 };
79 
80 int iis2dh_i2c_init(const struct device *dev);
81 int iis2dh_spi_init(const struct device *dev);
82 
83 #ifdef CONFIG_IIS2DH_TRIGGER
84 int iis2dh_init_interrupt(const struct device *dev);
85 int iis2dh_trigger_set(const struct device *dev,
86 			  const struct sensor_trigger *trig,
87 			  sensor_trigger_handler_t handler);
88 #endif /* CONFIG_IIS2DH_TRIGGER */
89 
90 #endif /* ZEPHYR_DRIVERS_SENSOR_IIS2DH_IIS2DH_H_ */
91