1 /*
2  * Copyright (c) 2023 Phytec Messtechnik GmbH
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 #include <zephyr/kernel.h>
8 #include <zephyr/sys/util_macro.h>
9 #include <zephyr/drivers/sensor.h>
10 #include <zephyr/device.h>
11 #include <zephyr/pm/device.h>
12 #include <zephyr/sys/printk.h>
13 
14 /* getting all devices from device tree with alias "prox_sensor?" */
15 #define PROX_ALIASES(i) DT_ALIAS(_CONCAT(prox_sensor, i))
16 #define PROX_DEVICES(i, _) \
17 	IF_ENABLED(DT_NODE_EXISTS(PROX_ALIASES(i)),\
18 	(DEVICE_DT_GET(PROX_ALIASES(i)),))
19 
20 /* creating a list with the first 10 devices */
21 static const struct device *prox_devices[] = {
22 	LISTIFY(10, PROX_DEVICES, ())
23 };
24 
print_prox_data(void)25 void print_prox_data(void)
26 {
27 	struct sensor_value pdata;
28 
29 	for (int i = 0; i < ARRAY_SIZE(prox_devices); i++) {
30 		const struct device *dev = prox_devices[i];
31 
32 		if (sensor_sample_fetch(dev)) {
33 			printk("Failed to fetch sample from %s\n", dev->name);
34 		}
35 
36 		sensor_channel_get(dev, SENSOR_CHAN_PROX, &pdata);
37 		printk("Proximity on %s: %d\n", dev->name, pdata.val1);
38 	}
39 }
40 
main(void)41 int main(void)
42 {
43 	printk("Proximity sensor sample application\n");
44 	printk("Found %d proximity sensor(s): ", ARRAY_SIZE(prox_devices));
45 	for (int i = 0; i < ARRAY_SIZE(prox_devices); i++) {
46 		printk("%s ", prox_devices[i]->name);
47 	}
48 	printk("\n");
49 
50 	while (true) {
51 		k_sleep(K_MSEC(2000));
52 		print_prox_data();
53 	}
54 	return 0;
55 }
56