1 /* ST Microelectronics ISM330DHCX 6-axis IMU sensor 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/ism330dhcx.pdf
9  */
10 
11 #define DT_DRV_COMPAT st_ism330dhcx
12 
13 #include <string.h>
14 #include "ism330dhcx.h"
15 #include <zephyr/logging/log.h>
16 
17 #if DT_ANY_INST_ON_BUS_STATUS_OKAY(spi)
18 
19 #define ISM330DHCX_SPI_READ		(1 << 7)
20 
21 LOG_MODULE_DECLARE(ISM330DHCX, CONFIG_SENSOR_LOG_LEVEL);
22 
ism330dhcx_spi_read(const struct device * dev,uint8_t reg_addr,uint8_t * value,uint8_t len)23 static int ism330dhcx_spi_read(const struct device *dev, uint8_t reg_addr, uint8_t *value,
24 			       uint8_t len)
25 {
26 	const struct ism330dhcx_config *cfg = dev->config;
27 	uint8_t buffer_tx[2] = { reg_addr | ISM330DHCX_SPI_READ, 0 };
28 	const struct spi_buf tx_buf = {
29 			.buf = buffer_tx,
30 			.len = 2,
31 	};
32 	const struct spi_buf_set tx = {
33 		.buffers = &tx_buf,
34 		.count = 1
35 	};
36 	const struct spi_buf rx_buf[2] = {
37 		{
38 			.buf = NULL,
39 			.len = 1,
40 		},
41 		{
42 			.buf = value,
43 			.len = len,
44 		}
45 	};
46 	const struct spi_buf_set rx = {
47 		.buffers = rx_buf,
48 		.count = 2
49 	};
50 
51 
52 	if (len > 64) {
53 		return -EIO;
54 	}
55 
56 	if (spi_transceive_dt(&cfg->spi, &tx, &rx)) {
57 		return -EIO;
58 	}
59 
60 	return 0;
61 }
62 
ism330dhcx_spi_write(const struct device * dev,uint8_t reg_addr,uint8_t * value,uint8_t len)63 static int ism330dhcx_spi_write(const struct device *dev, uint8_t reg_addr, uint8_t *value,
64 				uint8_t len)
65 {
66 	const struct ism330dhcx_config *cfg = dev->config;
67 	uint8_t buffer_tx[1] = { reg_addr & ~ISM330DHCX_SPI_READ };
68 	const struct spi_buf tx_buf[2] = {
69 		{
70 			.buf = buffer_tx,
71 			.len = 1,
72 		},
73 		{
74 			.buf = value,
75 			.len = len,
76 		}
77 	};
78 	const struct spi_buf_set tx = {
79 		.buffers = tx_buf,
80 		.count = 2
81 	};
82 
83 
84 	if (len > 64) {
85 		return -EIO;
86 	}
87 
88 	if (spi_write_dt(&cfg->spi, &tx)) {
89 		return -EIO;
90 	}
91 
92 	return 0;
93 }
94 
ism330dhcx_spi_init(const struct device * dev)95 int ism330dhcx_spi_init(const struct device *dev)
96 {
97 	struct ism330dhcx_data *data = dev->data;
98 	const struct ism330dhcx_config *cfg = dev->config;
99 
100 	if (!spi_is_ready_dt(&cfg->spi)) {
101 		LOG_ERR("SPI bus is not ready");
102 		return -ENODEV;
103 	};
104 
105 	data->ctx_spi.read_reg = (stmdev_read_ptr) ism330dhcx_spi_read;
106 	data->ctx_spi.write_reg = (stmdev_write_ptr) ism330dhcx_spi_write;
107 	data->ctx_spi.mdelay = (stmdev_mdelay_ptr) stmemsc_mdelay;
108 
109 	data->ctx = &data->ctx_spi;
110 	data->ctx->handle = (void *)dev;
111 
112 	return 0;
113 }
114 #endif /* DT_ANY_INST_ON_BUS_STATUS_OKAY(spi) */
115