1 /*
2  * Copyright (c) 2023 Würth Elektronik eiSos GmbH & Co. KG
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 #include "weplatform_i2c.h"
8 
9 #include <errno.h>
10 
11 #ifdef CONFIG_I2C
12 #include <zephyr/drivers/i2c.h>
13 #endif /* CONFIG_I2C */
14 
15 /**
16  * @brief Read data starting from the addressed register via I2C
17  * @param[in] interface Sensor interface
18  * @param[in] regAdr The register address to read from
19  * @param[in] numBytesToRead Number of bytes to read
20  * @param[out] data The read data will be stored here
21  * @retval Error code
22  */
WE_ReadReg_I2C(WE_sensorInterface_t * interface,uint8_t regAdr,uint16_t numBytesToRead,uint8_t * data)23 inline int8_t WE_ReadReg_I2C(WE_sensorInterface_t *interface, uint8_t regAdr,
24 			     uint16_t numBytesToRead, uint8_t *data)
25 {
26 	int status = 0;
27 
28 #ifdef CONFIG_I2C
29 	if (numBytesToRead > 1 && interface->options.i2c.useRegAddrMsbForMultiBytesRead) {
30 		/*
31 		 * Register address most significant bit is used to
32 		 * enable multi bytes read
33 		 */
34 		WRITE_BIT(regAdr, 7, 1);
35 	}
36 	if (interface->options.i2c.slaveTransmitterMode) {
37 		status = i2c_read_dt(interface->handle, data, numBytesToRead);
38 	} else {
39 		status = i2c_burst_read_dt(interface->handle, regAdr, data, numBytesToRead);
40 	}
41 #else
42 	status = -EIO;
43 #endif /* CONFIG_I2C */
44 
45 	return status == 0 ? WE_SUCCESS : WE_FAIL;
46 }
47 
48 /**
49  * @brief Write data starting from the addressed register via I2C
50  * @param[in] interface Sensor interface
51  * @param[in] regAdr Address of register to be written
52  * @param[in] numBytesToWrite Number of bytes to write
53  * @param[in] data Data to be written
54  * @retval Error code
55  */
WE_WriteReg_I2C(WE_sensorInterface_t * interface,uint8_t regAdr,uint16_t numBytesToWrite,uint8_t * data)56 inline int8_t WE_WriteReg_I2C(WE_sensorInterface_t *interface, uint8_t regAdr,
57 			      uint16_t numBytesToWrite, uint8_t *data)
58 {
59 	int status = 0;
60 
61 #ifdef CONFIG_I2C
62 	status = i2c_burst_write_dt(interface->handle, regAdr, data, numBytesToWrite);
63 #else
64 	status = -EIO;
65 #endif /* CONFIG_I2C */
66 
67 	return status == 0 ? WE_SUCCESS : WE_FAIL;
68 }
69