Alien Queen
Alien Queen
How Can I Consistently Handle Sensor Data Read Failures on AVR32UC with Zephyr OS?
something like this
#include <zephyr.h>
#include <device.h>
#include <drivers/sensor.h>
#include <sys/printk.h>

const struct device *sensor_dev;

#define RETRY_COUNT 3
#define RETRY_DELAY K_SECONDS(2)
#define FETCH_INTERVAL K_SECONDS(10)

void main(void)
{
struct sensor_value temp, humidity;
int ret, retry;

sensor_dev = device_get_binding(DT_LABEL(DT_INST(0, ams_dht22)));
if (!sensor_dev) {
printk("Failed to bind DHT22 sensor\n");
return;
}

while (1) {
retry = 0;
while (retry < RETRY_COUNT) {
ret = sensor_sample_fetch(sensor_dev);
if (ret == 0) {
break;
}
printk("Failed to fetch data, attempt %d/%d\n", retry + 1, RETRY_COUNT);
retry++;
k_sleep(RETRY_DELAY);
}

if (retry == RETRY_COUNT) {
printk("Failed to fetch data after %d attempts\n", RETRY_COUNT);
k_sleep(FETCH_INTERVAL);
continue;
}

ret = sensor_channel_get(sensor_dev, SENSOR_CHAN_AMBIENT_TEMP, &temp);
if (ret < 0) {
printk("Failed to get temperature data\n");
continue;
}

ret = sensor_channel_get(sensor_dev, SENSOR_CHAN_HUMIDITY, &humidity);
if (ret < 0) {
printk("Failed to get humidity data\n");
continue;
}

printk("Temperature: %d.%d C\n", temp.val1, temp.val2);
printk("Humidity: %d.%d %%\n", humidity.val1, humidity.val2);

k_sleep(FETCH_INTERVAL);
}
}
#include <zephyr.h>
#include <device.h>
#include <drivers/sensor.h>
#include <sys/printk.h>

const struct device *sensor_dev;

#define RETRY_COUNT 3
#define RETRY_DELAY K_SECONDS(2)
#define FETCH_INTERVAL K_SECONDS(10)

void main(void)
{
struct sensor_value temp, humidity;
int ret, retry;

sensor_dev = device_get_binding(DT_LABEL(DT_INST(0, ams_dht22)));
if (!sensor_dev) {
printk("Failed to bind DHT22 sensor\n");
return;
}

while (1) {
retry = 0;
while (retry < RETRY_COUNT) {
ret = sensor_sample_fetch(sensor_dev);
if (ret == 0) {
break;
}
printk("Failed to fetch data, attempt %d/%d\n", retry + 1, RETRY_COUNT);
retry++;
k_sleep(RETRY_DELAY);
}

if (retry == RETRY_COUNT) {
printk("Failed to fetch data after %d attempts\n", RETRY_COUNT);
k_sleep(FETCH_INTERVAL);
continue;
}

ret = sensor_channel_get(sensor_dev, SENSOR_CHAN_AMBIENT_TEMP, &temp);
if (ret < 0) {
printk("Failed to get temperature data\n");
continue;
}

ret = sensor_channel_get(sensor_dev, SENSOR_CHAN_HUMIDITY, &humidity);
if (ret < 0) {
printk("Failed to get humidity data\n");
continue;
}

printk("Temperature: %d.%d C\n", temp.val1, temp.val2);
printk("Humidity: %d.%d %%\n", humidity.val1, humidity.val2);

k_sleep(FETCH_INTERVAL);
}
}
8 replies