1 /* ST Microelectronics LIS2DH 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/lis2dh.pdf
9  */
10 
11 #define DT_DRV_COMPAT st_lis2dh
12 
13 #include <string.h>
14 #include <zephyr/drivers/i2c.h>
15 #include <zephyr/logging/log.h>
16 
17 #include "lis2dh.h"
18 
19 #if DT_ANY_INST_ON_BUS_STATUS_OKAY(i2c)
20 
21 LOG_MODULE_DECLARE(lis2dh, CONFIG_SENSOR_LOG_LEVEL);
22 
lis2dh_i2c_read_data(const struct device * dev,uint8_t reg_addr,uint8_t * value,uint8_t len)23 static int lis2dh_i2c_read_data(const struct device *dev, uint8_t reg_addr,
24 				 uint8_t *value, uint8_t len)
25 {
26 	const struct lis2dh_config *cfg = dev->config;
27 
28 	return i2c_burst_read_dt(&cfg->bus_cfg.i2c, reg_addr | LIS2DH_AUTOINCREMENT_ADDR, value,
29 				 len);
30 }
31 
lis2dh_i2c_write_data(const struct device * dev,uint8_t reg_addr,uint8_t * value,uint8_t len)32 static int lis2dh_i2c_write_data(const struct device *dev, uint8_t reg_addr,
33 				  uint8_t *value, uint8_t len)
34 {
35 	const struct lis2dh_config *cfg = dev->config;
36 
37 	return i2c_burst_write_dt(&cfg->bus_cfg.i2c, reg_addr | LIS2DH_AUTOINCREMENT_ADDR, value,
38 				  len);
39 }
40 
lis2dh_i2c_read_reg(const struct device * dev,uint8_t reg_addr,uint8_t * value)41 static int lis2dh_i2c_read_reg(const struct device *dev, uint8_t reg_addr,
42 				uint8_t *value)
43 {
44 	const struct lis2dh_config *cfg = dev->config;
45 
46 	return i2c_reg_read_byte_dt(&cfg->bus_cfg.i2c, reg_addr, value);
47 }
48 
lis2dh_i2c_write_reg(const struct device * dev,uint8_t reg_addr,uint8_t value)49 static int lis2dh_i2c_write_reg(const struct device *dev, uint8_t reg_addr,
50 				uint8_t value)
51 {
52 	const struct lis2dh_config *cfg = dev->config;
53 
54 	return i2c_reg_write_byte_dt(&cfg->bus_cfg.i2c, reg_addr, value);
55 }
56 
lis2dh_i2c_update_reg(const struct device * dev,uint8_t reg_addr,uint8_t mask,uint8_t value)57 static int lis2dh_i2c_update_reg(const struct device *dev, uint8_t reg_addr,
58 				  uint8_t mask, uint8_t value)
59 {
60 	const struct lis2dh_config *cfg = dev->config;
61 
62 	return i2c_reg_update_byte_dt(&cfg->bus_cfg.i2c, reg_addr, mask, value);
63 }
64 
65 static const struct lis2dh_transfer_function lis2dh_i2c_transfer_fn = {
66 	.read_data = lis2dh_i2c_read_data,
67 	.write_data = lis2dh_i2c_write_data,
68 	.read_reg  = lis2dh_i2c_read_reg,
69 	.write_reg  = lis2dh_i2c_write_reg,
70 	.update_reg = lis2dh_i2c_update_reg,
71 };
72 
lis2dh_i2c_init(const struct device * dev)73 int lis2dh_i2c_init(const struct device *dev)
74 {
75 	struct lis2dh_data *data = dev->data;
76 	const struct lis2dh_config *cfg = dev->config;
77 
78 	if (!device_is_ready(cfg->bus_cfg.i2c.bus)) {
79 		LOG_ERR("Bus device is not ready");
80 		return -ENODEV;
81 	}
82 
83 	data->hw_tf = &lis2dh_i2c_transfer_fn;
84 
85 	return 0;
86 }
87 #endif /* DT_ANY_INST_ON_BUS_STATUS_OKAY(i2c) */
88