1 /*
2  * Copyright (c) 2016, 2017 Intel Corporation
3  * Copyright (c) 2017 IpTronix S.r.l.
4  * Copyright (c) 2021 Nordic Semiconductor ASA
5  *
6  * SPDX-License-Identifier: Apache-2.0
7  */
8 
9 /*
10  * Bus-specific functionality for BMP388s accessed via SPI.
11  */
12 
13 #include <zephyr/logging/log.h>
14 #include "bmp388.h"
15 
16 #ifdef BMP3XX_USE_SPI_BUS
17 
18 LOG_MODULE_DECLARE(BMP388, CONFIG_SENSOR_LOG_LEVEL);
19 
bmp388_bus_check_spi(const union bmp388_bus * bus)20 static int bmp388_bus_check_spi(const union bmp388_bus *bus)
21 {
22 	return spi_is_ready_dt(&bus->spi) ? 0 : -ENODEV;
23 }
24 
bmp388_reg_read_spi(const union bmp388_bus * bus,uint8_t regaddr,uint8_t * buf,int size)25 static int bmp388_reg_read_spi(const union bmp388_bus *bus, uint8_t regaddr, uint8_t *buf, int size)
26 {
27 	int ret;
28 
29 	if ((size <= 0) || (size > BMP388_SAMPLE_BUFFER_SIZE)) {
30 		return -EINVAL;
31 	}
32 
33 	uint8_t buffer[size + 2];
34 	const struct spi_buf rxtx_buf = {
35 		.buf = &buffer,
36 		.len = ARRAY_SIZE(buffer),
37 	};
38 	const struct spi_buf_set rxtx = {
39 		.buffers = &rxtx_buf,
40 		.count = 1
41 	};
42 
43 	memset(buffer, 0x00, ARRAY_SIZE(buffer));
44 	buffer[0] = (regaddr) | 0x80;
45 
46 	ret = spi_transceive_dt(&bus->spi, &rxtx, &rxtx);
47 	if (ret) {
48 		LOG_DBG("spi_transceive FAIL %d\n", ret);
49 		return ret;
50 	}
51 
52 	memcpy(buf, (uint8_t *)&buffer[2], size);
53 
54 	return 0;
55 }
56 
bmp388_reg_write_spi(const union bmp388_bus * bus,uint8_t reg,uint8_t val)57 static int bmp388_reg_write_spi(const union bmp388_bus *bus,
58 				uint8_t reg, uint8_t val)
59 {
60 	uint8_t cmd[] = { reg & 0x7F, val };
61 	const struct spi_buf tx_buf = {
62 		.buf = cmd,
63 		.len = sizeof(cmd)
64 	};
65 	const struct spi_buf_set tx = {
66 		.buffers = &tx_buf,
67 		.count = 1
68 	};
69 	int ret;
70 
71 	ret = spi_write_dt(&bus->spi, &tx);
72 	if (ret) {
73 		LOG_DBG("spi_write FAIL %d\n", ret);
74 		return ret;
75 	}
76 	return 0;
77 }
78 
79 const struct bmp388_bus_io bmp388_bus_io_spi = {
80 	.check = bmp388_bus_check_spi,
81 	.read = bmp388_reg_read_spi,
82 	.write = bmp388_reg_write_spi,
83 };
84 #endif /* BMP3XX_USE_SPI_BUS */
85