DHT11

dht11和ds18b20很类似,都是使用单总线通信的。

3种编程实现方式:

  • 查询方式,直接操作gpio,时序通过延时等待实现等
  • 中断方式,通过设置双边沿触发中断,获取时序中高低电平时间,根据时间来判定解析时序
  • 使用内核自带dht11驱动

对于dht11的工作原理,参考别人文章即可:https://blog.csdn.net/qq_44981039/article/details/110185982

驱动实现

野火imx6ull开发板原理图

在这里插入图片描述

设备树编写

根节点下添加:dht11

dht11 {
	compatible = "xgj,dht11";
	pinctrl-names = "default";
	pinctrl-0 = <&pinctrl_ds18b20>;
	dht11-gpios = <&gpio1 2 GPIO_ACTIVE_HIGH>; 
	status = "okay"; 
}

iomuxc节点下添加:

	/*ds18b20*/
	pinctrl_ds18b20: ds18b20grp {
		fsl,pins = <
			MX6UL_PAD_GPIO1_IO02__GPIO1_IO02	0x10b0  
		>;
	}; 

  • dht11和ds18b20使用的是同一个引脚

设备树编译:

ares@ubuntu:~/work/ebf_linux_kernel-ebf_4.19.35_imx6ul$ cat make_dtb.sh
#!/bin/sh

make ARCH=arm -j4 CROSS_COMPILE=arm-linux-gnueabihf- dtbs

将设备树拷贝系统目录:

debian@npi:~/nfs_root/driver$ cat cp_dtb_to_linux.sh
#!/bin/sh

sudo cp imx6ull-mmc-npi.dtb /usr/lib/linux-image-4.19.35-carp-imx6/
  • /usr/lib/linux-image-4.19.35-carp-imx6/ ,系统存放设备树的目录

重启系统设备树生效:

sudo reboot

驱动编写

typedef unsigned char  uint8_t;

#define DEV_DTS_NODE_PATH    "/dht11"                /* 设备树节点的路径,在根节点下 */
#define DEV_PIN_DTS_NAME     "dht11-gpios"           /* GPIO引脚的属性名 */
#define DEV_NAME             "dht11"                 /* 设备名  /dev/dht11 */
#define DEV_DTS_COMPATIBLE   "xgj,dht11"             /* 设备匹配属性 compatible */

#define DHT11_PIN               dht11_dev.gpio
#define DHT11_IO_OUT()          gpio_direction_output(DHT11_PIN, 1);
#define DHT11_IO_IN()           gpio_direction_input(DHT11_PIN)
#define DHT11_WRITE(bit)        gpio_set_value(DHT11_PIN, bit)
#define DHT11_READ()            gpio_get_value(DHT11_PIN)

struct dht11 {
    int gpio;                       /* gpio */ 
    int irq;
    dev_t dev_no;                   /* 设备号 */    
    struct cdev chrdev;             
    struct class *class;
    spinlock_t lock;
};
static int dht11_wait_for_ready(void)
{   
    int timeout;

    timeout = 400;
    while (DHT11_READ() && timeout)      /* 等待低电平到来 */
    {
        udelay(1);
        --timeout;
    }
    if (!timeout) 
    {
        printk("timeout %d\n", __LINE__);
        return -1;    /* 超时 */
    }

    timeout = 1000;
    while (!DHT11_READ() && timeout)      /* 等待高电平到来    */
    {
        udelay(1);
        --timeout;
    }
    if (!timeout) 
    {
        printk("timeout %d\n", __LINE__);
        return -1;    /* 超时 */
    }

    timeout = 1000;
    while (DHT11_READ() && timeout)  /* 等待高电平结束 */
    {
        udelay(1);
        --timeout;
    }
    if (!timeout) 
    {
        printk("timeout %d\n", __LINE__);
        return -1;    /* 超时 */
    }

    return 0;
}

static int dht11_start(void)      
{
    DHT11_IO_OUT();
    DHT11_WRITE(0);
    mdelay(20);
    DHT11_WRITE(1);
    udelay(30);
    DHT11_IO_IN();          /* 设置为输入 */ 
    udelay(2);
   
    if (dht11_wait_for_ready()) return -1;
    return 0;
}

