1 /*
2  * Copyright (c) 2012-2014 Wind River Systems, Inc.
3  * Copyright (c) 2021 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/devicetree.h>
11 #include <zephyr/drivers/sensor.h>
12 #include <zephyr/drivers/sensor_data_types.h>
13 #include <zephyr/rtio/rtio.h>
14 #include <zephyr/dsp/print_format.h>
15 
16 /*
17  * Get a device structure from a devicetree node with compatible
18  * "bosch,bme280". (If there are multiple, just pick one.)
19  */
20 const struct device *const dev = DEVICE_DT_GET_ANY(bosch_bme280);
21 
22 SENSOR_DT_READ_IODEV(iodev, DT_COMPAT_GET_ANY_STATUS_OKAY(bosch_bme280),
23 		{SENSOR_CHAN_AMBIENT_TEMP, 0},
24 		{SENSOR_CHAN_HUMIDITY, 0},
25 		{SENSOR_CHAN_PRESS, 0});
26 
27 RTIO_DEFINE(ctx, 1, 1);
28 
check_bme280_device(void)29 static const struct device *check_bme280_device(void)
30 {
31 	if (dev == NULL) {
32 		/* No such node, or the node does not have status "okay". */
33 		printk("\nError: no device found.\n");
34 		return NULL;
35 	}
36 
37 	if (!device_is_ready(dev)) {
38 		printk("\nError: Device \"%s\" is not ready; "
39 		       "check the driver initialization logs for errors.\n",
40 		       dev->name);
41 		return NULL;
42 	}
43 
44 	printk("Found device \"%s\", getting sensor data\n", dev->name);
45 	return dev;
46 }
47 
main(void)48 int main(void)
49 {
50 	const struct device *dev = check_bme280_device();
51 
52 	if (dev == NULL) {
53 		return 0;
54 	}
55 
56 	while (1) {
57 		uint8_t buf[128];
58 
59 		int rc = sensor_read(&iodev, &ctx, buf, 128);
60 
61 		if (rc != 0) {
62 			printk("%s: sensor_read() failed: %d\n", dev->name, rc);
63 			return rc;
64 		}
65 
66 		const struct sensor_decoder_api *decoder;
67 
68 		rc = sensor_get_decoder(dev, &decoder);
69 
70 		if (rc != 0) {
71 			printk("%s: sensor_get_decode() failed: %d\n", dev->name, rc);
72 			return rc;
73 		}
74 
75 		uint32_t temp_fit = 0;
76 		struct sensor_q31_data temp_data = {0};
77 
78 		decoder->decode(buf,
79 			(struct sensor_chan_spec) {SENSOR_CHAN_AMBIENT_TEMP, 0},
80 			&temp_fit, 1, &temp_data);
81 
82 		uint32_t press_fit = 0;
83 		struct sensor_q31_data press_data = {0};
84 
85 		decoder->decode(buf,
86 				(struct sensor_chan_spec) {SENSOR_CHAN_PRESS, 0},
87 				&press_fit, 1, &press_data);
88 
89 		uint32_t hum_fit = 0;
90 		struct sensor_q31_data hum_data = {0};
91 
92 		decoder->decode(buf,
93 				(struct sensor_chan_spec) {SENSOR_CHAN_HUMIDITY, 0},
94 				&hum_fit, 1, &hum_data);
95 
96 		printk("temp: %s%d.%d; press: %s%d.%d; humidity: %s%d.%d\n",
97 			PRIq_arg(temp_data.readings[0].temperature, 6, temp_data.shift),
98 			PRIq_arg(press_data.readings[0].pressure, 6, press_data.shift),
99 			PRIq_arg(hum_data.readings[0].humidity, 6, hum_data.shift));
100 
101 		k_sleep(K_MSEC(1000));
102 	}
103 	return 0;
104 }
105