Sensor Driver Development Guide

This document is a development guide document for sensor drivers under the RT-Thread Sensor driver framework, providing development standards and specifications for the development team.

  • Engineers engaged in sensor-driven development

Note

Note: Before reading this document, please read the sensor driver framework introduction first .

Developing a sensor driver generally requires the following steps: research and preparation, development, testing, and submission.

During the development process, you can refer to the supported sensors. Click here to view the list of supported sensors .

According to the datasheet or other methods, understand the characteristics of the sensor and record them, such as the following:

  • Sensor Type

  • Communication interface (i2c/spi/...)

  • Measuring range

  • Shortest measurement cycle

  • Support several working modes and power modes

The main task of development is to connect to the ops interface of the Sensor driver framework, and then register it as a Sensor device, so that the relevant behaviors of the sensor can be controlled through the driver framework.

ops interface connection

The sensor framework provides two interfaces ( fetch_data/ control), which need to be implemented in the driver.

fetch_data

Function: Get sensor data. Interface prototype:

rt_size_t (*fetch_data)(struct rt_sensor_device *sensor, void *buf, rt_size_t len);copymistakeCopy Success

The Sensor driver framework currently supports three default opening modes: polling (RT_DEVICE_FLAG_RDONLY), interrupt (RT_DEVICE_FLAG_INT_RX), and FIFO (RT_DEVICE_FLAG_FIFO_RX). You need to determine the working mode of the sensor here, and then return the sensor data according to different modes.

As shown below:

static rt_size_t xxx_acc_fetch_data(struct rt_sensor_device *sensor, void *buf, rt_size_t len)
{
    if (sensor->parent.open_flag & RT_DEVICE_FLAG_RDONLY)
    {
        return _xxx_acc_polling_get_data(sensor, buf, len);
    }
    else if (sensor->parent.open_flag & RT_DEVICE_FLAG_INT_RX)
    {
        return _xxx_acc_int_get_data(sensor, buf, len);
    }
    else if (sensor->parent.open_flag & RT_DEVICE_FLAG_FIFO_RX)
    {
        return _xxx_acc_fifo_get_data(sensor, buf, len);
    }
    else
        return 0;
}copymistakeCopy Success

When returning data, developers should first identify the data type of the stored data, and then fill in the data field and timestamp, as shown below:

sensor_data->type = RT_SENSOR_CLASS_ACCE
sensor_data->data.acce.x = acceleration.x;
sensor_data->data.acce.y = acceleration.y;
sensor_data->data.acce.z = acceleration.z;
sensor_data->timestamp = rt_sensor_get_ts();copymistakeCopy Success

Note

Note: - Please use the timestamp acquisition function provided by the Sensor driver framework to obtain the timestamp rt_sensor_get_ts. - In FIFO mode, the underlying data may be coupled, and a module needs to be used to update the data of two sensors at the same time. - The data unit must be converted to the data unit specified in the Sensor driver framework.

The data units are as follows:

Sensor Name

type

unit

illustrate

Accelerometer

RT_SENSOR_CLASS_ACCE

mg

1 g = 1000 mg, 1 g = 9.8 m/s2

Gyroscope

RT_SENSOR_CLASS_GYRO

mdps

1 dps = 1000 mdps, dps (degrees per second)

Magnetometer

RT_SENSOR_CLASS_MAG

mGauss

1 G = 1000 mGauss

Ambient Light

RT_SENSOR_CLASS_LIGHT

lux

Lumen value

Approaching light

RT_SENSOR_CLASS_PROXIMITY

centimeters

Represents the distance from the object to the sensor, unit: cm

Barometer

RT_SENSOR_CLASS_BARO

Pa

100 Pa = 1 hPa (hectopascal)

thermometer

RT_SENSOR_CLASS_TEMP

°c/10

0.1 degrees Celsius

Hygrometer

RT_SENSOR_CLASS_HUMI

