dht11.c 7.91 KB
Newer Older
Harald Geyer's avatar
Harald Geyer committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
/*
 * 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>
Richard Weinberger's avatar
Richard Weinberger committed
32
#include <linux/mutex.h>
Harald Geyer's avatar
Harald Geyer committed
33 34 35
#include <linux/delay.h>
#include <linux/gpio.h>
#include <linux/of_gpio.h>
36
#include <linux/timekeeping.h>
Harald Geyer's avatar
Harald Geyer committed
37 38 39 40 41 42 43

#include <linux/iio/iio.h>

#define DRIVER_NAME	"dht11"

#define DHT11_DATA_VALID_TIME	2000000000  /* 2s in ns */

Richard Weinberger's avatar
Richard Weinberger committed
44
#define DHT11_EDGES_PREAMBLE 2
Harald Geyer's avatar
Harald Geyer committed
45
#define DHT11_BITS_PER_READ 40
Richard Weinberger's avatar
Richard Weinberger committed
46 47 48 49
/*
 * Note that when reading the sensor actually 84 edges are detected, but
 * since the last edge is not significant, we only store 83:
 */
50 51
#define DHT11_EDGES_PER_READ (2 * DHT11_BITS_PER_READ + \
			      DHT11_EDGES_PREAMBLE + 1)
Harald Geyer's avatar
Harald Geyer committed
52 53 54 55 56 57 58 59 60 61 62 63 64 65 66

/* 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;
67
	/* The iio sysfs interface doesn't prevent concurrent reads: */
Richard Weinberger's avatar
Richard Weinberger committed
68
	struct mutex			lock;
Harald Geyer's avatar
Harald Geyer committed
69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92

	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;
}

93
static int dht11_decode(struct dht11 *dht11, int offset, int timeres)
Harald Geyer's avatar
Harald Geyer committed
94
{
95
	int i, t, timing[DHT11_BITS_PER_READ], threshold;
Harald Geyer's avatar
Harald Geyer committed
96 97 98
	unsigned char temp_int, temp_dec, hum_int, hum_dec, checksum;

	threshold = DHT11_DATA_BIT_HIGH / timeres;
99
	if (DHT11_DATA_BIT_LOW / timeres + 1 >= threshold)
Harald Geyer's avatar
Harald Geyer committed
100 101 102 103
		pr_err("dht11: WARNING: decoding ambiguous\n");

	/* scale down with timeres and check validity */
	for (i = 0; i < DHT11_BITS_PER_READ; ++i) {
104 105 106
		t = dht11->edges[offset + 2 * i + 2].ts -
			dht11->edges[offset + 2 * i + 1].ts;
		if (!dht11->edges[offset + 2 * i + 1].value)
Harald Geyer's avatar
Harald Geyer committed
107 108 109 110 111 112 113 114 115 116 117 118 119
			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;

120
	dht11->timestamp = ktime_get_real_ns();
Harald Geyer's avatar
Harald Geyer committed
121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137
	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;
}

Richard Weinberger's avatar
Richard Weinberger committed
138 139 140 141 142 143 144 145 146 147
/*
 * 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) {
148
		dht11->edges[dht11->num_edges].ts = ktime_get_real_ns();
Richard Weinberger's avatar
Richard Weinberger committed
149 150 151 152 153 154 155 156 157 158
		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;
}

Harald Geyer's avatar
Harald Geyer committed
159
static int dht11_read_raw(struct iio_dev *iio_dev,
160
			  const struct iio_chan_spec *chan,
Harald Geyer's avatar
Harald Geyer committed
161 162 163
			int *val, int *val2, long m)
{
	struct dht11 *dht11 = iio_priv(iio_dev);
164
	int ret, timeres;
Harald Geyer's avatar
Harald Geyer committed
165

Richard Weinberger's avatar
Richard Weinberger committed
166
	mutex_lock(&dht11->lock);
167 168 169 170 171 172 173 174 175 176 177 178 179
	if (dht11->timestamp + DHT11_DATA_VALID_TIME < ktime_get_real_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;
		}

Harald Geyer's avatar
Harald Geyer committed
180 181 182 183 184 185 186 187 188 189 190
		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;

Richard Weinberger's avatar
Richard Weinberger committed
191 192 193 194 195 196
		ret = request_irq(dht11->irq, dht11_handle_irq,
				  IRQF_TRIGGER_RISING | IRQF_TRIGGER_FALLING,
				  iio_dev->name, iio_dev);
		if (ret)
			goto err;

Harald Geyer's avatar
Harald Geyer committed
197
		ret = wait_for_completion_killable_timeout(&dht11->completion,
198
							   HZ);
Richard Weinberger's avatar
Richard Weinberger committed
199 200 201

		free_irq(dht11->irq, iio_dev);

Harald Geyer's avatar
Harald Geyer committed
202 203
		if (ret == 0 && dht11->num_edges < DHT11_EDGES_PER_READ - 1) {
			dev_err(&iio_dev->dev,
204
				"Only %d signal edges detected\n",
Harald Geyer's avatar
Harald Geyer committed
205 206 207 208 209 210 211
					dht11->num_edges);
			ret = -ETIMEDOUT;
		}
		if (ret < 0)
			goto err;

		ret = dht11_decode(dht11,
212
				   dht11->num_edges == DHT11_EDGES_PER_READ ?
Harald Geyer's avatar
Harald Geyer committed
213
					DHT11_EDGES_PREAMBLE :
214 215
					DHT11_EDGES_PREAMBLE - 2,
				timeres);
Harald Geyer's avatar
Harald Geyer committed
216 217 218 219 220 221 222 223 224 225 226 227 228
		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;
Richard Weinberger's avatar
Richard Weinberger committed
229
	mutex_unlock(&dht11->lock);
Harald Geyer's avatar
Harald Geyer committed
230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267
	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;

268
	ret = of_get_gpio(node, 0);
Harald Geyer's avatar
Harald Geyer committed
269 270
	if (ret < 0)
		return ret;
271
	dht11->gpio = ret;
Harald Geyer's avatar
Harald Geyer committed
272 273 274 275 276 277 278 279 280 281
	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;
	}

282
	dht11->timestamp = ktime_get_real_ns() - DHT11_DATA_VALID_TIME - 1;
Harald Geyer's avatar
Harald Geyer committed
283 284 285 286 287
	dht11->num_edges = -1;

	platform_set_drvdata(pdev, iio);

	init_completion(&dht11->completion);
Richard Weinberger's avatar
Richard Weinberger committed
288
	mutex_init(&dht11->lock);
Harald Geyer's avatar
Harald Geyer committed
289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311
	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");