1 /*
2  * Copyright (c) 2023 Ian Morris
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 #include <stdio.h>
8 #include <stdlib.h>
9 
10 #include <zephyr/device.h>
11 #include <zephyr/drivers/sensor.h>
12 #include <zephyr/sys/util_macro.h>
13 #include <zephyr/kernel.h>
14 
15 #define DHT_ALIAS(i) DT_ALIAS(_CONCAT(dht, i))
16 #define DHT_DEVICE(i, _)                                                                 \
17 	IF_ENABLED(DT_NODE_EXISTS(DHT_ALIAS(i)), (DEVICE_DT_GET(DHT_ALIAS(i)),))
18 
19 /* Support up to 10 temperature/humidity sensors */
20 static const struct device *const sensors[] = {LISTIFY(10, DHT_DEVICE, ())};
21 
main(void)22 int main(void)
23 {
24 	int rc;
25 
26 	for (size_t i = 0; i < ARRAY_SIZE(sensors); i++) {
27 		if (!device_is_ready(sensors[i])) {
28 			printk("sensor: device %s not ready.\n", sensors[i]->name);
29 			return 0;
30 		}
31 	}
32 
33 	while (1) {
34 		for (size_t i = 0; i < ARRAY_SIZE(sensors); i++) {
35 			struct device *dev = (struct device *)sensors[i];
36 
37 			rc = sensor_sample_fetch(dev);
38 			if (rc < 0) {
39 				printk("%s: sensor_sample_fetch() failed: %d\n", dev->name, rc);
40 				return rc;
41 			}
42 
43 			struct sensor_value temp;
44 			struct sensor_value hum;
45 
46 			rc = sensor_channel_get(dev, SENSOR_CHAN_AMBIENT_TEMP, &temp);
47 			if (rc == 0) {
48 				rc = sensor_channel_get(dev, SENSOR_CHAN_HUMIDITY, &hum);
49 			}
50 			if (rc != 0) {
51 				printf("get failed: %d\n", rc);
52 				break;
53 			}
54 
55 			printk("%16s: temp is %d.%02d °C humidity is %d.%02d %%RH\n",
56 							dev->name, temp.val1, temp.val2 / 10000,
57 							hum.val1, hum.val2 / 10000);
58 		}
59 		k_msleep(1000);
60 	}
61 	return 0;
62 }
63