Relative humidity RH, usually expressed in ‰

Heart rate monitor

RT_SENSOR_CLASS_HR

bpm

Times per minute

noise

RT_SENSOR_CLASS_NOISE

HZ

Frequency Unit

Pedometer

RT_SENSOR_CLASS_STEP

1

Number of steps: dimensionless unit 1

Force Sensors

RT_SENSOR_UNIT_MN

mN

Pressure: 10^-3 N

Note: New sensor data units will be added iteratively later.

control

rt_err_t (*control)(struct rt_sensor_device *sensor, int cmd, void *arg);copymistakeCopy Success

The control of the sensor is realized by this interface function. Different operations are performed by judging the different command words passed in. Currently, the following command words are supported:

#define  RT_SENSOR_CTRL_GET_ID            (0)  /* 读设备ID */
#define  RT_SENSOR_CTRL_GET_INFO          (1)  /* 获取设备信息(由框架实现,在驱动中不需要实现)*/
#define  RT_SENSOR_CTRL_SET_RANGE         (2)  /* 设置传感器测量范围 */
#define  RT_SENSOR_CTRL_SET_ODR           (3)  /* 设置传感器数据输出速率,unit is HZ */
#define  RT_SENSOR_CTRL_SET_MODE          (4)  /* 设置工作模式 */
#define  RT_SENSOR_CTRL_SET_POWER         (5)  /* 设置电源模式 */
#define  RT_SENSOR_CTRL_SELF_TEST         (6)  /* 自检 */copymistakeCopy Success

This function needs to be implemented in the driver as follows:

static rt_err_t xxx_acc_control(struct rt_sensor_device *sensor, int cmd, void *args)
{
    rt_err_t result = RT_EOK;

    switch (cmd)
    {
    case RT_SENSOR_CTRL_GET_ID:
        result = _xxx_acc_get_id(sensor, args);
        break;
    case RT_SENSOR_CTRL_SET_RANGE:
        result = _xxx_acc_set_range(sensor, (rt_int32_t)args);
        break;
    case RT_SENSOR_CTRL_SET_ODR:
        result = _xxx_acc_set_odr(sensor, (rt_uint32_t)args & 0xffff);
        break;
    case RT_SENSOR_CTRL_SET_MODE:
        result = _xxx_acc_set_mode(sensor, (rt_uint32_t)args & 0xff);
        break;
    case RT_SENSOR_CTRL_SET_POWER:
        result = _xxx_acc_set_power(sensor, (rt_uint32_t)args & 0xff);
        break;
    case RT_SENSOR_CTRL_SELF_TEST:
        break;
    default:
        return -RT_ERROR;
    }
    return result;
}copymistakeCopy Success

Note

Note: It should be noted that the data type of the parameter passed is specified by the struct rt_sensor_config structure. Therefore, RT_SENSOR_CTRL_SET_RANGEthe parameter passed by this command is rt_int32_tof type , which needs to be forced once to get the correct parameter.

Then implement a device interface structure ops to store the above interface functions,

static struct rt_sensor_ops xxx_ops =
{
    xxx_acc_fetch_data,
    xxx_acc_control
};copymistakeCopy Success

Device Registration

After completing the docking of the Sensor's ops, you need to register a sensor device so that the upper layer can find the sensor device and then control it.

Device registration requires the following steps: create a rt_sensor_tstructure pointer, allocate memory for the structure, and complete related initialization.

