1 /* adxl372_i2c.c - I2C routines for ADXL372 driver
2 */
3
4 /*
5 * Copyright (c) 2018 STMicroelectronics
6 *
7 * SPDX-License-Identifier: Apache-2.0
8 */
9
10 #define DT_DRV_COMPAT adi_adxl372
11
12 #include <string.h>
13 #include <zephyr/logging/log.h>
14
15 #include "adxl372.h"
16
17 #if DT_ANY_INST_ON_BUS_STATUS_OKAY(i2c)
18
19 LOG_MODULE_DECLARE(ADXL372, CONFIG_SENSOR_LOG_LEVEL);
20
adxl372_bus_access(const struct device * dev,uint8_t reg,void * data,size_t length)21 static int adxl372_bus_access(const struct device *dev, uint8_t reg,
22 void *data, size_t length)
23 {
24 const struct adxl372_dev_config *config = dev->config;
25
26 if (reg & ADXL372_READ) {
27 return i2c_burst_read_dt(&config->i2c,
28 ADXL372_TO_I2C_REG(reg),
29 (uint8_t *) data, length);
30 } else {
31 if (length != 1) {
32 return -EINVAL;
33 }
34
35 return i2c_reg_write_byte_dt(&config->i2c,
36 ADXL372_TO_I2C_REG(reg),
37 *(uint8_t *)data);
38 }
39 }
40
adxl372_i2c_reg_read(const struct device * dev,uint8_t reg_addr,uint8_t * reg_data)41 static int adxl372_i2c_reg_read(const struct device *dev, uint8_t reg_addr,
42 uint8_t *reg_data)
43 {
44 return adxl372_bus_access(dev, ADXL372_REG_READ(reg_addr), reg_data, 1);
45 }
46
adxl372_i2c_reg_read_multiple(const struct device * dev,uint8_t reg_addr,uint8_t * reg_data,uint16_t count)47 static int adxl372_i2c_reg_read_multiple(const struct device *dev,
48 uint8_t reg_addr,
49 uint8_t *reg_data,
50 uint16_t count)
51 {
52 return adxl372_bus_access(dev, ADXL372_REG_READ(reg_addr),
53 reg_data, count);
54 }
55
adxl372_i2c_reg_write(const struct device * dev,uint8_t reg_addr,uint8_t reg_data)56 static int adxl372_i2c_reg_write(const struct device *dev,
57 uint8_t reg_addr,
58 uint8_t reg_data)
59 {
60 return adxl372_bus_access(dev, ADXL372_REG_WRITE(reg_addr),
61 ®_data, 1);
62 }
63
64
adxl372_i2c_reg_write_mask(const struct device * dev,uint8_t reg_addr,uint32_t mask,uint8_t data)65 int adxl372_i2c_reg_write_mask(const struct device *dev,
66 uint8_t reg_addr,
67 uint32_t mask,
68 uint8_t data)
69 {
70 int ret;
71 uint8_t tmp;
72
73 ret = adxl372_i2c_reg_read(dev, reg_addr, &tmp);
74 if (ret) {
75 return ret;
76 }
77
78 tmp &= ~mask;
79 tmp |= data;
80
81 return adxl372_i2c_reg_write(dev, reg_addr, tmp);
82 }
83
84 static const struct adxl372_transfer_function adxl372_i2c_transfer_fn = {
85 .read_reg_multiple = adxl372_i2c_reg_read_multiple,
86 .write_reg = adxl372_i2c_reg_write,
87 .read_reg = adxl372_i2c_reg_read,
88 .write_reg_mask = adxl372_i2c_reg_write_mask,
89 };
90
adxl372_i2c_init(const struct device * dev)91 int adxl372_i2c_init(const struct device *dev)
92 {
93 struct adxl372_data *data = dev->data;
94 const struct adxl372_dev_config *config = dev->config;
95
96 data->hw_tf = &adxl372_i2c_transfer_fn;
97
98 if (!device_is_ready(config->i2c.bus)) {
99 return -ENODEV;
100 }
101
102 return 0;
103 }
104 #endif /* DT_ANY_INST_ON_BUS_STATUS_OKAY(i2c) */
105