1 /*
2  * Copyright (c) 2022 Thomas Stranger
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 #include <zephyr/kernel.h>
8 #include <zephyr/device.h>
9 #include <zephyr/devicetree.h>
10 #include <zephyr/drivers/sensor.h>
11 
12 /*
13  * Get a device structure from a devicetree node with compatible
14  * "maxim,ds18b20". (If there are multiple, just pick one.)
15  */
get_ds18b20_device(void)16 static const struct device *get_ds18b20_device(void)
17 {
18 	const struct device *const dev = DEVICE_DT_GET_ANY(maxim_ds18b20);
19 
20 	if (dev == NULL) {
21 		/* No such node, or the node does not have status "okay". */
22 		printk("\nError: no device found.\n");
23 		return NULL;
24 	}
25 
26 	if (!device_is_ready(dev)) {
27 		printk("\nError: Device \"%s\" is not ready; "
28 		       "check the driver initialization logs for errors.\n",
29 		       dev->name);
30 		return NULL;
31 	}
32 
33 	printk("Found device \"%s\", getting sensor data\n", dev->name);
34 	return dev;
35 }
36 
main(void)37 int main(void)
38 {
39 	const struct device *dev = get_ds18b20_device();
40 	int res;
41 
42 	if (dev == NULL) {
43 		return 0;
44 	}
45 
46 	while (true) {
47 		struct sensor_value temp;
48 
49 		res = sensor_sample_fetch(dev);
50 		if (res != 0) {
51 			printk("sample_fetch() failed: %d\n", res);
52 			return res;
53 		}
54 
55 		res = sensor_channel_get(dev, SENSOR_CHAN_AMBIENT_TEMP, &temp);
56 		if (res != 0) {
57 			printk("channel_get() failed: %d\n", res);
58 			return res;
59 		}
60 
61 		printk("Temp: %d.%06d\n", temp.val1, temp.val2);
62 		k_sleep(K_MSEC(2000));
63 	}
64 
65 	return 0;
66 }
67