1 /*
2  * Copyright (c) 2021 Jonathan Hahn
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 #include <stdio.h>
8 #include <zephyr/kernel.h>
9 #include <zephyr/device.h>
10 #include <zephyr/drivers/sensor.h>
11 
12 #define SAMPLING_INTERVAL_MS 10
13 #define DISPLAY_INTERVAL_MS 50
14 
set_sampling_frequency(const struct device * sensor,double sampling_frequency)15 static int set_sampling_frequency(const struct device *sensor, double sampling_frequency)
16 {
17 	struct sensor_value setting;
18 
19 	(void)sensor_value_from_double(&setting, sampling_frequency);
20 
21 	return sensor_attr_set(sensor,
22 			       SENSOR_CHAN_GYRO_XYZ, SENSOR_ATTR_SAMPLING_FREQUENCY, &setting);
23 }
24 
fetch_and_display(const struct device * sensor)25 static void fetch_and_display(const struct device *sensor)
26 {
27 	struct sensor_value gyro[3];
28 
29 	int rc = sensor_sample_fetch(sensor);
30 
31 	if (rc != 0) {
32 		printf("ERROR: Failed fetching gyro values: %d.\n", rc);
33 		return;
34 	}
35 
36 	rc = sensor_channel_get(sensor,
37 				SENSOR_CHAN_GYRO_XYZ,
38 				gyro);
39 
40 	if (rc != 0) {
41 		printf("ERROR: Failed getting gyro values: %d\n", rc);
42 		return;
43 	}
44 
45 	printf("%u ms: x %f , y %f , z %f\n",
46 	       k_uptime_get_32(),
47 	       sensor_value_to_double(&gyro[0]),
48 	       sensor_value_to_double(&gyro[1]),
49 	       sensor_value_to_double(&gyro[2]));
50 }
51 
main(void)52 int main(void)
53 {
54 	const double sampling_frequency = 1000.0 / SAMPLING_INTERVAL_MS;
55 	const struct device *const sensor = DEVICE_DT_GET_ONE(st_i3g4250d);
56 
57 	if (!device_is_ready(sensor)) {
58 		printf("Sensor %s is not ready\n", sensor->name);
59 		return 0;
60 	}
61 
62 	printf("Set sensor sampling frequency to %f Hz.\n", sampling_frequency);
63 	set_sampling_frequency(sensor, sampling_frequency);
64 
65 	printf("Start polling with an interval of %d ms\n", DISPLAY_INTERVAL_MS);
66 	while (true) {
67 		fetch_and_display(sensor);
68 
69 		/* Wait some time before printing the next value */
70 		k_sleep(K_MSEC(DISPLAY_INTERVAL_MS));
71 	}
72 	return 0;
73 }
74