static int dht11_read_byte(unsigned char *byte)
{
    unsigned char i;
    unsigned char bit = 0;
    unsigned char data = 0;
    int timeout = 0;   
    
    for (i = 0; i < 8; i++)
    {
        timeout = 1000;  
        while (DHT11_READ() && timeout)   /* 等待变为低电平 */
        {
            udelay(1);
            --timeout;
        }
        if (!timeout) 
        {
            printk("timeout %d\n", __LINE__);         
            return -1;           /* 超时 */
        }

        timeout = 1000;
        while (!DHT11_READ() && timeout)    /* 等待变为高电平 */
        {
            udelay(1);
            --timeout;
        }
        if (!timeout) 
        {
            printk("timeout %d\n", __LINE__);
            return -1;           /* 超时 */
        }
        udelay(40);
        
        bit = DHT11_READ();

        data <<= 1;            
        if (bit) 
        {
            data |= 0x01;
        #if 0
            timeout = 1000;
            while (DHT11_READ() && timeout)    /* 等待高电平结束 */
            {
                udelay(1);
                --timeout;
            }
            if (!timeout) 
            {
                printk("timeout %d\n", __LINE__);
                return -1;           /* 超时 */
            }
        #endif
        }
        // data <<= 1;          /* 导致错误的原因 : 移位要放前面,不能放在这里,若放在后面一旦获取最后一个位就会多移动一位导致数据不对 */
    }

    *byte = data;
    return 0;
}
  • 这部分就是驱动dht11的代码,和单片机下驱动没有什么区别。
  • 在编写读取一个字节的函数时出现谬误 : data <<= 1,数据移位,不能放到最后,移位要放前面,不能放在这里,若放在后面一旦获取最后一个位就会多移动一位导致数据不对,该谬误导致调试了挺久,开始还以为时序有问题一直检查时序。。。

dht11驱动跟内核框架有关的部分:

/* 使设备只能被一个进程打开 */
static int _drv_open (struct inode *node, struct file *file)   
{
    printk("dht11 open\n");
    return 0;
}

static ssize_t _drv_read(struct file *filp, char __user *buf, size_t size, loff_t *offset)
{
    int ret;
    int i;
    unsigned  char data[5] = {0};
    unsigned long flags;

    if (size != 5) return -EINVAL;
    
    /* 关闭中断,防止时序被中断破坏 */
    spin_lock_irqsave(&dht11_dev.lock, flags);
    
    /* 启动信号 */
    if (dht11_start() != 0)
    {
        printk("dht11 start failed\n");
        ret = -EFAULT;
        goto failed1;
    }

    /* 读出5字节数据 */
    for (i = 0; i < 5; i++)    
    {
        if (dht11_read_byte(&data[i]))
        {
            printk("read data err\n");
            ret = -EAGAIN;
            goto failed1;
        }
    }
    
     /* 打开中断 */
    spin_unlock_irqrestore(&dht11_dev.lock, flags);
        /* 校验数据 */
    if (data[4] != (data[0]+data[1]+data[2]+data[3]))
    {
        printk("check data failed\n");
        ret = -EAGAIN;
        goto failed1;
    }
    
    /* 将数据拷贝回用户空间 */
	if (copy_to_user(buf, data, 5)) 
    {
        ret = -EFAULT;
    } 
    else 
    {
        ret = 5;
    }

    return ret;
failed1:
    spin_unlock_irqrestore(&dht11_dev.lock, flags);
    return ret;
}

static int _drv_release(struct inode *node, struct file *file)
{
    printk("dht11 release\n");
    return 0;
}

static struct file_operations drv_file_ops = { 
	.owner	= THIS_MODULE,
	.open   = _drv_open,
    .read   = _drv_read,
    .release = _drv_release,
};

/* 设备树的匹配列表 */
static struct of_device_id dts_match_table[] = {
    {.compatible = DEV_DTS_COMPATIBLE, },                     /* 通过设备树来匹配 */
};

