1 /* ST Microelectronics IIS3DHHC accelerometer sensor
2  *
3  * Copyright (c) 2019 STMicroelectronics
4  *
5  * SPDX-License-Identifier: Apache-2.0
6  *
7  * Datasheet:
8  * https://www.st.com/resource/en/datasheet/iis3dhhc.pdf
9  */
10 
11 #define DT_DRV_COMPAT st_iis3dhhc
12 
13 #include <string.h>
14 #include "iis3dhhc.h"
15 #include <zephyr/logging/log.h>
16 
17 #if DT_ANY_INST_ON_BUS_STATUS_OKAY(spi)
18 
19 #define IIS3DHHC_SPI_READ		(1 << 7)
20 
21 LOG_MODULE_DECLARE(IIS3DHHC, CONFIG_SENSOR_LOG_LEVEL);
22 
iis3dhhc_spi_read(const struct device * dev,uint8_t reg,uint8_t * data,uint16_t len)23 static int iis3dhhc_spi_read(const struct device *dev, uint8_t reg, uint8_t *data, uint16_t len)
24 {
25 	const struct iis3dhhc_config *config = dev->config;
26 	uint8_t buffer_tx[2] = { reg | IIS3DHHC_SPI_READ, 0 };
27 	const struct spi_buf tx_buf = {
28 			.buf = buffer_tx,
29 			.len = 2,
30 	};
31 	const struct spi_buf_set tx = {
32 		.buffers = &tx_buf,
33 		.count = 1
34 	};
35 	const struct spi_buf rx_buf[2] = {
36 		{
37 			.buf = NULL,
38 			.len = 1,
39 		},
40 		{
41 			.buf = data,
42 			.len = len,
43 		}
44 	};
45 	const struct spi_buf_set rx = {
46 		.buffers = rx_buf,
47 		.count = 2
48 	};
49 
50 	if (spi_transceive_dt(&config->spi, &tx, &rx)) {
51 		return -EIO;
52 	}
53 
54 	return 0;
55 }
56 
iis3dhhc_spi_write(const struct device * dev,uint8_t reg,uint8_t * data,uint16_t len)57 static int iis3dhhc_spi_write(const struct device *dev, uint8_t reg, uint8_t *data, uint16_t len)
58 {
59 	const struct iis3dhhc_config *config = dev->config;
60 	uint8_t buffer_tx[1] = { reg & ~IIS3DHHC_SPI_READ };
61 	const struct spi_buf tx_buf[2] = {
62 		{
63 			.buf = buffer_tx,
64 			.len = 1,
65 		},
66 		{
67 			.buf = data,
68 			.len = len,
69 		}
70 	};
71 	const struct spi_buf_set tx = {
72 		.buffers = tx_buf,
73 		.count = 2
74 	};
75 
76 
77 	if (spi_write_dt(&config->spi, &tx)) {
78 		return -EIO;
79 	}
80 
81 	return 0;
82 }
83 
84 stmdev_ctx_t iis3dhhc_spi_ctx = {
85 	.read_reg = (stmdev_read_ptr) iis3dhhc_spi_read,
86 	.write_reg = (stmdev_write_ptr) iis3dhhc_spi_write,
87 	.mdelay = (stmdev_mdelay_ptr) stmemsc_mdelay,
88 };
89 
iis3dhhc_spi_init(const struct device * dev)90 int iis3dhhc_spi_init(const struct device *dev)
91 {
92 	struct iis3dhhc_data *data = dev->data;
93 	const struct iis3dhhc_config *config = dev->config;
94 
95 	if (!spi_is_ready_dt(&config->spi)) {
96 		LOG_ERR("SPI bus is not ready");
97 		return -ENODEV;
98 	};
99 
100 	data->ctx = &iis3dhhc_spi_ctx;
101 	data->ctx->handle = (void *)dev;
102 
103 	return 0;
104 }
105 #endif /* DT_ANY_INST_ON_BUS_STATUS_OKAY(spi) */
106