1 /*
2 * Copyright (c) 2023 Trackunit Corporation
3 *
4 * SPDX-License-Identifier: Apache-2.0
5 */
6
7 #include "bmi323.h"
8 #include <zephyr/device.h>
9 #include <zephyr/drivers/spi.h>
10
bosch_bmi323_spi_read_words(const void * context,uint8_t offset,uint16_t * words,uint16_t words_count)11 static int bosch_bmi323_spi_read_words(const void *context, uint8_t offset, uint16_t *words,
12 uint16_t words_count)
13 {
14 const struct spi_dt_spec *spi = (const struct spi_dt_spec *)context;
15 uint8_t address[2];
16 struct spi_buf transmit_buffer;
17 struct spi_buf_set transmit_buffer_set;
18 struct spi_buf receive_buffers[2];
19 struct spi_buf_set receive_buffers_set;
20 int ret;
21
22 address[0] = offset | 0x80;
23 address[1] = 0x00;
24
25 transmit_buffer.buf = address;
26 transmit_buffer.len = sizeof(address);
27
28 transmit_buffer_set.buffers = &transmit_buffer;
29 transmit_buffer_set.count = 1;
30
31 receive_buffers[0].buf = NULL;
32 receive_buffers[0].len = 2;
33 receive_buffers[1].buf = words;
34 receive_buffers[1].len = (words_count * 2);
35
36 receive_buffers_set.buffers = receive_buffers;
37 receive_buffers_set.count = 2;
38
39 ret = spi_transceive_dt(spi, &transmit_buffer_set, &receive_buffers_set);
40
41 k_usleep(2);
42
43 return ret;
44 }
45
bosch_bmi323_spi_write_words(const void * context,uint8_t offset,uint16_t * words,uint16_t words_count)46 static int bosch_bmi323_spi_write_words(const void *context, uint8_t offset, uint16_t *words,
47 uint16_t words_count)
48 {
49 const struct spi_dt_spec *spi = (const struct spi_dt_spec *)context;
50 uint8_t address;
51 struct spi_buf transmit_buffers[2];
52 struct spi_buf_set transmit_buffer_set;
53 int ret;
54
55 address = offset & 0x7F;
56
57 transmit_buffers[0].buf = &address;
58 transmit_buffers[0].len = 1;
59 transmit_buffers[1].buf = words;
60 transmit_buffers[1].len = (words_count * 2);
61
62 transmit_buffer_set.buffers = transmit_buffers;
63 transmit_buffer_set.count = 2;
64
65 ret = spi_write_dt(spi, &transmit_buffer_set);
66
67 k_usleep(2);
68
69 return ret;
70 }
71
bosch_bmi323_spi_init(const void * context)72 static int bosch_bmi323_spi_init(const void *context)
73 {
74 const struct spi_dt_spec *spi = (const struct spi_dt_spec *)context;
75 uint16_t sensor_id;
76 int ret;
77
78 if (spi_is_ready_dt(spi) == false) {
79 return -ENODEV;
80 }
81
82 ret = bosch_bmi323_spi_read_words(spi, 0, &sensor_id, 1);
83
84 if (ret < 0) {
85 return ret;
86 }
87
88 k_usleep(1500);
89
90 return 0;
91 }
92
93 const struct bosch_bmi323_bus_api bosch_bmi323_spi_bus_api = {
94 .read_words = bosch_bmi323_spi_read_words,
95 .write_words = bosch_bmi323_spi_write_words,
96 .init = bosch_bmi323_spi_init};
97