static int _driver_probe(struct platform_device *pdev)
{ 
    int err;
    struct device *ds_dev;
    struct device_node *dev_node;
    
    struct device_node *node = pdev->dev.of_node;

    if (!node) {          
        printk("hc-sr501 dts node can not found!\r\n");    
        return -EINVAL; 
    }

    dev_node = of_find_node_by_path(DEV_DTS_NODE_PATH);       /* 找到dht11的设备树节点  */
    if (IS_ERR(dev_node)) {          
        printk("dht11 DTS Node not found!\r\n"); 
        return PTR_ERR(dev_node); 
    }

    dht11_dev.gpio = of_get_named_gpio(dev_node, DEV_PIN_DTS_NAME, 0);   /* 获取dht11的gpio编号 */
    if ( dht11_dev.gpio < 0) {
        printk("dht11-gpio not found!\r\n"); 
        return -EINVAL;
    }

    err = gpio_request(dht11_dev.gpio, DEV_PIN_DTS_NAME);  
	if(err) 
    {
		printk("gpio_request gpio is failed!\n");
        return -EINVAL;
	}

    printk("dht11 gpio %d\n", dht11_dev.gpio);

    /* 内核自动分配设备号 */
    err = alloc_chrdev_region(&dht11_dev.dev_no, 0, 1, DEV_NAME);        
	if (err < 0) {
		pr_err("Error: failed to register mbochs_dev, err: %d\n", err);
        goto failed3;
	}

	cdev_init(&dht11_dev.chrdev, &drv_file_ops);

	cdev_add(&dht11_dev.chrdev, dht11_dev.dev_no, 1);

    dht11_dev.class = class_create(THIS_MODULE, DEV_NAME);
	if (IS_ERR(dht11_dev.class)) {   
        err = PTR_ERR(dht11_dev.class);
        goto failed1;
	}

    /* 创建设备节点 */
    ds_dev = device_create(dht11_dev.class , NULL, dht11_dev.dev_no, NULL, DEV_NAME); 
    if (IS_ERR(ds_dev)) {       /* 判断指针是否合法 */
        err = PTR_ERR(ds_dev);
		goto failed2;
	}

    spin_lock_init(&dht11_dev.lock);          /* 初始化自旋锁 */
    printk("dht11 probe success\r\n");
    return 0;
failed2:
    device_destroy(dht11_dev.class, dht11_dev.dev_no);
    class_destroy(dht11_dev.class);
failed1:
    unregister_chrdev_region(dht11_dev.dev_no, 1);
    cdev_del(&dht11_dev.chrdev);
failed3:
    gpio_free(dht11_dev.gpio);
    return err;
}

static int _driver_remove(struct platform_device *pdev)
{
    device_destroy(dht11_dev.class, dht11_dev.dev_no);
	class_destroy(dht11_dev.class);
	unregister_chrdev_region(dht11_dev.dev_no, 1);
    cdev_del(&dht11_dev.chrdev);
    gpio_free(dht11_dev.gpio);

    printk(KERN_INFO"dht11 remove success\n");

    return 0;
}

static struct platform_driver _platform_driver = {
      .probe = _driver_probe,
      .remove = _driver_remove,
      .driver = {
        .name = DEV_DTS_COMPATIBLE,
        .owner = THIS_MODULE,
        .of_match_table = dts_match_table,         /* 通过设备树匹配 */
      },
};

/* 入口函数 */ 
static int __init _driver_init(void)
{
    int ret;
    printk("dht11 %s\n", __FUNCTION__);
    
    ret = platform_driver_register(&_platform_driver);   //注册platform驱动
    return ret;
}

/*  出口函数 */
static void __exit _driver_exit(void)
{
    printk("dht11  %s\n", __FUNCTION__);
    platform_driver_unregister(&_platform_driver);
}

module_init(_driver_init);
module_exit(_driver_exit);

MODULE_AUTHOR("Ares");
MODULE_LICENSE("GPL");

测试程序

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <sys/ioctl.h>
#include <poll.h>
#include <stdint.h>

#define DEV_NAME   "/dev/dht11"

void sleep_ms(unsigned int ms)
{
    struct timeval delay;
	delay.tv_sec = 0;
	delay.tv_usec = ms * 1000; 
	select(0, NULL, NULL, NULL, &delay);
}

int main(int argc, char **argv)
{
	int fd;
    int ret;
  
    struct pollfd fds[1];
	
	/* 2. 打开文件 */
	fd = open(DEV_NAME, O_RDWR);   // | O_NONBLOCK

	if (fd < 0)
	{
		printf("can not open file %s, %d\n", DEV_NAME, fd);
		return -1;
	}

    uint8_t dht11_data[5];
    while (1)
    {
        if ((ret = read(fd, dht11_data, sizeof(dht11_data))) == sizeof(dht11_data))
        {
            printf("temp %d.%d  humi %d.%d\r\n", dht11_data[2], dht11_data[3], dht11_data[0], dht11_data[1]);  
        }
        else
        {
            printf("get temp err %d\r\n", ret);
        }
        sleep_ms(500);   
    }
}

中断方式

通过编写调试发现通过中断方式很难实现,由于linux的非实时性,中断会丢失,会导致时序不对。

内核中自带的dht11驱动使用IIO子系统实现

drivers/iio/humidity/dht11.c

内核配置:
请添加图片描述
编写设备树参考Documentation\devicetree\bindings\iio\humidity\dht11.txt

* DHT11 humidity/temperature sensor (and compatibles like DHT22)

Required properties:
  - compatible: Should be "dht11"
  - gpios: Should specify the GPIO connected to the sensor's data
    line, see "gpios property" in
    Documentation/devicetree/bindings/gpio/gpio.txt.

Example:

humidity_sensor {
	compatible = "dht11";
	gpios = <&gpio0 6 0>;
}
  • 若要使用内核dht11驱动,只要在设备树中添加compatible = "dht11"
  • gpios ,设置传感器的单总线的通信引脚
Logo

更多推荐