1 /*
2  * Copyright (c) 2024 TDK Invensense
3  * Copyright (c) 2022 Esco Medical ApS
4  * Copyright (c) 2020 TDK Invensense
5  *
6  * SPDX-License-Identifier: Apache-2.0
7  */
8 
9 /*
10  * Bus-specific functionality for ICM42670 accessed via SPI.
11  */
12 
13 #include "icm42670.h"
14 
15 #if CONFIG_SPI
16 
17 #include <zephyr/logging/log.h>
18 LOG_MODULE_DECLARE(ICM42670, CONFIG_SENSOR_LOG_LEVEL);
19 
icm42670_bus_check_spi(const union icm42670_bus * bus)20 static int icm42670_bus_check_spi(const union icm42670_bus *bus)
21 {
22 	return spi_is_ready_dt(&bus->spi) ? 0 : -ENODEV;
23 }
24 
icm42670_reg_read_spi(const union icm42670_bus * bus,uint8_t start,uint8_t * buf,uint32_t size)25 static int icm42670_reg_read_spi(const union icm42670_bus *bus, uint8_t start, uint8_t *buf,
26 				 uint32_t size)
27 
28 {
29 	uint8_t cmd[] = {(start | 0x80)};
30 	const struct spi_buf tx_buf = {.buf = cmd, .len = sizeof(cmd)};
31 	const struct spi_buf_set tx = {.buffers = &tx_buf, .count = 1};
32 	struct spi_buf rx_buf[2];
33 	const struct spi_buf_set rx = {.buffers = rx_buf, .count = ARRAY_SIZE(rx_buf)};
34 	int ret;
35 
36 	rx_buf[0].buf = NULL;
37 	rx_buf[0].len = 1;
38 
39 	rx_buf[1].len = size;
40 	rx_buf[1].buf = buf;
41 
42 	ret = spi_transceive_dt(&bus->spi, &tx, &rx);
43 	if (ret) {
44 		LOG_ERR("spi_transceive FAIL %d\n", ret);
45 		return ret;
46 	}
47 	return 0;
48 }
49 
icm42670_reg_write_spi(const union icm42670_bus * bus,uint8_t reg,uint8_t * buf,uint32_t size)50 static int icm42670_reg_write_spi(const union icm42670_bus *bus, uint8_t reg, uint8_t *buf,
51 				  uint32_t size)
52 {
53 	uint8_t cmd[] = {reg & 0x7F};
54 	const struct spi_buf tx_buf[2] = {{.buf = cmd, .len = sizeof(cmd)},
55 					  {.buf = buf, .len = size}};
56 	const struct spi_buf_set tx = {.buffers = tx_buf, .count = 2};
57 	int ret = spi_write_dt(&bus->spi, &tx);
58 
59 	if (ret) {
60 		LOG_ERR("spi_write FAIL %d\n", ret);
61 		return ret;
62 	}
63 	return 0;
64 }
65 
66 const struct icm42670_bus_io icm42670_bus_io_spi = {
67 	.check = icm42670_bus_check_spi,
68 	.read = icm42670_reg_read_spi,
69 	.write = icm42670_reg_write_spi,
70 };
71 
72 #endif /* CONFIG_SPI */
73