1 /*
2 * Copyright (c) 2019 Nordic Semiconductor ASA
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
fetch_and_display(const struct device * sensor)12 static void fetch_and_display(const struct device *sensor)
13 {
14 static unsigned int count;
15 struct sensor_value accel[3];
16 struct sensor_value temperature;
17 const char *overrun = "";
18 int rc = sensor_sample_fetch(sensor);
19
20 ++count;
21 if (rc == -EBADMSG) {
22 /* Sample overrun. Ignore in polled mode. */
23 if (IS_ENABLED(CONFIG_LIS2DH_TRIGGER)) {
24 overrun = "[OVERRUN] ";
25 }
26 rc = 0;
27 }
28 if (rc == 0) {
29 rc = sensor_channel_get(sensor,
30 SENSOR_CHAN_ACCEL_XYZ,
31 accel);
32 }
33 if (rc < 0) {
34 printf("ERROR: Update failed: %d\n", rc);
35 } else {
36 printf("#%u @ %u ms: %sx %f , y %f , z %f",
37 count, k_uptime_get_32(), overrun,
38 sensor_value_to_double(&accel[0]),
39 sensor_value_to_double(&accel[1]),
40 sensor_value_to_double(&accel[2]));
41 }
42
43 if (IS_ENABLED(CONFIG_LIS2DH_MEASURE_TEMPERATURE)) {
44 if (rc == 0) {
45 rc = sensor_channel_get(sensor, SENSOR_CHAN_DIE_TEMP, &temperature);
46 if (rc < 0) {
47 printf("\nERROR: Unable to read temperature:%d\n", rc);
48 } else {
49 printf(", t %f\n", sensor_value_to_double(&temperature));
50 }
51 }
52
53 } else {
54 printf("\n");
55 }
56 }
57
58 #ifdef CONFIG_LIS2DH_TRIGGER
trigger_handler(const struct device * dev,const struct sensor_trigger * trig)59 static void trigger_handler(const struct device *dev,
60 const struct sensor_trigger *trig)
61 {
62 fetch_and_display(dev);
63 }
64 #endif
65
main(void)66 int main(void)
67 {
68 const struct device *const sensor = DEVICE_DT_GET_ANY(st_lis2dh);
69
70 if (sensor == NULL) {
71 printf("No device found\n");
72 return 0;
73 }
74 if (!device_is_ready(sensor)) {
75 printf("Device %s is not ready\n", sensor->name);
76 return 0;
77 }
78
79 #if CONFIG_LIS2DH_TRIGGER
80 {
81 struct sensor_trigger trig;
82 int rc;
83
84 trig.type = SENSOR_TRIG_DATA_READY;
85 trig.chan = SENSOR_CHAN_ACCEL_XYZ;
86
87 if (IS_ENABLED(CONFIG_LIS2DH_ODR_RUNTIME)) {
88 struct sensor_value odr = {
89 .val1 = 1,
90 };
91
92 rc = sensor_attr_set(sensor, trig.chan,
93 SENSOR_ATTR_SAMPLING_FREQUENCY,
94 &odr);
95 if (rc != 0) {
96 printf("Failed to set odr: %d\n", rc);
97 return 0;
98 }
99 printf("Sampling at %u Hz\n", odr.val1);
100 }
101
102 rc = sensor_trigger_set(sensor, &trig, trigger_handler);
103 if (rc != 0) {
104 printf("Failed to set trigger: %d\n", rc);
105 return 0;
106 }
107
108 printf("Waiting for triggers\n");
109 while (true) {
110 k_sleep(K_MSEC(2000));
111 }
112 }
113 #else /* CONFIG_LIS2DH_TRIGGER */
114 printf("Polling at 0.5 Hz\n");
115 while (true) {
116 fetch_and_display(sensor);
117 k_sleep(K_MSEC(2000));
118 }
119 #endif /* CONFIG_LIS2DH_TRIGGER */
120 }
121