基于 RT-Thread 的智能家居系统 Demo(一)使用 Sensor 框架读取 DS18B20 温度数据

学习要点:

  1. 实现 DS18B20 温度传感器驱动;
  2. 介绍 RT-Thread 的 sensor 组件;
  3. 将 DS18B20 温度传感器对接 RT-Thread 的 sensor 组件(提高上层代码的可重用性);
  4. 学习线程的使用,在线程中正确读取 DS18B20 温度值。

DS18B20 驱动

头文件 sensor_dallas_ds18b20.h,提供以下 API:

API 描述
ds18b20_init 初始化 ds18b20 设备
ds18b20_get_temperature 读取 ds18b20 温度数据
rt_hw_ds18b20_init 初始化并注册 ds18b20 设备
#ifndef __DS18B20_H__
#define __DS18B20_H__

#include 
#include 
#include 
#include "sensor.h"

#define CONNECT_SUCCESS  0
#define CONNECT_FAILED   1

struct ds18b20_device
{
    rt_base_t pin;
    rt_mutex_t lock;
};
typedef struct ds18b20_device *ds18b20_device_t;

uint8_t ds18b20_init(rt_base_t pin);
int32_t ds18b20_get_temperature(rt_base_t pin);
int rt_hw_ds18b20_init(const char *name, struct rt_sensor_config *cfg);

#endif /* __DS18B20_H_ */

源文件 sensor_dallas_ds18b20.c,具体如下:

#include "sensor_dallas_ds18b20.h"
#include "sensor.h"
#include "board.h"
#include 

#define DBG_TAG "sensor.dallas.ds18b20"
#define DBG_LVL DBG_INFO

#define SENSOR_TEMP_RANGE_MAX (125)
#define SENSOR_TEMP_RANGE_MIN (-55)

RT_WEAK void rt_hw_us_delay(rt_uint32_t us)
{
    rt_uint32_t delta;

    us = us * (SysTick->LOAD / (1000000 / RT_TICK_PER_SECOND));
    delta = SysTick->VAL;

    while (delta - SysTick->VAL < us) continue;
}

static void ds18b20_reset(rt_base_t pin)
{
    rt_pin_mode(pin, PIN_MODE_OUTPUT);
    rt_pin_write(pin, PIN_LOW);
    rt_hw_us_delay(780);               /* 480us - 960us */
    rt_pin_write(pin, PIN_HIGH);
    rt_hw_us_delay(40);                /* 15us - 60us*/
}

static uint8_t ds18b20_connect(rt_base_t pin)
{
    uint8_t retry = 0;
    rt_pin_mode(pin, PIN_MODE_INPUT);

    while (rt_pin_read(pin) && retry < 200)
    {
        retry++;
        rt_hw_us_delay(1);
    };

    if(retry >= 200)
        return CONNECT_FAILED;
    else
        retry = 0;

    while (!rt_pin_read(pin) && retry < 240)
    {
        retry++;
        rt_hw_us_delay(1);
    };

    if(retry >= 240)
        return CONNECT_FAILED;

    return CONNECT_SUCCESS;
}

static uint8_t ds18b20_read_bit(rt_base_t pin)
{
    uint8_t data;

    rt_pin_mode(pin, PIN_MODE_OUTPUT);
    rt_pin_write(pin, PIN_LOW);
    rt_hw_us_delay(2);
    rt_pin_write(pin, PIN_HIGH);
    rt_pin_mode(pin, PIN_MODE_INPUT);
    rt_hw_us_delay(12);

    if(rt_pin_read(pin))
        data = 1;
    else
        data = 0;

    rt_hw_us_delay(50);

    return data;
}

static uint8_t ds18b20_read_byte(rt_base_t pin)
{
    uint8_t i, j, dat;
    dat = 0;

    for (i = 1; i <= 8; i++)
    {
        j = ds18b20_read_bit(pin);
        dat = (j << 7) | (dat >> 1);
    }

    return dat;
}

static void ds18b20_write_byte(rt_base_t pin, uint8_t dat)
{
    uint8_t j;
    uint8_t testb;
    rt_pin_mode(pin, PIN_MODE_OUTPUT);

    for (j = 1; j <= 8; j++)
    {
        testb = dat & 0x01;
        dat = dat >> 1;

        if(testb)
        {
            rt_pin_write(pin, PIN_LOW);
            rt_hw_us_delay(1);
            rt_pin_write(pin, PIN_HIGH);
            rt_hw_us_delay(60);
        }
        else
        {
            rt_pin_write(pin, PIN_LOW);
            rt_hw_us_delay(60);
            rt_pin_write(pin, PIN_HIGH);
            rt_hw_us_delay(1);
        }
    }
}

