1 /*
2 * Copyright 2024 NXP
3 * Copyright (c) 2018 Phytec Messtechnik GmbH
4 *
5 * SPDX-License-Identifier: Apache-2.0
6 */
7
8 #include <zephyr/kernel.h>
9 #include <zephyr/drivers/sensor.h>
10 #include <stdio.h>
11
12 K_SEM_DEFINE(sem, 0, 1); /* starts off "not available" */
13
trigger_handler(const struct device * dev,const struct sensor_trigger * trigger)14 static void trigger_handler(const struct device *dev, const struct sensor_trigger *trigger)
15 {
16 ARG_UNUSED(trigger);
17
18 /* Always fetch the sample to clear the data ready interrupt in the
19 * sensor.
20 */
21 if (sensor_sample_fetch(dev)) {
22 printf("sensor_sample_fetch failed\n");
23 return;
24 }
25
26 k_sem_give(&sem);
27 }
28
main(void)29 int main(void)
30 {
31 struct sensor_value data[3];
32 const struct device *const dev = DEVICE_DT_GET(DT_ALIAS(accel0));
33
34 struct sensor_trigger trig = {
35 .type = SENSOR_TRIG_DATA_READY,
36 .chan = SENSOR_CHAN_ACCEL_XYZ,
37 };
38
39 if (!device_is_ready(dev)) {
40 printf("Device %s is not ready\n", dev->name);
41 return 0;
42 }
43
44 if (sensor_trigger_set(dev, &trig, trigger_handler)) {
45 printf("Could not set trigger\n");
46 return 0;
47 }
48
49 while (1) {
50 k_sem_take(&sem, K_FOREVER);
51 sensor_channel_get(dev, SENSOR_CHAN_ACCEL_XYZ, data);
52
53 /* Print accel x,y,z data */
54 printf("%16s [m/s^2]: (%12.6f, %12.6f, %12.6f)\n", dev->name,
55 sensor_value_to_double(&data[0]), sensor_value_to_double(&data[1]),
56 sensor_value_to_double(&data[2]));
57 }
58 }
59