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 #define DT_DRV_COMPAT st_iis2dh
12 
13 #include <string.h>
14 #include "iis2dh.h"
15 #include <zephyr/logging/log.h>
16 
17 #if DT_ANY_INST_ON_BUS_STATUS_OKAY(spi)
18 
19 #define IIS2DH_SPI_READM	(3 << 6)	/* 0xC0 */
20 #define IIS2DH_SPI_WRITEM	(1 << 6)	/* 0x40 */
21 
22 LOG_MODULE_DECLARE(IIS2DH, CONFIG_SENSOR_LOG_LEVEL);
23 
iis2dh_spi_read(const struct device * dev,uint8_t reg,uint8_t * data,uint16_t len)24 static int iis2dh_spi_read(const struct device *dev, uint8_t reg, uint8_t *data, uint16_t len)
25 {
26 	const struct iis2dh_device_config *config = dev->config;
27 	uint8_t buffer_tx[2] = { reg | IIS2DH_SPI_READM, 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 = data,
43 			.len = len,
44 		}
45 	};
46 	const struct spi_buf_set rx = {
47 		.buffers = rx_buf,
48 		.count = 2
49 	};
50 
51 	if (spi_transceive_dt(&config->spi, &tx, &rx)) {
52 		return -EIO;
53 	}
54 
55 	return 0;
56 }
57 
iis2dh_spi_write(const struct device * dev,uint8_t reg,uint8_t * data,uint16_t len)58 static int iis2dh_spi_write(const struct device *dev, uint8_t reg, uint8_t *data, uint16_t len)
59 {
60 	const struct iis2dh_device_config *config = dev->config;
61 	uint8_t buffer_tx[1] = { reg | IIS2DH_SPI_WRITEM };
62 	const struct spi_buf tx_buf[2] = {
63 		{
64 			.buf = buffer_tx,
65 			.len = 1,
66 		},
67 		{
68 			.buf = data,
69 			.len = len,
70 		}
71 	};
72 	const struct spi_buf_set tx = {
73 		.buffers = tx_buf,
74 		.count = 2
75 	};
76 
77 
78 	if (spi_write_dt(&config->spi, &tx)) {
79 		return -EIO;
80 	}
81 
82 	return 0;
83 }
84 
85 stmdev_ctx_t iis2dh_spi_ctx = {
86 	.read_reg = (stmdev_read_ptr) iis2dh_spi_read,
87 	.write_reg = (stmdev_write_ptr) iis2dh_spi_write,
88 	.mdelay = (stmdev_mdelay_ptr) stmemsc_mdelay,
89 };
90 
iis2dh_spi_init(const struct device * dev)91 int iis2dh_spi_init(const struct device *dev)
92 {
93 	struct iis2dh_data *data = dev->data;
94 	const struct iis2dh_device_config *config = dev->config;
95 
96 	if (!spi_is_ready_dt(&config->spi)) {
97 		LOG_ERR("Bus device is not ready");
98 		return -ENODEV;
99 	}
100 
101 	data->ctx = &iis2dh_spi_ctx;
102 	data->ctx->handle = (void *)dev;
103 
104 	return 0;
105 }
106 #endif /* DT_ANY_INST_ON_BUS_STATUS_OKAY(spi) */
107