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 /*
15  * SPI read
16  */
stmemsc_spi_read(const struct spi_dt_spec * stmemsc,uint8_t reg_addr,uint8_t * value,uint8_t len)17 int stmemsc_spi_read(const struct spi_dt_spec *stmemsc,
18 		     uint8_t reg_addr, uint8_t *value, uint8_t len)
19 {
20 	uint8_t buffer_tx[2] = { reg_addr | SPI_READ, 0 };
21 
22 	/*  write 1 byte with reg addr (msb at 1) + 1 dummy byte */
23 	const struct spi_buf tx_buf = { .buf = buffer_tx, .len = 2, };
24 	const struct spi_buf_set tx = { .buffers = &tx_buf, .count = 1 };
25 
26 	/*
27 	 *   transaction #1: dummy read to skip first byte
28 	 *   transaction #2: read "len" byte of data
29 	 */
30 	const struct spi_buf rx_buf[2] = {
31 		{ .buf = NULL, .len = 1, },
32 		{ .buf = value, .len = len, }
33 	};
34 	const struct spi_buf_set rx = { .buffers = rx_buf, .count = 2 };
35 
36 	return spi_transceive_dt(stmemsc, &tx, &rx);
37 }
38 
39 /*
40  * SPI write
41  */
stmemsc_spi_write(const struct spi_dt_spec * stmemsc,uint8_t reg_addr,uint8_t * value,uint8_t len)42 int stmemsc_spi_write(const struct spi_dt_spec *stmemsc,
43 		      uint8_t reg_addr, uint8_t *value, uint8_t len)
44 {
45 	uint8_t buffer_tx[1] = { reg_addr & ~SPI_READ };
46 
47 	/*
48 	 *   transaction #1: write 1 byte with reg addr (msb at 0)
49 	 *   transaction #2: write "len" byte of data
50 	 */
51 	const struct spi_buf tx_buf[2] = {
52 		{ .buf = buffer_tx, .len = 1, },
53 		{ .buf = value, .len = len, }
54 	};
55 	const struct spi_buf_set tx = { .buffers = tx_buf, .count = 2 };
56 
57 	return spi_write_dt(stmemsc, &tx);
58 }
59