1 /*
2  * Copyright (c) 2023 TOKITA Hiroshi
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 #include <zephyr/kernel.h>
8 #include <zephyr/device.h>
9 #include <zephyr/drivers/sensor.h>
10 #include <zephyr/sys/printk.h>
11 
12 #define DIE_TEMP_ALIAS(i) DT_ALIAS(_CONCAT(die_temp, i))
13 #define DIE_TEMPERATURE_SENSOR(i, _)                                                               \
14 	IF_ENABLED(DT_NODE_EXISTS(DIE_TEMP_ALIAS(i)), (DEVICE_DT_GET(DIE_TEMP_ALIAS(i)),))
15 
16 /* support up to 16 cpu die temperature sensors */
17 static const struct device *const sensors[] = {LISTIFY(16, DIE_TEMPERATURE_SENSOR, ())};
18 
print_die_temperature(const struct device * dev)19 static int print_die_temperature(const struct device *dev)
20 {
21 	struct sensor_value val;
22 	int rc;
23 
24 	/* fetch sensor samples */
25 	rc = sensor_sample_fetch(dev);
26 	if (rc) {
27 		printk("Failed to fetch sample (%d)\n", rc);
28 		return rc;
29 	}
30 
31 	rc = sensor_channel_get(dev, SENSOR_CHAN_DIE_TEMP, &val);
32 	if (rc) {
33 		printk("Failed to get data (%d)\n", rc);
34 		return rc;
35 	}
36 
37 	printk("CPU Die temperature[%s]: %.1f °C\n", dev->name, sensor_value_to_double(&val));
38 	return 0;
39 }
40 
main(void)41 int main(void)
42 {
43 	int rc;
44 
45 	for (size_t i = 0; i < ARRAY_SIZE(sensors); i++) {
46 		if (!device_is_ready(sensors[i])) {
47 			printk("sensor: device %s not ready.\n", sensors[i]->name);
48 			return 0;
49 		}
50 	}
51 
52 	while (1) {
53 		for (size_t i = 0; i < ARRAY_SIZE(sensors); i++) {
54 			rc = print_die_temperature(sensors[i]);
55 			if (rc < 0) {
56 				return 0;
57 			}
58 		}
59 		k_msleep(300);
60 	}
61 	return 0;
62 }
63