void ds18b20_start(rt_base_t pin)
{
    ds18b20_reset(pin);
    ds18b20_connect(pin);
    ds18b20_write_byte(pin, 0xcc);  /* skip rom */
    ds18b20_write_byte(pin, 0x44);  /* convert */
}

uint8_t ds18b20_init(rt_base_t pin)
{
    uint8_t ret = 0;

    ds18b20_reset(pin);
    ret = ds18b20_connect(pin);

    return ret;
}

int32_t ds18b20_get_temperature(rt_base_t pin)
{
    uint8_t TL, TH;
    int32_t tem;
	rt_ubase_t level;
    
    ds18b20_start(pin);
    ds18b20_init(pin);

	level = rt_hw_interrupt_disable();  /* Disable global interrupt */

    ds18b20_write_byte(pin, 0xcc);
    ds18b20_write_byte(pin, 0xbe);
    TL = ds18b20_read_byte(pin);    /* LSB first */
    TH = ds18b20_read_byte(pin);

	rt_hw_interrupt_enable(level);  /* Enable global interrupt */

    tem = TH;
    tem <<= 8;
    tem |= TL;
    
    if(tem < 0)
    {
        tem = tem - 1;
        tem = ~tem;
        tem = (int32_t)(tem * 0.0625 * 10 + 0.5);
        return -tem;
    }
    else
    {
        tem = (int32_t)(tem * 0.0625 * 10 + 0.5);
        return tem;
    }
}

static rt_size_t _ds18b20_polling_get_data(rt_sensor_t sensor, struct rt_sensor_data *data)
{
    rt_int32_t temperature_x10;
    if (sensor->info.type == RT_SENSOR_CLASS_TEMP)
    {
        temperature_x10 = ds18b20_get_temperature((rt_base_t)sensor->config.intf.user_data);
        data->data.temp = temperature_x10;
        data->timestamp = rt_sensor_get_ts();
    }    
    return 1;
}

static rt_size_t ds18b20_fetch_data(struct rt_sensor_device *sensor, void *buf, rt_size_t len)
{
    RT_ASSERT(buf);

    if (sensor->config.mode == RT_SENSOR_MODE_POLLING)
    {
        return _ds18b20_polling_get_data(sensor, buf);
    }
    else
        return 0;
}

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

    return result;
}

static struct rt_sensor_ops sensor_ops =
{
    ds18b20_fetch_data,
    ds18b20_control
};

int rt_hw_ds18b20_init(const char *name, struct rt_sensor_config *cfg)
{
    rt_int8_t result;
    rt_sensor_t sensor_temp = RT_NULL; 
    
    if (!ds18b20_init((rt_base_t)cfg->intf.user_data))
    {
        /* temperature sensor register */
        sensor_temp = rt_calloc(1, sizeof(struct rt_sensor_device));
        if (sensor_temp == RT_NULL)
            return -1;

        sensor_temp->info.type       = RT_SENSOR_CLASS_TEMP;
        sensor_temp->info.vendor     = RT_SENSOR_VENDOR_DALLAS;
        sensor_temp->info.model      = "ds18b20";
        sensor_temp->info.unit       = RT_SENSOR_UNIT_DCELSIUS;
        sensor_temp->info.intf_type  = RT_SENSOR_INTF_ONEWIRE;
        sensor_temp->info.range_max  = SENSOR_TEMP_RANGE_MAX;
        sensor_temp->info.range_min  = SENSOR_TEMP_RANGE_MIN;
        sensor_temp->info.period_min = 5;

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

        result = rt_hw_sensor_register(sensor_temp, name, RT_DEVICE_FLAG_RDONLY, RT_NULL);
        if (result != RT_EOK)
        {
            LOG_E("device register err code: %d", result);
            goto __exit;
        }

    }
	else {
		rt_kprintf("ds18b20 init failed.\n");
	}
    return RT_EOK;
    
__exit:
    if (sensor_temp)
        rt_free(sensor_temp);
    return -RT_ERROR;     
}

将这两个文件放到 bsp 工程的 board/ports/ 目录下,并修改 board/SConscript 文件,如下:

import os
import rtconfig
from building import *

Import('SDK_LIB')

cwd = GetCurrentDir()

# add general drivers
src = Split('''
board.c
CubeMX_Config/Src/stm32f4xx_hal_msp.c
''')

src += Glob('ports/sensor_dallas_ds18b20.c')

path =  [cwd]
path += [cwd + '/CubeMX_Config/Inc']
path += [cwd + '/ports']

startup_path_prefix = SDK_LIB

