1 /*
2  * Copyright (c) 2022 TOKITA Hiroshi <tokita.hiroshi@fujitsu.com
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 ACCEL_ALIAS(i) DT_ALIAS(_CONCAT(accel, i))
16 #define ACCELEROMETER_DEVICE(i, _)                                                                 \
17 	IF_ENABLED(DT_NODE_EXISTS(ACCEL_ALIAS(i)), (DEVICE_DT_GET(ACCEL_ALIAS(i)),))
18 
19 /* support up to 10 accelerometer sensors */
20 static const struct device *const sensors[] = {LISTIFY(10, ACCELEROMETER_DEVICE, ())};
21 
22 static const enum sensor_channel channels[] = {
23 	SENSOR_CHAN_ACCEL_X,
24 	SENSOR_CHAN_ACCEL_Y,
25 	SENSOR_CHAN_ACCEL_Z,
26 };
27 
print_accels(const struct device * dev)28 static int print_accels(const struct device *dev)
29 {
30 	int ret;
31 	struct sensor_value accel[3];
32 
33 	ret = sensor_sample_fetch(dev);
34 	if (ret < 0) {
35 		printk("%s: sensor_sample_fetch() failed: %d\n", dev->name, ret);
36 		return ret;
37 	}
38 
39 	for (size_t i = 0; i < ARRAY_SIZE(channels); i++) {
40 		ret = sensor_channel_get(dev, channels[i], &accel[i]);
41 		if (ret < 0) {
42 			printk("%s: sensor_channel_get(%c) failed: %d\n", dev->name, 'X' + i, ret);
43 			return ret;
44 		}
45 	}
46 
47 	printk("%16s [m/s^2]:    (%12.6f, %12.6f, %12.6f)\n", dev->name,
48 	       sensor_value_to_double(&accel[0]), sensor_value_to_double(&accel[1]),
49 	       sensor_value_to_double(&accel[2]));
50 
51 	return 0;
52 }
53 
set_sampling_freq(const struct device * dev)54 static int set_sampling_freq(const struct device *dev)
55 {
56 	int ret;
57 	struct sensor_value odr;
58 
59 	ret = sensor_attr_get(dev, SENSOR_CHAN_ACCEL_XYZ, SENSOR_ATTR_SAMPLING_FREQUENCY, &odr);
60 
61 	/* If we don't get a frequency > 0, we set one */
62 	if (ret != 0 || (odr.val1 == 0 && odr.val2 == 0)) {
63 		odr.val1 = 100;
64 		odr.val2 = 0;
65 
66 		ret = sensor_attr_set(dev, SENSOR_CHAN_ACCEL_XYZ, SENSOR_ATTR_SAMPLING_FREQUENCY,
67 				      &odr);
68 
69 		if (ret != 0) {
70 			printk("%s : failed to set sampling frequency\n", dev->name);
71 		}
72 	}
73 
74 	return 0;
75 }
76 
main(void)77 int main(void)
78 {
79 	int ret;
80 
81 	for (size_t i = 0; i < ARRAY_SIZE(sensors); i++) {
82 		if (!device_is_ready(sensors[i])) {
83 			printk("sensor: device %s not ready.\n", sensors[i]->name);
84 			return 0;
85 		}
86 		set_sampling_freq(sensors[i]);
87 	}
88 
89 #ifndef CONFIG_COVERAGE
90 	while (1) {
91 #else
92 	for (int i = 0; i < 5; i++) {
93 #endif
94 		for (size_t i = 0; i < ARRAY_SIZE(sensors); i++) {
95 			ret = print_accels(sensors[i]);
96 			if (ret < 0) {
97 				return 0;
98 			}
99 		}
100 		k_msleep(1000);
101 	}
102 	return 0;
103 }
104