1 /* ST Microelectronics STMEMS hal i/f
2 *
3 * Copyright (c) 2021 STMicroelectronics
4 *
5 * SPDX-License-Identifier: Apache-2.0
6 *
7 * zephyrproject-rtos/modules/hal/st/sensor/stmemsc/
8 */
9
10 #include "stmemsc.h"
11
12 #define SPI_READ (1 << 7)
13
14 /* Enable address auto-increment on some stmemsc sensors */
15 #define STMEMSC_SPI_ADDR_AUTO_INCR BIT(6)
16
17 /*
18 * SPI read
19 */
stmemsc_spi_read(const struct spi_dt_spec * stmemsc,uint8_t reg_addr,uint8_t * value,uint8_t len)20 int stmemsc_spi_read(const struct spi_dt_spec *stmemsc,
21 uint8_t reg_addr, uint8_t *value, uint8_t len)
22 {
23 uint8_t buffer_tx[2] = { reg_addr | SPI_READ, 0 };
24
25 /* write 1 byte with reg addr (msb at 1) + 1 dummy byte */
26 const struct spi_buf tx_buf = { .buf = buffer_tx, .len = 2, };
27 const struct spi_buf_set tx = { .buffers = &tx_buf, .count = 1 };
28
29 /*
30 * transaction #1: dummy read to skip first byte
31 * transaction #2: read "len" byte of data
32 */
33 const struct spi_buf rx_buf[2] = {
34 { .buf = NULL, .len = 1, },
35 { .buf = value, .len = len, }
36 };
37 const struct spi_buf_set rx = { .buffers = rx_buf, .count = 2 };
38
39 return spi_transceive_dt(stmemsc, &tx, &rx);
40 }
41
42 /*
43 * SPI write
44 */
stmemsc_spi_write(const struct spi_dt_spec * stmemsc,uint8_t reg_addr,uint8_t * value,uint8_t len)45 int stmemsc_spi_write(const struct spi_dt_spec *stmemsc,
46 uint8_t reg_addr, uint8_t *value, uint8_t len)
47 {
48 uint8_t buffer_tx[1] = { reg_addr & ~SPI_READ };
49
50 /*
51 * transaction #1: write 1 byte with reg addr (msb at 0)
52 * transaction #2: write "len" byte of data
53 */
54 const struct spi_buf tx_buf[2] = {
55 { .buf = buffer_tx, .len = 1, },
56 { .buf = value, .len = len, }
57 };
58 const struct spi_buf_set tx = { .buffers = tx_buf, .count = 2 };
59
60 return spi_write_dt(stmemsc, &tx);
61 }
62
stmemsc_spi_read_incr(const struct spi_dt_spec * stmemsc,uint8_t reg_addr,uint8_t * value,uint8_t len)63 int stmemsc_spi_read_incr(const struct spi_dt_spec *stmemsc,
64 uint8_t reg_addr, uint8_t *value, uint8_t len)
65 {
66 reg_addr |= STMEMSC_SPI_ADDR_AUTO_INCR;
67 return stmemsc_spi_read(stmemsc, reg_addr, value, len);
68 }
69
stmemsc_spi_write_incr(const struct spi_dt_spec * stmemsc,uint8_t reg_addr,uint8_t * value,uint8_t len)70 int stmemsc_spi_write_incr(const struct spi_dt_spec *stmemsc,
71 uint8_t reg_addr, uint8_t *value, uint8_t len)
72 {
73 reg_addr |= STMEMSC_SPI_ADDR_AUTO_INCR;
74 return stmemsc_spi_write(stmemsc, reg_addr, value, len);
75 }
76