|
| 1 | +/* |
| 2 | + * Copyright (c) 2019 Nordic Semiconductor ASA |
| 3 | + * |
| 4 | + * SPDX-License-Identifier: Apache-2.0 |
| 5 | + */ |
| 6 | + |
| 7 | +#include <zephyr.h> |
| 8 | +#include <device.h> |
| 9 | +#include <drivers/sensor.h> |
| 10 | +#include <stdio.h> |
| 11 | + |
| 12 | +static const char *now_str(void) |
| 13 | +{ |
| 14 | + static char buf[16]; /* ...HH:MM:SS.MMM */ |
| 15 | + u32_t now = k_uptime_get_32(); |
| 16 | + unsigned int ms = now % MSEC_PER_SEC; |
| 17 | + unsigned int s; |
| 18 | + unsigned int min; |
| 19 | + unsigned int h; |
| 20 | + |
| 21 | + now /= MSEC_PER_SEC; |
| 22 | + s = now % 60U; |
| 23 | + now /= 60U; |
| 24 | + min = now % 60U; |
| 25 | + now /= 60U; |
| 26 | + h = now; |
| 27 | + |
| 28 | + snprintf(buf, sizeof(buf), "%u:%02u:%02u.%03u", |
| 29 | + h, min, s, ms); |
| 30 | + return buf; |
| 31 | +} |
| 32 | + |
| 33 | +void main(void) |
| 34 | +{ |
| 35 | + const char *const label = DT_INST_0_AOSONG_DHT_LABEL; |
| 36 | + struct device *dht22 = device_get_binding(label); |
| 37 | + |
| 38 | + if (!dht22) { |
| 39 | + printf("Failed to find sensor %s\n", label); |
| 40 | + return; |
| 41 | + } |
| 42 | + |
| 43 | + while (true) { |
| 44 | + int rc = sensor_sample_fetch(dht22); |
| 45 | + |
| 46 | + if (rc != 0) { |
| 47 | + printf("Sensor fetch failed: %d\n", rc); |
| 48 | + break; |
| 49 | + } |
| 50 | + |
| 51 | + struct sensor_value temperature; |
| 52 | + struct sensor_value humidity; |
| 53 | + |
| 54 | + rc = sensor_channel_get(dht22, SENSOR_CHAN_AMBIENT_TEMP, |
| 55 | + &temperature); |
| 56 | + if (rc == 0) { |
| 57 | + rc = sensor_channel_get(dht22, SENSOR_CHAN_HUMIDITY, |
| 58 | + &humidity); |
| 59 | + } |
| 60 | + if (rc != 0) { |
| 61 | + printf("get failed: %d\n", rc); |
| 62 | + break; |
| 63 | + } |
| 64 | + |
| 65 | + printf("[%s]: %.1f Cel ; %.1f %%RH\n", |
| 66 | + now_str(), |
| 67 | + sensor_value_to_double(&temperature), |
| 68 | + sensor_value_to_double(&humidity)); |
| 69 | + k_sleep(K_SECONDS(2)); |
| 70 | + } |
| 71 | +} |
0 commit comments