1 /*
2 * Copyright (c) 2018 Peter Bigot Consulting, LLC
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
12 #define ALERT_HUMIDITY_LO 50
13 #define ALERT_HUMIDITY_HI 60
14
15 #ifdef CONFIG_SHT3XD_TRIGGER
16 static volatile bool alerted;
17
trigger_handler(const struct device * dev,const struct sensor_trigger * trig)18 static void trigger_handler(const struct device *dev,
19 const struct sensor_trigger *trig)
20 {
21 alerted = !alerted;
22 }
23
24 #endif
25
main(void)26 int main(void)
27 {
28 const struct device *const dev = DEVICE_DT_GET_ONE(sensirion_sht3xd);
29 int rc;
30
31 if (!device_is_ready(dev)) {
32 printf("Device %s is not ready\n", dev->name);
33 return 0;
34 }
35
36 #ifdef CONFIG_SHT3XD_TRIGGER
37 struct sensor_trigger trig = {
38 .type = SENSOR_TRIG_THRESHOLD,
39 .chan = SENSOR_CHAN_HUMIDITY,
40 };
41 struct sensor_value lo_thr = { ALERT_HUMIDITY_LO };
42 struct sensor_value hi_thr = { ALERT_HUMIDITY_HI };
43 bool last_alerted = false;
44
45 rc = sensor_attr_set(dev, SENSOR_CHAN_HUMIDITY,
46 SENSOR_ATTR_LOWER_THRESH, &lo_thr);
47 if (rc == 0) {
48 rc = sensor_attr_set(dev, SENSOR_CHAN_HUMIDITY,
49 SENSOR_ATTR_UPPER_THRESH, &hi_thr);
50 }
51 if (rc == 0) {
52 rc = sensor_trigger_set(dev, &trig, trigger_handler);
53 }
54 if (rc != 0) {
55 printf("SHT3XD: trigger config failed: %d\n", rc);
56 return 0;
57 }
58 printf("Alert outside %d..%d %%RH got %d\n", lo_thr.val1,
59 hi_thr.val1, rc);
60 #endif
61
62 while (true) {
63 struct sensor_value temp, hum;
64
65 rc = sensor_sample_fetch(dev);
66 if (rc == 0) {
67 rc = sensor_channel_get(dev, SENSOR_CHAN_AMBIENT_TEMP,
68 &temp);
69 }
70 if (rc == 0) {
71 rc = sensor_channel_get(dev, SENSOR_CHAN_HUMIDITY,
72 &hum);
73 }
74 if (rc != 0) {
75 printf("SHT3XD: failed: %d\n", rc);
76 break;
77 }
78
79 #ifdef CONFIG_SHT3XD_TRIGGER
80 if (alerted != last_alerted) {
81 if (lo_thr.val1 > hum.val1) {
82 printf("ALERT: humidity %d < %d\n",
83 hum.val1, lo_thr.val1);
84 } else if (hi_thr.val1 < hum.val1) {
85 printf("ALERT: humidity %d > %d\n",
86 hum.val1, hi_thr.val1);
87 } else {
88 printf("ALERT: humidity %d <= %d <= %d\n",
89 lo_thr.val1, hum.val1, hi_thr.val1);
90 }
91 last_alerted = alerted;
92 }
93 #endif
94
95 printf("SHT3XD: %.2f Cel ; %0.2f %%RH\n",
96 sensor_value_to_double(&temp),
97 sensor_value_to_double(&hum));
98
99 k_sleep(K_MSEC(2000));
100 }
101 return 0;
102 }
103