Edit online

Demo

4 Dec 2024
Read time: 1 minute(s)

Demo

以下代码片段展示了一个用于传感器轮询的函数 sensor_polling,可以作为 TSensor 设备的使用参考。sensor_polling 从命令行参数中获取设备名称和读取次数,并读取传感器数据并显示。关于 sensor_polling 命令的代码,详见 kernel/rt-thread/components/drivers/sensors/sensor_cmd.c
static void sensor_polling(int argc, char **argv)
{
    rt_uint16_t num = 10;
    rt_device_t dev = RT_NULL;
    rt_sensor_t sensor;
    struct rt_sensor_data data;
    rt_size_t res, i;
    rt_int32_t delay;
    rt_err_t result;

    dev = rt_device_find(argv[1]);
    if (dev == RT_NULL)
    {
        LOG_E("Can't find device:%s", argv[1]);
        return;
    }
    if (argc > 2)
        num = atoi(argv[2]);

    sensor = (rt_sensor_t)dev;
    delay  = sensor->info.period_min > 100 ? sensor->info.period_min : 100;

    for (i = 0; i < num; i++)
    {
        res = rt_device_read(dev, 0, &data, 1);
        if (res != 1)
        {
            LOG_E("read data failed!size is %d", res);
        }
        else
        {
            sensor_show_data(i, sensor, &data);
        }
        rt_thread_mdelay(delay);
    }
    rt_device_close(dev);
}