1 /*
2 * Copyright (c) 2021 Aurelien Jarno <aurelien@aurel32.net>
3 *
4 * SPDX-License-Identifier: Apache-2.0
5 */
6
7 #define DT_DRV_COMPAT meas_ms5607
8
9 #include <string.h>
10 #include <zephyr/drivers/i2c.h>
11 #include <zephyr/sys/byteorder.h>
12 #include "ms5607.h"
13
14 #define LOG_LEVEL CONFIG_SENSOR_LOG_LEVEL
15 #include <zephyr/logging/log.h>
16 LOG_MODULE_DECLARE(ms5607);
17
18 #if DT_ANY_INST_ON_BUS_STATUS_OKAY(i2c)
19
ms5607_i2c_raw_cmd(const struct ms5607_config * config,uint8_t cmd)20 static int ms5607_i2c_raw_cmd(const struct ms5607_config *config, uint8_t cmd)
21 {
22 return i2c_write_dt(&config->bus_cfg.i2c, &cmd, 1);
23 }
24
ms5607_i2c_reset(const struct ms5607_config * config)25 static int ms5607_i2c_reset(const struct ms5607_config *config)
26 {
27 int err = ms5607_i2c_raw_cmd(config, MS5607_CMD_RESET);
28
29 if (err < 0) {
30 return err;
31 }
32
33 return 0;
34 }
35
ms5607_i2c_read_prom(const struct ms5607_config * config,uint8_t cmd,uint16_t * val)36 static int ms5607_i2c_read_prom(const struct ms5607_config *config, uint8_t cmd,
37 uint16_t *val)
38 {
39 uint8_t valb[2];
40 int err;
41
42 err = i2c_burst_read_dt(&config->bus_cfg.i2c, cmd, valb, sizeof(valb));
43 if (err < 0) {
44 return err;
45 }
46
47 *val = sys_get_be16(valb);
48
49 return 0;
50 }
51
52
ms5607_i2c_start_conversion(const struct ms5607_config * config,uint8_t cmd)53 static int ms5607_i2c_start_conversion(const struct ms5607_config *config, uint8_t cmd)
54 {
55 return ms5607_i2c_raw_cmd(config, cmd);
56 }
57
ms5607_i2c_read_adc(const struct ms5607_config * config,uint32_t * val)58 static int ms5607_i2c_read_adc(const struct ms5607_config *config, uint32_t *val)
59 {
60 int err;
61 uint8_t valb[3];
62
63 err = i2c_burst_read_dt(&config->bus_cfg.i2c, MS5607_CMD_CONV_READ_ADC, valb, sizeof(valb));
64 if (err < 0) {
65 return err;
66 }
67
68 *val = (valb[0] << 16) + (valb[1] << 8) + valb[2];
69
70 return 0;
71 }
72
73
ms5607_i2c_check(const struct ms5607_config * config)74 static int ms5607_i2c_check(const struct ms5607_config *config)
75 {
76 if (!device_is_ready(config->bus_cfg.i2c.bus)) {
77 LOG_DBG("I2C bus device not ready");
78 return -ENODEV;
79 }
80
81 return 0;
82 }
83
84 const struct ms5607_transfer_function ms5607_i2c_transfer_function = {
85 .bus_check = ms5607_i2c_check,
86 .reset = ms5607_i2c_reset,
87 .read_prom = ms5607_i2c_read_prom,
88 .start_conversion = ms5607_i2c_start_conversion,
89 .read_adc = ms5607_i2c_read_adc,
90 };
91
92 #endif
93