if rtconfig.CROSS_TOOL == 'gcc':
    src += [startup_path_prefix + '/STM32F4xx_HAL/CMSIS/Device/ST/STM32F4xx/Source/Templates/gcc/startup_stm32f411xe.s']
elif rtconfig.CROSS_TOOL == 'keil':
    src += [startup_path_prefix + '/STM32F4xx_HAL/CMSIS/Device/ST/STM32F4xx/Source/Templates/arm/startup_stm32f411xe.s']
elif rtconfig.CROSS_TOOL == 'iar':
    src += [startup_path_prefix + '/STM32F4xx_HAL/CMSIS/Device/ST/STM32F4xx/Source/Templates/iar/startup_stm32f411xe.s']

# STM32F405xx) || STM32F415xx) || STM32F407xx) || STM32F417xx)
# STM32F427xx) || STM32F437xx) || STM32F429xx) || STM32F439xx)
# STM32F401xC) || STM32F401xE) || STM32F410Tx) || STM32F410Cx)
# STM32F410Rx) || STM32F411xE) || STM32F446xx) || STM32F469xx)
# STM32F479xx) || STM32F412Cx) || STM32F412Rx) || STM32F412Vx)
# STM32F412Zx) || STM32F413xx) || STM32F423xx)
# You can select chips from the list above
CPPDEFINES = ['STM32F411xE']
group = DefineGroup('Drivers', src, depend = [''], CPPPATH = path, CPPDEFINES = CPPDEFINES)

Return('group')

Sensor 框架介绍

Sensor 框架的整体框架图如下所示。它为上层提供的是标准 device 接口 open/close/read/write/control,这些接口与上层用户程序对接,为底层驱动提供的是简单的 ops(operations 操作命令)接口 fetch_data/control,这两个接口对接具体硬件的底层驱动。除此之外,Sensor 框架还支持 module(模块),为底层存在耦合的传感器设备提供服务,如果,ds18b20 的底层不存在耦合,此处不需要用到 module。

基于 RT-Thread 的智能家居系统 Demo(一)使用 Sensor 框架读取 DS18B20 温度数据_第1张图片

Sensor 框架更多的介绍在 RT-Thread 的文档中心已有详细说明,这里不过多赘述,链接:https://www.rt-thread.org/document/site/development-guide/sensor/sensor_driver/

Sensor 框架的使用

看完文档中心的 Sensor 介绍后,相信大伙儿已经对这个框架有了一定的了解。有的小伙伴是不是早就按耐不住想要跃跃欲试将传感器对接到 Sensor 框架上?这里以 ds18b20 温度传感器为例子。

Sensor 框架的使用分三个步骤:

  1. 开启 sensor 框架
  2. ops 接口对接
  3. 传感器设备注册

开启 sensor 框架

在 menuconfig 中将它开启

RT-Thread Components --->
  Device Drivers --->
      [*] Using Sensor device drivers

打开之后,需要使用 scons --target=mdk5 更新工程即可。看,Sensor 框架加入到工程当中了:

ops 接口对接

我们知道,Sensor 框架的接口分为上层接口和底层接口两种。将 ds18b20 的底层驱动对接到框架上,其实对接就是 Sensor 框架的底层接口,具体的,是底层的 ops 接口。

我们在 RT-Thread 源码中可以找到 Sensor 框架的源码,源码路径为:rt-thread\components\drivers\sensors,在 sensor.h 文件中,我们可以找到对 ops 接口的定义,有两个函数指针,fetch_datacontorl

struct rt_sensor_ops
{
    rt_size_t (*fetch_data)(struct rt_sensor_device *sensor, void *buf, rt_size_t len);
    rt_err_t (*control)(struct rt_sensor_device *sensor, int cmd, void *arg);
};
  • fetch_data 作用是获取传感器数据
  • control 作用是通过控制命令控制传感器

ds18b20 并不支持 control,我们只需要实现 fetch_data 就好了。