int rt_hw_xxx_init(const char *name, struct rt_sensor_config *cfg)
{
    rt_int8_t result;
    rt_sensor_t sensor = RT_NULL;

    sensor = rt_calloc(1, sizeof(struct rt_sensor_device));
    if (sensor == RT_NULL)
        return -1;

    sensor->info.type       = RT_SENSOR_CLASS_ACCE;
    sensor->info.vendor     = RT_SENSOR_VENDOR_STM;
    sensor->info.model      = "xxx_acce";
    sensor->info.unit       = RT_SENSOR_UNIT_MG;
    sensor->info.intf_type  = RT_SENSOR_INTF_I2C;
    sensor->info.range_max  = SENSOR_ACC_RANGE_16G;
    sensor->info.range_min  = SENSOR_ACC_RANGE_2G;
    sensor->info.period_min = 100;

    rt_memcpy(&sensor->config, cfg, sizeof(struct rt_sensor_config));
    sensor->ops = &sensor_ops;

    result = rt_hw_sensor_register(sensor, name, RT_DEVICE_FLAG_RDONLY | RT_DEVICE_FLAG_FIFO_RX, RT_NULL);
    if (result != RT_EOK)
    {
        LOG_E("device register err code: %d", result);
        rt_free(sensor);
        return -RT_ERROR;
    }

    LOG_I("acc sensor init success");
    return 0;
}copymistakeCopy Success

Note

Note: - rt_hw_sensor_registerA prefix will be automatically added to the name passed in, such as 加速度计the type of sensor will automatically add acce_a prefix. Since the system default device name is up to 7 characters, if the name passed in exceeds 3 characters, it will be truncated. - When registering, if the sensor supports FIFO, you need to add the RT_DEVICE_FLAG_FIFO_RX flag. - If two devices are coupled, you need to use a module to decouple them. Initialize a module, assign the device control blocks of the two sensors to it, and assign the module address to the two sensor devices. The framework will automatically create a module lock.

The parameter passed in struct rt_sensor_config *cfgis used to decouple the hardware communication interface. By passing this parameter in when the underlying driver is initialized, the hardware interface configuration is implemented. It contains struct rt_sensor_intfthis structure,

struct rt_sensor_intf
{
    char         *dev_name;   /* The name of the communication device */
    rt_uint8_t    type;       /* Communication interface type */
    void         *user_data;  /* Private data for the sensor. ex. i2c addr,spi cs,control I/O */
};copymistakeCopy Success

Among them, type indicates the type of interface, dev_name indicates the name of the device, such as "i2c1". user_data is some private data of this interface type. If it is I2C, this is the i2c address corresponding to the sensor, and the input method is (void*)0x55.

When initializing the underlying driver, you need to initialize this structure first, and then pass it in as a parameter to complete the decoupling of the communication interface. Similar to this:

#define irq_pin GET_PIN(B, 0)

int lps22hb_port(void)
{
    struct rt_sensor_config cfg;

    cfg.intf.dev_name = "i2c1";
    cfg.intf.user_data = (void *)0x55;
    cfg.irq_pin.pin = irq_pin;
    cfg.irq_pin.mode = PIN_MODE_INPUT_PULLDOWN;
    rt_hw_xxx_init("xxx", &cfg);

    return RT_EOK;
}
INIT_APP_EXPORT(lps22hb_port);copymistakeCopy Success

  1. Use the list_device command to check whether the corresponding device is successfully registered.

  2. Use the exported test function sensor_polling/int/fifo <sensor_name> to determine whether the data can be read successfully.

  3. Testing other modes and control interfaces

The Sensor driver needs to 软件包be submitted in the form of . For the specific structure, please refer to the existing Sensor software package. For the specific submission process, please refer to the Document Center: Software Package Development Guide

  • Used when dynamically allocating memory rt_calloc, this API will initialize the requested memory to 0, and there is no need to manually clear it.

  • Please assign initial values ​​to statically defined variables, and initialize unused variables to 0.

  • If possible, please support multiple instances. Please pay attention to the following issues:

    • No global variables

    • All configuration information is stored in the sensor structure

    • Configurations not in the sensor structure are stored using the user_data of rt_device

Last updated

Assoc. Prof. Wiroon Sriborrirux, Founder of Advance Innovation Center (AIC) and Bangsaen Design House (BDH), Electrical Engineering Department, Faculty of Engineering, Burapha University