1 /*
2  * Copyright (c) 2022 Thomas Stranger
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 #ifndef ZEPHYR_DRIVERS_SENSOR_DS18B20_DS18B20_H_
8 #define ZEPHYR_DRIVERS_SENSOR_DS18B20_DS18B20_H_
9 
10 #include <zephyr/device.h>
11 #include <zephyr/devicetree.h>
12 #include <zephyr/kernel.h>
13 #include <zephyr/drivers/gpio.h>
14 #include <zephyr/drivers/w1.h>
15 #include <zephyr/sys/util_macro.h>
16 
17 #define DS18B20_CMD_CONVERT_T         0x44
18 #define DS18B20_CMD_WRITE_SCRATCHPAD  0x4E
19 #define DS18B20_CMD_READ_SCRATCHPAD   0xBE
20 #define DS18B20_CMD_COPY_SCRATCHPAD   0x48
21 #define DS18B20_CMD_RECALL_EEPROM     0xB8
22 #define DS18B20_CMD_READ_POWER_SUPPLY 0xB4
23 
24 /* resolution is set using bit 5 and 6 of configuration register
25  * macro only valid for values 9 to 12
26  */
27 #define DS18B20_RESOLUTION_POS		5
28 #define DS18B20_RESOLUTION_MASK		(BIT_MASK(2) << DS18B20_RESOLUTION_POS)
29 /* convert resolution in bits to scratchpad config format */
30 #define DS18B20_RESOLUTION(res)		((res - 9) << DS18B20_RESOLUTION_POS)
31 /* convert resolution in bits to array index (for resolution specific elements) */
32 #define DS18B20_RESOLUTION_INDEX(res)	(res - 9)
33 
34 struct ds18b20_scratchpad {
35 	int16_t temp;
36 	uint8_t alarm_temp_high;
37 	uint8_t alarm_temp_low;
38 	uint8_t config;
39 	uint8_t res[3];
40 	uint8_t crc;
41 };
42 
43 struct ds18b20_config {
44 	const struct device *bus;
45 	uint8_t family;
46 	uint8_t resolution;
47 };
48 
49 struct ds18b20_data {
50 	struct w1_slave_config config;
51 	struct ds18b20_scratchpad scratchpad;
52 	bool lazy_loaded;
53 };
54 
ds18b20_bus(const struct device * dev)55 static inline const struct device *ds18b20_bus(const struct device *dev)
56 {
57 	const struct ds18b20_config *dcp = dev->config;
58 
59 	return dcp->bus;
60 }
61 
62 #endif /* ZEPHYR_DRIVERS_SENSOR_DS18B20_DS18B20_H_ */
63