1 /*
2  * Copyright (c) 2017 Linaro Limited
3  * Copyright (c) 2019 Nordic Semiconductor ASA
4  *
5  * SPDX-License-Identifier: Apache-2.0
6  */
7 
8 #include <zephyr/kernel.h>
9 #include <zephyr/device.h>
10 #include <zephyr/drivers/sensor.h>
11 #include <stdio.h>
12 #include <zephyr/sys/util.h>
13 
process_sample(const struct device * dev)14 static void process_sample(const struct device *dev)
15 {
16 	static unsigned int obs;
17 	struct sensor_value pressure, temp;
18 
19 	if (sensor_sample_fetch(dev) < 0) {
20 		printf("Sensor sample update error\n");
21 		return;
22 	}
23 
24 	if (sensor_channel_get(dev, SENSOR_CHAN_PRESS, &pressure) < 0) {
25 		printf("Cannot read LPS22HH pressure channel\n");
26 		return;
27 	}
28 
29 	if (sensor_channel_get(dev, SENSOR_CHAN_AMBIENT_TEMP, &temp) < 0) {
30 		printf("Cannot read LPS22HH temperature channel\n");
31 		return;
32 	}
33 
34 	++obs;
35 	printf("Observation: %u\n", obs);
36 
37 	/* display pressure */
38 	printf("Pressure: %.3f kPa\n", sensor_value_to_double(&pressure));
39 
40 	/* display temperature */
41 	printf("Temperature: %.2f C\n", sensor_value_to_double(&temp));
42 
43 }
44 
lps22hh_handler(const struct device * dev,const struct sensor_trigger * trig)45 static void lps22hh_handler(const struct device *dev,
46 			    const struct sensor_trigger *trig)
47 {
48 	process_sample(dev);
49 }
50 
main(void)51 int main(void)
52 {
53 	const struct device *const dev = DEVICE_DT_GET_ONE(st_lps22hh);
54 
55 	if (!device_is_ready(dev)) {
56 		printk("sensor: device not ready.\n");
57 		return 0;
58 	}
59 
60 	if (IS_ENABLED(CONFIG_LPS22HH_TRIGGER)) {
61 		struct sensor_value attr = {
62 			.val1 = 1,
63 		};
64 		struct sensor_trigger trig = {
65 			.type = SENSOR_TRIG_DATA_READY,
66 			.chan = SENSOR_CHAN_ALL,
67 		};
68 
69 		if (sensor_attr_set(dev, SENSOR_CHAN_ALL,
70 				    SENSOR_ATTR_SAMPLING_FREQUENCY, &attr) < 0) {
71 			printf("Cannot configure sampling rate\n");
72 			return 0;
73 		}
74 		if (sensor_trigger_set(dev, &trig, lps22hh_handler) < 0) {
75 			printf("Cannot configure trigger\n");
76 			return 0;
77 		}
78 		printk("Configured for triggered collection at %u Hz\n",
79 		       attr.val1);
80 	}
81 
82 	while (!IS_ENABLED(CONFIG_LPS22HH_TRIGGER)) {
83 		process_sample(dev);
84 		k_sleep(K_MSEC(2000));
85 	}
86 	k_sleep(K_FOREVER);
87 	return 0;
88 }
89