Sensor 框架当前默认支持三种打开方式:

  1. 轮询(RT_DEVICE_FLAG_RDONLY
  2. 中断(RT_DEVICE_FLAG_INT_RX
  3. FIFO(RT_DEVICE_FLAG_FIFO_RX

需要在这里判断传感器的工作模式,然后再根据不同的模式返回传感器数据。我们以轮询的方式读取 ds18b20 的温度数据,那么 fetch_data 的实现如下:

static rt_size_t 
ds18b20_fetch_data(struct rt_sensor_device *sensor, void *buf, rt_size_t len)
{
    RT_ASSERT(buf);

    if (sensor->config.mode == RT_SENSOR_MODE_POLLING) {
        return _ds18b20_polling_get_data(sensor, buf);
    }
    else return 0;
}

具体的,_ds18b20_polling_get_data(sensor, buf) 的实现如下,其中,ds18b20_get_temperature 函数就是 ds18b20 温度传感器底层驱动的获取温度的函数。

static rt_size_t 
_ds18b20_polling_get_data(rt_sensor_t sensor, struct rt_sensor_data *data)
{
    rt_int32_t temperature_x10;
    if (sensor->info.type == RT_SENSOR_CLASS_TEMP) {
      temperature_x10 = ds18b20_get_temperature((rt_base_t)sensor->config.intf.user_data);
      data->data.temp = temperature_x10;
      data->timestamp = rt_sensor_get_ts();
    }    
    return 1;
}

因为不需要 control,我们直接让 control 返回 RT_EOK 即可

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

这样,我们的 ops 函数就写好了。然后,需要实现一个设备接口的结构体 ops 存储上面的接口函数:

static struct rt_sensor_ops sensor_ops =
{
    ds18b20_fetch_data,
    ds18b20_control
};

这样一来, ops 接口就对接成功了。

传感器设备注册

完成 Sensor 的 ops 的对接之后还要注册一个 Sensor 设备,这样上层才能找到这个传感器设备,进而进行控制。

设备的注册一共需要下面几步:

  1. 创建一个 rt_sensor_t 的结构体指针
  2. 为结构体分配内存
  3. 完成相关初始化

具体的,放到 ds18b20 上面来,具体实现如下:

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

  if (!ds18b20_init((rt_base_t)cfg->intf.user_data))
  {
      /* temperature sensor register */
      sensor_temp = rt_calloc(1, sizeof(struct rt_sensor_device));
      if (sensor_temp == RT_NULL)
          return -1;

      sensor_temp->info.type       = RT_SENSOR_CLASS_TEMP;
      sensor_temp->info.vendor     = RT_SENSOR_VENDOR_DALLAS;
      sensor_temp->info.model     = "ds18b20";
      sensor_temp->info.unit       = RT_SENSOR_UNIT_DCELSIUS;
      sensor_temp->info.intf_type = RT_SENSOR_INTF_ONEWIRE;
      sensor_temp->info.range_max = SENSOR_TEMP_RANGE_MAX;
      sensor_temp->info.range_min = SENSOR_TEMP_RANGE_MIN;
      sensor_temp->info.period_min = 5;

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

      result = rt_hw_sensor_register(sensor_temp, name, RT_DEVICE_FLAG_RDONLY, RT_NULL);
      if (result != RT_EOK)
      {
          LOG_E("device register err code: %d", result);
          goto __exit;
      }

  }
  return RT_EOK;

__exit:
  if (sensor_temp)
      rt_free(sensor_temp);
  return -RT_ERROR;    
}

我们来解读一下

传感器设备注册的第一步:创建一个 rt_sensor_t 的结构体指针,上述代码中是这么实现的:

rt_sensor_t sensor_temp = RT_NULL;

传感器设备注册的第二步:为结构体分配内存,上述代码中是这么实现的:

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

传感器设备注册的第三步:完成相关初始化,上述代码中是这么实现的:

      sensor_temp->info.type       = RT_SENSOR_CLASS_TEMP;
      sensor_temp->info.vendor     = RT_SENSOR_VENDOR_DALLAS;
      sensor_temp->info.model     = "ds18b20";
      sensor_temp->info.unit       = RT_SENSOR_UNIT_DCELSIUS;
      sensor_temp->info.intf_type = RT_SENSOR_INTF_ONEWIRE;
      sensor_temp->info.range_max = SENSOR_TEMP_RANGE_MAX;
      sensor_temp->info.range_min = SENSOR_TEMP_RANGE_MIN;
      sensor_temp->info.period_min = 5;

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

传感器设备注册的三个步骤完成之后,就可以放心大胆地注册传感器设备了,上述代码中是这么实现的:

rt_hw_sensor_register(sensor_temp, name, RT_DEVICE_FLAG_RDONLY, RT_NULL);

上述的 “ops 接口对接” 和 “传感器设备注册” 两个工作完成后,就可以通过 Sensor 框架中的上层接口 open/close/read/write/control,对 ds18b20 进行操作了。

先不着急,我们在 FinSH 中输入 list_device 命令查看 ds18b20 温度传感器是否真的已经被注册上去了。

关于设备名称

在本示例代码中,温度传感器初始化时传入的设备名称为 ds18b20,如下所示:

static int rt_hw_ds18b20_port(void)
{
    struct rt_sensor_config cfg;

    cfg.intf.user_data = (void *)DS18B20_DATA_PIN;
    rt_hw_ds18b20_init("ds18b20", &cfg);

    return RT_EOK;
}
INIT_ENV_EXPORT(rt_hw_ds18b20_port);

rt_device_find 查找设备时使用的却是 temp_ds18b20。这是因为 Sensor 框架会根据不同的传感器类型,会为其添加一个前缀,对于温度传感器则添加 temp_。在 components/drivers/sensors/sensor.c 有如下代码:

static char *const sensor_name_str[] =
{
    "none",
    "acce_",     /* Accelerometer     */
    "gyro_",     /* Gyroscope         */
    "mag_",      /* Magnetometer      */
    "temp_",     /* Temperature       */
    "humi_",     /* Relative Humidity */
    "baro_",     /* Barometer         */
    "li_",       /* Ambient light     */
    "pr_",       /* Proximity         */
    "hr_",       /* Heart Rate        */
    "tvoc_",     /* TVOC Level        */
    "noi_",      /* Noise Loudness    */
    "step_",     /* Step sensor       */
    "forc_"      /* Force sensor      */
};

关中断读取数据

为了提高软件可靠性,在 ds18b20_get_temperature 函数中调用底层接口读取温度数据时,增加了关中断操作,如下:

int32_t ds18b20_get_temperature(rt_base_t pin)
{
    uint8_t TL, TH;
    int32_t tem;
	rt_ubase_t level;
    
    ds18b20_start(pin);
    ds18b20_init(pin);

	level = rt_hw_interrupt_disable();  /* Disable global interrupt */

    ds18b20_write_byte(pin, 0xcc);
    ds18b20_write_byte(pin, 0xbe);
    TL = ds18b20_read_byte(pin);    /* LSB first */
    TH = ds18b20_read_byte(pin);

	rt_hw_interrupt_enable(level);  /* Enable global interrupt */
    
    ...
}

在线程中读取温度数据

我们通过一个线程,去实时获取 ds18b20 的温度数据。

线程的基本操作有:

  • 创建/初始化( rt_thread_create / rt_thread_init
  • 启动(rt_thread_startup
  • 运行(rt_thread_delay / rt_thread_control
  • 删除/脱离(rt_thread_delete / rt_thread_detach

之前我们已经将 ds18b20 对接到 ops 接口并成功注册成传感器设备了,接下来就可以利用 Sensor 框架的上层接口 open/close/read/write/control 对 ds18b20 进行操作了。

main 函数中创建一个读取 ds18b20 温度数据的线程并启动它,线程入口函数是 read_temp_entry

rt_thread_t ds18b20_thread, led_thread;

ds18b20_thread = rt_thread_create("18b20tem",
                                read_temp_entry,
                                "temp_ds18b20",
                                512,
                                RT_THREAD_PRIORITY_MAX / 2,
                                20);
if (ds18b20_thread != RT_NULL) {
  rt_thread_startup(ds18b20_thread);
}

在线程入口函数 read_temp_entry 中,我们通过几个步骤,就可以读取 ds18b20 的温度数据了:

  1. 创建一个 rt_sensor_data 的数据结构体
  2. 查找传感器设备驱动
  3. 打开对应的传感器设备
  4. 读取传感器设备数据

上述步骤具体实现如下:

static void read_temp_entry(void *parameter)
{
  rt_device_t dev = RT_NULL;
  struct rt_sensor_data sensor_data;
  rt_size_t res;

  dev = rt_device_find(parameter);
  if (dev == RT_NULL) {
      rt_kprintf("Can't find device:%s\n", parameter);
      return;
  }

  if (rt_device_open(dev, RT_DEVICE_FLAG_RDWR) != RT_EOK) {
      rt_kprintf("open device failed!\n");
      return;
  }
  rt_device_control(dev, RT_SENSOR_CTRL_SET_ODR, (void *)100);

  while (1) {
      
      res = rt_device_read(dev, 0, &sensor_data, 1);
      if (res != 1) {
          rt_kprintf("read data failed!size is %d\n", res);
          rt_device_close(dev);
          return;
      } else {
          rt_kprintf("temp:%3d.%dC, timestamp:%5d\n", 
                     sensor_data.data.temp / 10, 
                     sensor_data.data.temp % 10, 
                     sensor_data.timestamp);
      }
      rt_thread_mdelay(100);
  }
}

通过 FinSH 控制台,查看该线程源源不断输出的数据:

基于 RT-Thread 的智能家居系统 Demo(一)使用 Sensor 框架读取 DS18B20 温度数据_第2张图片

你可能感兴趣的:(单片机,RT-Thread,RT-Thread,系列)