从网上,看到一篇关于dht11驱动的文章,该驱动是通过中断的方式实现的。中断能及时读取dht11的数据,是否就能保证读取到的数据都是正确的呢。将驱动稍作修改后,读出来的数据出错的概率很小。每次进入中断的次数一定,有可能do_gettimeofday(&dev->tv)获取到的时间有可能受到内核调度的影响(优先级高的中断可打断其他优先级低的中断)。原文链接
http://blog.youkuaiyun.com/jvaemape/article/details/36004393
#include <linux/module.h>
#include <linux/workqueue.h>
#include <linux/slab.h>
#include <linux/input.h>
#include <linux/init.h>
#include <linux/errno.h>
#include <linux/serio.h>
#include <linux/delay.h>
#include <linux/clk.h>
#include <linux/wait.h>
#include <linux/sched.h>
#include <linux/cdev.h>
#include <linux/miscdevice.h>
#include <linux/fs.h>
#include <linux/gpio.h>
#include <linux/delay.h>
#include <linux/printk.h>
#include <linux/time.h>
#include <linux/irq.h>
#include <asm-generic/uaccess.h>
#define DEVICE_NAME "dht11"
#define DHT11_PIN S5PV210_GPH0(0)
#define DEVICE_MAJOR 0
struct dht11_sensor_dev{
unsigned long pin;
unsigned char value[5];
unsigned int irq;
int bitcount;
int bytecount;
int started;
int signal;
int time;
int count;
dev_t devno;
struct class *dht11_class;
struct cdev cdev;
struct mutex read_data;
struct timeval lasttv;
struct timeval tv;
struct work_struct dht11_work;
};
static struct dht11_sensor_dev *dht11_dev;
static void dht11_data_factory(struct work_struct *work)
{
long deltv = 0;
mutex_lock(&dht11_dev->read_data);
dht11_dev->count++;
deltv = dht11_dev->tv.tv_sec - dht11_dev->lasttv.tv_sec;
dht11_dev->time = (int)(deltv * 1000000 + (dht11_dev->tv.tv_usec - dht11_dev->lasttv.tv_usec));
dht11_dev->lasttv = dht11_dev->tv;
if((dht11_dev->signal == 1) && (dht11_dev->time>40))
{
dht11_dev->started = 1;
}
else
{
if((dht11_dev->signal == 0) && (dht11_dev->started == 1))
{
dht11_dev->started = 0;
if((dht11_dev->time>20)&&dht11_dev->time <38)
{
dht11_dev->bitcount++;
if(dht11_dev->bitcount == 8)
{
dht11_dev->bitcount = 0;
dht11_dev->bytecount++;
}
}
if ((dht11_dev->time>55)&& (dht11_dev->time<80))
{
dht11_dev->value[dht11_dev->bytecount] = dht11_dev->value[dht11_dev->bytecount] | (0x80 >> dht11_dev->bitcount);
dht11_dev->bitcount++;
if(dht11_dev->bitcount == 8)
{
dht11_dev->bitcount = 0;
dht11_dev->bytecount++;
}
}
}
}
mutex_unlock(&dht11_dev->read_data);
}
static irqreturn_t dht11_interrupt_hander(int irq, void *dev_id)
{
struct dht11_sensor_dev *dev = (struct dht11_sensor_dev *)dev_id;
dev->signal = gpio_get_value(dev->pin);
do_gettimeofday(&dev->tv);
schedule_work(&dht11_dev->dht11_work);
return IRQ_HANDLED;
}
static int dht11_start(void)
{
if(gpio_request(dht11_dev->pin, DEVICE_NAME))
{
printk(KERN_INFO "[%s] gpio_request \n", __func__);
return -1;
}
gpio_direction_output(dht11_dev->pin, 0);
msleep(30);
gpio_set_value(dht11_dev->pin,1);
udelay(30);
gpio_direction_input(dht11_dev->pin);
gpio_free(dht11_dev->pin);
do_gettimeofday(&dht11_dev->lasttv);
dht11_dev->count=0;
return 0;
}
static int dht11_setup_interrupts(void)
{
int result;
dht11_dev->irq = gpio_to_irq(dht11_dev->pin);
result = request_irq(dht11_dev->irq, dht11_interrupt_hander,
IRQ_TYPE_EDGE_BOTH, DEVICE_NAME, (void *)dht11_dev);
switch (result)
{
case -EBUSY:
printk(KERN_ERR "*%s(): IRQ %d is busy\n", __func__, dht11_dev->irq);
return -EBUSY;
case -EINVAL:
printk(KERN_ERR "*%s(): Bad irq number or handler\n", __func__);
return -EINVAL;
default:
// printk("request irq for dht11 ok\n");
return result;
}
}
static int dht11_clear_interrupts(void)
{
free_irq(dht11_dev->irq, (void *)dht11_dev);
msleep(20);
if(gpio_request(dht11_dev->pin, DEVICE_NAME)){
printk(KERN_INFO "[%s] gpio_request \n", __func__);
return -1;
}
gpio_direction_output(dht11_dev->pin, 1);
gpio_free(dht11_dev->pin);
return 1;
}
static int dht11_checksum(struct dht11_sensor_dev *dev)
{
int tmp = 0;
tmp = dev->value[0] + dev->value[1] + dev->value[2] + dev->value[3];
if(tmp != dev->value[4]){
printk(KERN_INFO "[%s] %d %d\n", __func__, dev->value[4], tmp);
return -1;
}
return 1;
}
static int dht11_sensor_open(struct inode *inode, struct file *filp)
{
printk("dht11_sensor_open\n");
return 0;
}
static ssize_t dht11_sensor_read(struct file *filp,char __user *buf,size_t size,loff_t *f_pos)
{
int result = 0;
dht11_dev->started = 0;
dht11_dev->bitcount = 0;
dht11_dev->bytecount = 0;
dht11_dev->value[0] = 0;
dht11_dev->value[1] = 0;
dht11_dev->value[2] = 0;
dht11_dev->value[3] = 0;
dht11_dev->value[4] = 0;
dht11_start();
dht11_setup_interrupts();
msleep(10);
dht11_clear_interrupts();
result=dht11_checksum(dht11_dev);
if(result<0)
return -EAGAIN;
printk("Humidity=%d.%d%%---Temperature=%d.%dC\n",\
dht11_dev->value[0], dht11_dev->value[1], \
dht11_dev->value[2], dht11_dev->value[3]);
printk("count =%d\n",dht11_dev->count);
result=copy_to_user(buf,&dht11_dev->value,4);
if(result<0)
{
printk("copy to user err\n");
return -EAGAIN;
}
return result;
}
static int dht11_sensor_release(struct inode *inode,struct file *filp)
{
module_put(THIS_MODULE);
return 0;
}
static struct file_operations dht11_sensor_fops={
.owner = THIS_MODULE,
.open = dht11_sensor_open,
.read = dht11_sensor_read,
.release = dht11_sensor_release,
};
static int dht11_gpio_init(void)
{
int result;
dht11_dev->pin = DHT11_PIN;
result=gpio_request(dht11_dev->pin, DEVICE_NAME);
if(result)
{
printk(KERN_INFO "[%s] gpio_request \n", __func__);
return -1;
}
gpio_direction_output(dht11_dev->pin,1);
gpio_free(dht11_dev->pin);
return 0;
}
static int dht11_sensor_setup_cdev(void)
{
int ret;
cdev_init(&(dht11_dev->cdev), &dht11_sensor_fops);
dht11_dev->cdev.owner = THIS_MODULE;
ret=cdev_add(&(dht11_dev->cdev),dht11_dev->devno, 1);
if(ret)
{
printk(KERN_NOTICE"erro %d adding %s\n",ret,DEVICE_NAME);
}
return ret;
}
int __init dht11_sensor_init(void)
{
int result;
dht11_dev=kmalloc(sizeof(struct dht11_sensor_dev),GFP_KERNEL);
if(!dht11_dev)
{
result=-ENOMEM;
goto allocate_memory_fail;
}
if(DEVICE_MAJOR)
{
result = register_chrdev_region(dht11_dev->devno, 1, DEVICE_NAME);
}
else
{
result = alloc_chrdev_region(&dht11_dev->devno, 0, 1, DEVICE_NAME);
}
if(result < 0)
{
printk("register_chrdev_region err!\n");
goto chardev_region_fail;
}
dht11_dev->dht11_class = class_create(THIS_MODULE, DEVICE_NAME);
if(IS_ERR(dht11_dev->dht11_class))
{
printk("Err: failed in creating class.\n");
goto class_create_fail;
}
device_create(dht11_dev->dht11_class, NULL,dht11_dev->devno, NULL, DEVICE_NAME);
result=dht11_sensor_setup_cdev();
if(result<0)
goto cdev_fail;
result=dht11_gpio_init();
if(result<0)
goto gpio_request_fail;
INIT_WORK(&dht11_dev->dht11_work,dht11_data_factory);
mutex_init(&dht11_dev->read_data);
printk("dht11 init ok!\n");
return 0;
gpio_request_fail:
cdev_del(&dht11_dev->cdev);
cdev_fail:
device_destroy(dht11_dev->dht11_class,dht11_dev->devno);
class_destroy(dht11_dev->dht11_class);
class_create_fail:
unregister_chrdev_region(dht11_dev->devno,1);
chardev_region_fail:
allocate_memory_fail:
kfree(dht11_dev);
return result;
}
void __exit dht11_sensor_exit(void)
{
cdev_del(&dht11_dev->cdev);
device_destroy(dht11_dev->dht11_class,dht11_dev->devno);
class_destroy(dht11_dev->dht11_class);
unregister_chrdev_region(dht11_dev->devno, 1);
kfree(dht11_dev);
}
module_init(dht11_sensor_init);
module_exit(dht11_sensor_exit);
MODULE_AUTHOR("jvaemape");
MODULE_DESCRIPTION("DHT11 Driver");
MODULE_LICENSE("Dual BSD/GPL");
其实,高版本的内核中已集成湿度传感器的驱动,可以研究一下https://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/tree/drivers/iio/humidity/dht11.c?id=refs/tags/v4.5
源码摘录如下
/*
* DHT11/DHT22 bit banging GPIO driver
*
* Copyright (c) Harald Geyer <harald@ccbib.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#include <linux/err.h>
#include <linux/interrupt.h>
#include <linux/device.h>
#include <linux/kernel.h>
#include <linux/printk.h>
#include <linux/slab.h>
#include <linux/of.h>
#include <linux/of_device.h>
#include <linux/sysfs.h>
#include <linux/io.h>
#include <linux/module.h>
#include <linux/platform_device.h>
#include <linux/wait.h>
#include <linux/bitops.h>
#include <linux/completion.h>
#include <linux/mutex.h>
#include <linux/delay.h>
#include <linux/gpio.h>
#include <linux/of_gpio.h>
#include <linux/timekeeping.h>
#include <linux/iio/iio.h>
#define DRIVER_NAME "dht11"
#define DHT11_DATA_VALID_TIME 2000000000 /* 2s in ns */
#define DHT11_EDGES_PREAMBLE 2
#define DHT11_BITS_PER_READ 40
/*
* Note that when reading the sensor actually 84 edges are detected, but
* since the last edge is not significant, we only store 83:
*/
#define DHT11_EDGES_PER_READ (2 * DHT11_BITS_PER_READ + \
DHT11_EDGES_PREAMBLE + 1)
/* Data transmission timing (nano seconds) */
#define DHT11_START_TRANSMISSION 18 /* ms */
#define DHT11_SENSOR_RESPONSE 80000
#define DHT11_START_BIT 50000
#define DHT11_DATA_BIT_LOW 27000
#define DHT11_DATA_BIT_HIGH 70000
struct dht11 {
struct device *dev;
int gpio;
int irq;
struct completion completion;
/* The iio sysfs interface doesn't prevent concurrent reads: */
struct mutex lock;
s64 timestamp;
int temperature;
int humidity;
/* num_edges: -1 means "no transmission in progress" */
int num_edges;
struct {s64 ts; int value; } edges[DHT11_EDGES_PER_READ];
};
static unsigned char dht11_decode_byte(int *timing, int threshold)
{
unsigned char ret = 0;
int i;
for (i = 0; i < 8; ++i) {
ret <<= 1;
if (timing[i] >= threshold)
++ret;
}
return ret;
}
static int dht11_decode(struct dht11 *dht11, int offset, int timeres)
{
int i, t, timing[DHT11_BITS_PER_READ], threshold;
unsigned char temp_int, temp_dec, hum_int, hum_dec, checksum;
threshold = DHT11_DATA_BIT_HIGH / timeres;
if (DHT11_DATA_BIT_LOW / timeres + 1 >= threshold)
pr_err("dht11: WARNING: decoding ambiguous\n");
/* scale down with timeres and check validity */
for (i = 0; i < DHT11_BITS_PER_READ; ++i) {
t = dht11->edges[offset + 2 * i + 2].ts -
dht11->edges[offset + 2 * i + 1].ts;
if (!dht11->edges[offset + 2 * i + 1].value)
return -EIO; /* lost synchronisation */
timing[i] = t / timeres;
}
hum_int = dht11_decode_byte(timing, threshold);
hum_dec = dht11_decode_byte(&timing[8], threshold);
temp_int = dht11_decode_byte(&timing[16], threshold);
temp_dec = dht11_decode_byte(&timing[24], threshold);
checksum = dht11_decode_byte(&timing[32], threshold);
if (((hum_int + hum_dec + temp_int + temp_dec) & 0xff) != checksum)
return -EIO;
dht11->timestamp = ktime_get_boot_ns();
if (hum_int < 20) { /* DHT22 */
dht11->temperature = (((temp_int & 0x7f) << 8) + temp_dec) *
((temp_int & 0x80) ? -100 : 100);
dht11->humidity = ((hum_int << 8) + hum_dec) * 100;
} else if (temp_dec == 0 && hum_dec == 0) { /* DHT11 */
dht11->temperature = temp_int * 1000;
dht11->humidity = hum_int * 1000;
} else {
dev_err(dht11->dev,
"Don't know how to decode data: %d %d %d %d\n",
hum_int, hum_dec, temp_int, temp_dec);
return -EIO;
}
return 0;
}
/*
* IRQ handler called on GPIO edges
*/
static irqreturn_t dht11_handle_irq(int irq, void *data)
{
struct iio_dev *iio = data;
struct dht11 *dht11 = iio_priv(iio);
/* TODO: Consider making the handler safe for IRQ sharing */
if (dht11->num_edges < DHT11_EDGES_PER_READ && dht11->num_edges >= 0) {
dht11->edges[dht11->num_edges].ts = ktime_get_boot_ns();
dht11->edges[dht11->num_edges++].value =
gpio_get_value(dht11->gpio);
if (dht11->num_edges >= DHT11_EDGES_PER_READ)
complete(&dht11->completion);
}
return IRQ_HANDLED;
}
static int dht11_read_raw(struct iio_dev *iio_dev,
const struct iio_chan_spec *chan,
int *val, int *val2, long m)
{
struct dht11 *dht11 = iio_priv(iio_dev);
int ret, timeres;
mutex_lock(&dht11->lock);
if (dht11->timestamp + DHT11_DATA_VALID_TIME < ktime_get_boot_ns()) {
timeres = ktime_get_resolution_ns();
if (DHT11_DATA_BIT_HIGH < 2 * timeres) {
dev_err(dht11->dev, "timeresolution %dns too low\n",
timeres);
/* In theory a better clock could become available
* at some point ... and there is no error code
* that really fits better.
*/
ret = -EAGAIN;
goto err;
}
reinit_completion(&dht11->completion);
dht11->num_edges = 0;
ret = gpio_direction_output(dht11->gpio, 0);
if (ret)
goto err;
msleep(DHT11_START_TRANSMISSION);
ret = gpio_direction_input(dht11->gpio);
if (ret)
goto err;
ret = request_irq(dht11->irq, dht11_handle_irq,
IRQF_TRIGGER_RISING | IRQF_TRIGGER_FALLING,
iio_dev->name, iio_dev);
if (ret)
goto err;
ret = wait_for_completion_killable_timeout(&dht11->completion,
HZ);
free_irq(dht11->irq, iio_dev);
if (ret == 0 && dht11->num_edges < DHT11_EDGES_PER_READ - 1) {
dev_err(&iio_dev->dev,
"Only %d signal edges detected\n",
dht11->num_edges);
ret = -ETIMEDOUT;
}
if (ret < 0)
goto err;
ret = dht11_decode(dht11,
dht11->num_edges == DHT11_EDGES_PER_READ ?
DHT11_EDGES_PREAMBLE :
DHT11_EDGES_PREAMBLE - 2,
timeres);
if (ret)
goto err;
}
ret = IIO_VAL_INT;
if (chan->type == IIO_TEMP)
*val = dht11->temperature;
else if (chan->type == IIO_HUMIDITYRELATIVE)
*val = dht11->humidity;
else
ret = -EINVAL;
err:
dht11->num_edges = -1;
mutex_unlock(&dht11->lock);
return ret;
}
static const struct iio_info dht11_iio_info = {
.driver_module = THIS_MODULE,
.read_raw = dht11_read_raw,
};
static const struct iio_chan_spec dht11_chan_spec[] = {
{ .type = IIO_TEMP,
.info_mask_separate = BIT(IIO_CHAN_INFO_PROCESSED), },
{ .type = IIO_HUMIDITYRELATIVE,
.info_mask_separate = BIT(IIO_CHAN_INFO_PROCESSED), }
};
static const struct of_device_id dht11_dt_ids[] = {
{ .compatible = "dht11", },
{ }
};
MODULE_DEVICE_TABLE(of, dht11_dt_ids);
static int dht11_probe(struct platform_device *pdev)
{
struct device *dev = &pdev->dev;
struct device_node *node = dev->of_node;
struct dht11 *dht11;
struct iio_dev *iio;
int ret;
iio = devm_iio_device_alloc(dev, sizeof(*dht11));
if (!iio) {
dev_err(dev, "Failed to allocate IIO device\n");
return -ENOMEM;
}
dht11 = iio_priv(iio);
dht11->dev = dev;
ret = of_get_gpio(node, 0);
if (ret < 0)
return ret;
dht11->gpio = ret;
ret = devm_gpio_request_one(dev, dht11->gpio, GPIOF_IN, pdev->name);
if (ret)
return ret;
dht11->irq = gpio_to_irq(dht11->gpio);
if (dht11->irq < 0) {
dev_err(dev, "GPIO %d has no interrupt\n", dht11->gpio);
return -EINVAL;
}
dht11->timestamp = ktime_get_boot_ns() - DHT11_DATA_VALID_TIME - 1;
dht11->num_edges = -1;
platform_set_drvdata(pdev, iio);
init_completion(&dht11->completion);
mutex_init(&dht11->lock);
iio->name = pdev->name;
iio->dev.parent = &pdev->dev;
iio->info = &dht11_iio_info;
iio->modes = INDIO_DIRECT_MODE;
iio->channels = dht11_chan_spec;
iio->num_channels = ARRAY_SIZE(dht11_chan_spec);
return devm_iio_device_register(dev, iio);
}
static struct platform_driver dht11_driver = {
.driver = {
.name = DRIVER_NAME,
.of_match_table = dht11_dt_ids,
},
.probe = dht11_probe,
};
module_platform_driver(dht11_driver);
MODULE_AUTHOR("Harald Geyer <harald@ccbib.org>");
MODULE_DESCRIPTION("DHT11 humidity/temperature sensor driver");
MODULE_LICENSE("GPL v2");