1 /* ST Microelectronics IIS2MDC 3-axis magnetometer sensor
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/iis2mdc.pdf
9  */
10 
11 #define DT_DRV_COMPAT st_iis2mdc
12 
13 #include <string.h>
14 #include "iis2mdc.h"
15 #include <zephyr/logging/log.h>
16 
17 #if DT_ANY_INST_ON_BUS_STATUS_OKAY(spi)
18 
19 #define IIS2MDC_SPI_READ		(1 << 7)
20 
21 LOG_MODULE_DECLARE(IIS2MDC, CONFIG_SENSOR_LOG_LEVEL);
22 
iis2mdc_spi_read(const struct device * dev,uint8_t reg,uint8_t * val,uint16_t len)23 static int iis2mdc_spi_read(const struct device *dev, uint8_t reg,
24 			    uint8_t *val, uint16_t len)
25 {
26 	const struct iis2mdc_dev_config *cfg = dev->config;
27 	uint8_t buffer_tx[2] = { reg | IIS2MDC_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 = val,
43 			.len = len,
44 		}
45 	};
46 	const struct spi_buf_set rx = {
47 		.buffers = rx_buf,
48 		.count = 2
49 	};
50 
51 	if (len > 64) {
52 		return -EIO;
53 	}
54 
55 	if (spi_transceive_dt(&cfg->spi, &tx, &rx)) {
56 		return -EIO;
57 	}
58 
59 	return 0;
60 }
61 
iis2mdc_spi_write(const struct device * dev,uint8_t reg,uint8_t * val,uint16_t len)62 static int iis2mdc_spi_write(const struct device *dev, uint8_t reg,
63 			     uint8_t *val, uint16_t len)
64 {
65 	const struct iis2mdc_dev_config *cfg = dev->config;
66 	uint8_t buffer_tx[1] = { reg & ~IIS2MDC_SPI_READ };
67 	const struct spi_buf tx_buf[2] = {
68 		{
69 			.buf = buffer_tx,
70 			.len = 1,
71 		},
72 		{
73 			.buf = val,
74 			.len = len,
75 		}
76 	};
77 	const struct spi_buf_set tx = {
78 		.buffers = tx_buf,
79 		.count = 2
80 	};
81 
82 	if (len > 64) {
83 		return -EIO;
84 	}
85 
86 	if (spi_write_dt(&cfg->spi, &tx)) {
87 		return -EIO;
88 	}
89 
90 	return 0;
91 }
92 
iis2mdc_spi_init(const struct device * dev)93 int iis2mdc_spi_init(const struct device *dev)
94 {
95 	struct iis2mdc_data *data = dev->data;
96 	const struct iis2mdc_dev_config *const cfg = dev->config;
97 
98 	if (!spi_is_ready_dt(&cfg->spi)) {
99 		LOG_ERR("SPI bus is not ready");
100 		return -ENODEV;
101 	}
102 
103 	data->ctx_spi.read_reg = (stmdev_read_ptr) iis2mdc_spi_read;
104 	data->ctx_spi.write_reg = (stmdev_write_ptr) iis2mdc_spi_write;
105 	data->ctx_spi.mdelay = (stmdev_mdelay_ptr) stmemsc_mdelay;
106 
107 	data->ctx = &data->ctx_spi;
108 	data->ctx->handle = (void *)dev;
109 
110 	return 0;
111 }
112 #endif /* DT_ANY_INST_ON_BUS_STATUS_OKAY(spi) */
113