1 /*
2 * Copyright (c) 2018, Yannis Damigos
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 <stdio.h>
11 #include <zephyr/sys/util.h>
12
read_sensor(const struct device * sensor,enum sensor_channel channel)13 static int32_t read_sensor(const struct device *sensor,
14 enum sensor_channel channel)
15 {
16 struct sensor_value val[3];
17 int32_t ret = 0;
18
19 ret = sensor_sample_fetch(sensor);
20 if (ret < 0 && ret != -EBADMSG) {
21 printf("Sensor sample update error\n");
22 goto end;
23 }
24
25 ret = sensor_channel_get(sensor, channel, val);
26 if (ret < 0) {
27 printf("Cannot read sensor channels\n");
28 goto end;
29 }
30
31 printf("( x y z ) = ( %f %f %f )\n", sensor_value_to_double(&val[0]),
32 sensor_value_to_double(&val[1]),
33 sensor_value_to_double(&val[2]));
34
35 end:
36 return ret;
37 }
38
main(void)39 int main(void)
40 {
41 const struct device *const accelerometer = DEVICE_DT_GET_ONE(st_lis2dh);
42 const struct device *const magnetometer = DEVICE_DT_GET_ONE(st_lsm303dlhc_magn);
43
44 if (!device_is_ready(accelerometer)) {
45 printf("Device %s is not ready\n", accelerometer->name);
46 return 0;
47 }
48
49 if (!device_is_ready(magnetometer)) {
50 printf("Device %s is not ready\n", magnetometer->name);
51 return 0;
52 }
53
54 while (1) {
55 printf("Magnetometer data:\n");
56 if (read_sensor(magnetometer, SENSOR_CHAN_MAGN_XYZ) < 0) {
57 printf("Failed to read magnetometer data\n");
58 }
59
60 printf("Accelerometer data:\n");
61 if (read_sensor(accelerometer, SENSOR_CHAN_ACCEL_XYZ) < 0) {
62 printf("Failed to read accelerometer data\n");
63 }
64
65 k_sleep(K_MSEC(2000));
66 }
67 return 0;
68 }
69