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 #if BMP388_BUS_SPI
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 start,uint8_t * buf,int size)25 static int bmp388_reg_read_spi(const union bmp388_bus *bus,
26 uint8_t start, uint8_t *buf, int size)
27 {
28 uint8_t addr;
29 const struct spi_buf tx_buf = {
30 .buf = &addr,
31 .len = 1
32 };
33 const struct spi_buf_set tx = {
34 .buffers = &tx_buf,
35 .count = 1
36 };
37 struct spi_buf rx_buf[2];
38 const struct spi_buf_set rx = {
39 .buffers = rx_buf,
40 .count = ARRAY_SIZE(rx_buf)
41 };
42 int i;
43
44 rx_buf[0].buf = NULL;
45 rx_buf[0].len = 1;
46
47 rx_buf[1].len = 1;
48
49 for (i = 0; i < size; i++) {
50 int ret;
51
52 addr = (start + i) | 0x80;
53 rx_buf[1].buf = &buf[i];
54
55 ret = spi_transceive_dt(&bus->spi, &tx, &rx);
56 if (ret) {
57 LOG_DBG("spi_transceive FAIL %d\n", ret);
58 return ret;
59 }
60 }
61
62 return 0;
63 }
64
bmp388_reg_write_spi(const union bmp388_bus * bus,uint8_t reg,uint8_t val)65 static int bmp388_reg_write_spi(const union bmp388_bus *bus,
66 uint8_t reg, uint8_t val)
67 {
68 uint8_t cmd[] = { reg & 0x7F, val };
69 const struct spi_buf tx_buf = {
70 .buf = cmd,
71 .len = sizeof(cmd)
72 };
73 const struct spi_buf_set tx = {
74 .buffers = &tx_buf,
75 .count = 1
76 };
77 int ret;
78
79 ret = spi_write_dt(&bus->spi, &tx);
80 if (ret) {
81 LOG_DBG("spi_write FAIL %d\n", ret);
82 return ret;
83 }
84 return 0;
85 }
86
87 const struct bmp388_bus_io bmp388_bus_io_spi = {
88 .check = bmp388_bus_check_spi,
89 .read = bmp388_reg_read_spi,
90 .write = bmp388_reg_write_spi,
91 };
92 #endif /* BMP388_BUS_SPI */
93