1 /*
2  * Copyright (c) 2017 Linaro Limited
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 
process_sample(const struct device * dev)13 static void process_sample(const struct device *dev)
14 {
15 	static unsigned int obs;
16 	struct sensor_value temp, hum;
17 	if (sensor_sample_fetch(dev) < 0) {
18 		printf("Sensor sample update error\n");
19 		return;
20 	}
21 
22 	if (sensor_channel_get(dev, SENSOR_CHAN_AMBIENT_TEMP, &temp) < 0) {
23 		printf("Cannot read HTS221 temperature channel\n");
24 		return;
25 	}
26 
27 	if (sensor_channel_get(dev, SENSOR_CHAN_HUMIDITY, &hum) < 0) {
28 		printf("Cannot read HTS221 humidity channel\n");
29 		return;
30 	}
31 
32 	++obs;
33 	printf("Observation:%u\n", obs);
34 
35 	/* display temperature */
36 	printf("Temperature:%.1f C\n", sensor_value_to_double(&temp));
37 
38 	/* display humidity */
39 	printf("Relative Humidity:%.1f%%\n",
40 	       sensor_value_to_double(&hum));
41 }
42 
hts221_handler(const struct device * dev,const struct sensor_trigger * trig)43 static void hts221_handler(const struct device *dev,
44 			   const struct sensor_trigger *trig)
45 {
46 	process_sample(dev);
47 }
48 
main(void)49 int main(void)
50 {
51 	const struct device *const dev = DEVICE_DT_GET_ONE(st_hts221);
52 
53 	if (!device_is_ready(dev)) {
54 		printk("sensor: device not ready.\n");
55 		return 0;
56 	}
57 
58 	if (IS_ENABLED(CONFIG_HTS221_TRIGGER)) {
59 		struct sensor_trigger trig = {
60 			.type = SENSOR_TRIG_DATA_READY,
61 			.chan = SENSOR_CHAN_ALL,
62 		};
63 		if (sensor_trigger_set(dev, &trig, hts221_handler) < 0) {
64 			printf("Cannot configure trigger\n");
65 			return 0;
66 		}
67 	}
68 
69 	while (!IS_ENABLED(CONFIG_HTS221_TRIGGER)) {
70 		process_sample(dev);
71 		k_sleep(K_MSEC(2000));
72 	}
73 	k_sleep(K_FOREVER);
74 	return 0;
75 }
76