1 /*
2 * Copyright (c) 2021 G-Technologies Sdn. Bhd.
3 *
4 * SPDX-License-Identifier: Apache-2.0
5 */
6
7 #include <zephyr/kernel.h>
8 #include <zephyr/sys/printk.h>
9 #include <zephyr/drivers/sensor.h>
10 #include <zephyr/drivers/sensor/mhz19b.h>
11
main(void)12 int main(void)
13 {
14 const struct device *dev;
15 struct sensor_value val;
16 int ret;
17
18 printk("Winsen MH-Z19B CO2 sensor application\n");
19
20 dev = DEVICE_DT_GET_ONE(winsen_mhz19b);
21 if (!device_is_ready(dev)) {
22 printk("sensor: device not found.\n");
23 return 0;
24 }
25
26 printk("Configuring sensor - ");
27
28 val.val1 = 5000;
29 ret = sensor_attr_set(dev, SENSOR_CHAN_CO2, SENSOR_ATTR_FULL_SCALE, &val);
30 if (ret != 0) {
31 printk("failed to set range to %d\n", val.val1);
32 return 0;
33 }
34
35 val.val1 = 1;
36 ret = sensor_attr_set(dev, SENSOR_CHAN_CO2, SENSOR_ATTR_MHZ19B_ABC, &val);
37 if (ret != 0) {
38 printk("failed to set ABC to %d\n", val.val1);
39 return 0;
40 }
41
42 printk("OK\n");
43
44 printk("Reading configurations from sensor:\n");
45
46 ret = sensor_attr_get(dev, SENSOR_CHAN_CO2, SENSOR_ATTR_FULL_SCALE, &val);
47 if (ret != 0) {
48 printk("failed to get range\n");
49 return 0;
50 }
51
52 printk("Sensor range is set to %dppm\n", val.val1);
53
54 ret = sensor_attr_get(dev, SENSOR_CHAN_CO2, SENSOR_ATTR_MHZ19B_ABC, &val);
55 if (ret != 0) {
56 printk("failed to get ABC\n");
57 return 0;
58 }
59
60 printk("Sensor ABC is %s\n", val.val1 == 1 ? "enabled" : "disabled");
61
62 while (1) {
63 if (sensor_sample_fetch(dev) != 0) {
64 printk("sensor: sample fetch fail.\n");
65 return 0;
66 }
67
68 if (sensor_channel_get(dev, SENSOR_CHAN_CO2, &val) != 0) {
69 printk("sensor: channel get fail.\n");
70 return 0;
71 }
72
73 printk("sensor: co2 reading: %d\n", val.val1);
74
75 k_msleep(2000);
76 }
77 return 0;
78 }
79