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 BMM150s accessed via SPI.
11 */
12
13 #include <zephyr/logging/log.h>
14 #include "bmm150.h"
15
16 #if BMM150_BUS_SPI
17
18 LOG_MODULE_DECLARE(BMM150, CONFIG_SENSOR_LOG_LEVEL);
19
bmm150_bus_check_spi(const union bmm150_bus * bus)20 static int bmm150_bus_check_spi(const union bmm150_bus *bus)
21 {
22 return spi_is_ready_dt(&bus->spi) ? 0 : -ENODEV;
23 }
24
bmm150_reg_read_spi(const union bmm150_bus * bus,uint8_t start,uint8_t * buf,int size)25 static int bmm150_reg_read_spi(const union bmm150_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
bmm150_reg_write_spi(const union bmm150_bus * bus,uint8_t reg,uint8_t val)65 static int bmm150_reg_write_spi(const union bmm150_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 bmm150_bus_io bmm150_bus_io_spi = {
88 .check = bmm150_bus_check_spi,
89 .read = bmm150_reg_read_spi,
90 .write = bmm150_reg_write_spi,
91 };
92
93 #endif /* BMM150_BUS_SPI */
94