xref: /linux/drivers/iio/humidity/dht11.c (revision b85d45947951d23cb22d90caecf4c1eb81342c96)
1 /*
2  * DHT11/DHT22 bit banging GPIO driver
3  *
4  * Copyright (c) Harald Geyer <harald@ccbib.org>
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14  * GNU General Public License for more details.
15  */
16 
17 #include <linux/err.h>
18 #include <linux/interrupt.h>
19 #include <linux/device.h>
20 #include <linux/kernel.h>
21 #include <linux/printk.h>
22 #include <linux/slab.h>
23 #include <linux/of.h>
24 #include <linux/of_device.h>
25 #include <linux/sysfs.h>
26 #include <linux/io.h>
27 #include <linux/module.h>
28 #include <linux/platform_device.h>
29 #include <linux/wait.h>
30 #include <linux/bitops.h>
31 #include <linux/completion.h>
32 #include <linux/mutex.h>
33 #include <linux/delay.h>
34 #include <linux/gpio.h>
35 #include <linux/of_gpio.h>
36 #include <linux/timekeeping.h>
37 
38 #include <linux/iio/iio.h>
39 
40 #define DRIVER_NAME	"dht11"
41 
42 #define DHT11_DATA_VALID_TIME	2000000000  /* 2s in ns */
43 
44 #define DHT11_EDGES_PREAMBLE 2
45 #define DHT11_BITS_PER_READ 40
46 /*
47  * Note that when reading the sensor actually 84 edges are detected, but
48  * since the last edge is not significant, we only store 83:
49  */
50 #define DHT11_EDGES_PER_READ (2 * DHT11_BITS_PER_READ + \
51 			      DHT11_EDGES_PREAMBLE + 1)
52 
53 /* Data transmission timing (nano seconds) */
54 #define DHT11_START_TRANSMISSION	18  /* ms */
55 #define DHT11_SENSOR_RESPONSE	80000
56 #define DHT11_START_BIT		50000
57 #define DHT11_DATA_BIT_LOW	27000
58 #define DHT11_DATA_BIT_HIGH	70000
59 
60 struct dht11 {
61 	struct device			*dev;
62 
63 	int				gpio;
64 	int				irq;
65 
66 	struct completion		completion;
67 	/* The iio sysfs interface doesn't prevent concurrent reads: */
68 	struct mutex			lock;
69 
70 	s64				timestamp;
71 	int				temperature;
72 	int				humidity;
73 
74 	/* num_edges: -1 means "no transmission in progress" */
75 	int				num_edges;
76 	struct {s64 ts; int value; }	edges[DHT11_EDGES_PER_READ];
77 };
78 
79 static unsigned char dht11_decode_byte(int *timing, int threshold)
80 {
81 	unsigned char ret = 0;
82 	int i;
83 
84 	for (i = 0; i < 8; ++i) {
85 		ret <<= 1;
86 		if (timing[i] >= threshold)
87 			++ret;
88 	}
89 
90 	return ret;
91 }
92 
93 static int dht11_decode(struct dht11 *dht11, int offset, int timeres)
94 {
95 	int i, t, timing[DHT11_BITS_PER_READ], threshold;
96 	unsigned char temp_int, temp_dec, hum_int, hum_dec, checksum;
97 
98 	threshold = DHT11_DATA_BIT_HIGH / timeres;
99 	if (DHT11_DATA_BIT_LOW / timeres + 1 >= threshold)
100 		pr_err("dht11: WARNING: decoding ambiguous\n");
101 
102 	/* scale down with timeres and check validity */
103 	for (i = 0; i < DHT11_BITS_PER_READ; ++i) {
104 		t = dht11->edges[offset + 2 * i + 2].ts -
105 			dht11->edges[offset + 2 * i + 1].ts;
106 		if (!dht11->edges[offset + 2 * i + 1].value)
107 			return -EIO;  /* lost synchronisation */
108 		timing[i] = t / timeres;
109 	}
110 
111 	hum_int = dht11_decode_byte(timing, threshold);
112 	hum_dec = dht11_decode_byte(&timing[8], threshold);
113 	temp_int = dht11_decode_byte(&timing[16], threshold);
114 	temp_dec = dht11_decode_byte(&timing[24], threshold);
115 	checksum = dht11_decode_byte(&timing[32], threshold);
116 
117 	if (((hum_int + hum_dec + temp_int + temp_dec) & 0xff) != checksum)
118 		return -EIO;
119 
120 	dht11->timestamp = ktime_get_real_ns();
121 	if (hum_int < 20) {  /* DHT22 */
122 		dht11->temperature = (((temp_int & 0x7f) << 8) + temp_dec) *
123 					((temp_int & 0x80) ? -100 : 100);
124 		dht11->humidity = ((hum_int << 8) + hum_dec) * 100;
125 	} else if (temp_dec == 0 && hum_dec == 0) {  /* DHT11 */
126 		dht11->temperature = temp_int * 1000;
127 		dht11->humidity = hum_int * 1000;
128 	} else {
129 		dev_err(dht11->dev,
130 			"Don't know how to decode data: %d %d %d %d\n",
131 			hum_int, hum_dec, temp_int, temp_dec);
132 		return -EIO;
133 	}
134 
135 	return 0;
136 }
137 
138 /*
139  * IRQ handler called on GPIO edges
140  */
141 static irqreturn_t dht11_handle_irq(int irq, void *data)
142 {
143 	struct iio_dev *iio = data;
144 	struct dht11 *dht11 = iio_priv(iio);
145 
146 	/* TODO: Consider making the handler safe for IRQ sharing */
147 	if (dht11->num_edges < DHT11_EDGES_PER_READ && dht11->num_edges >= 0) {
148 		dht11->edges[dht11->num_edges].ts = ktime_get_real_ns();
149 		dht11->edges[dht11->num_edges++].value =
150 						gpio_get_value(dht11->gpio);
151 
152 		if (dht11->num_edges >= DHT11_EDGES_PER_READ)
153 			complete(&dht11->completion);
154 	}
155 
156 	return IRQ_HANDLED;
157 }
158 
159 static int dht11_read_raw(struct iio_dev *iio_dev,
160 			  const struct iio_chan_spec *chan,
161 			int *val, int *val2, long m)
162 {
163 	struct dht11 *dht11 = iio_priv(iio_dev);
164 	int ret, timeres;
165 
166 	mutex_lock(&dht11->lock);
167 	if (dht11->timestamp + DHT11_DATA_VALID_TIME < ktime_get_real_ns()) {
168 		timeres = ktime_get_resolution_ns();
169 		if (DHT11_DATA_BIT_HIGH < 2 * timeres) {
170 			dev_err(dht11->dev, "timeresolution %dns too low\n",
171 				timeres);
172 			/* In theory a better clock could become available
173 			 * at some point ... and there is no error code
174 			 * that really fits better.
175 			 */
176 			ret = -EAGAIN;
177 			goto err;
178 		}
179 
180 		reinit_completion(&dht11->completion);
181 
182 		dht11->num_edges = 0;
183 		ret = gpio_direction_output(dht11->gpio, 0);
184 		if (ret)
185 			goto err;
186 		msleep(DHT11_START_TRANSMISSION);
187 		ret = gpio_direction_input(dht11->gpio);
188 		if (ret)
189 			goto err;
190 
191 		ret = request_irq(dht11->irq, dht11_handle_irq,
192 				  IRQF_TRIGGER_RISING | IRQF_TRIGGER_FALLING,
193 				  iio_dev->name, iio_dev);
194 		if (ret)
195 			goto err;
196 
197 		ret = wait_for_completion_killable_timeout(&dht11->completion,
198 							   HZ);
199 
200 		free_irq(dht11->irq, iio_dev);
201 
202 		if (ret == 0 && dht11->num_edges < DHT11_EDGES_PER_READ - 1) {
203 			dev_err(&iio_dev->dev,
204 				"Only %d signal edges detected\n",
205 					dht11->num_edges);
206 			ret = -ETIMEDOUT;
207 		}
208 		if (ret < 0)
209 			goto err;
210 
211 		ret = dht11_decode(dht11,
212 				   dht11->num_edges == DHT11_EDGES_PER_READ ?
213 					DHT11_EDGES_PREAMBLE :
214 					DHT11_EDGES_PREAMBLE - 2,
215 				timeres);
216 		if (ret)
217 			goto err;
218 	}
219 
220 	ret = IIO_VAL_INT;
221 	if (chan->type == IIO_TEMP)
222 		*val = dht11->temperature;
223 	else if (chan->type == IIO_HUMIDITYRELATIVE)
224 		*val = dht11->humidity;
225 	else
226 		ret = -EINVAL;
227 err:
228 	dht11->num_edges = -1;
229 	mutex_unlock(&dht11->lock);
230 	return ret;
231 }
232 
233 static const struct iio_info dht11_iio_info = {
234 	.driver_module		= THIS_MODULE,
235 	.read_raw		= dht11_read_raw,
236 };
237 
238 static const struct iio_chan_spec dht11_chan_spec[] = {
239 	{ .type = IIO_TEMP,
240 		.info_mask_separate = BIT(IIO_CHAN_INFO_PROCESSED), },
241 	{ .type = IIO_HUMIDITYRELATIVE,
242 		.info_mask_separate = BIT(IIO_CHAN_INFO_PROCESSED), }
243 };
244 
245 static const struct of_device_id dht11_dt_ids[] = {
246 	{ .compatible = "dht11", },
247 	{ }
248 };
249 MODULE_DEVICE_TABLE(of, dht11_dt_ids);
250 
251 static int dht11_probe(struct platform_device *pdev)
252 {
253 	struct device *dev = &pdev->dev;
254 	struct device_node *node = dev->of_node;
255 	struct dht11 *dht11;
256 	struct iio_dev *iio;
257 	int ret;
258 
259 	iio = devm_iio_device_alloc(dev, sizeof(*dht11));
260 	if (!iio) {
261 		dev_err(dev, "Failed to allocate IIO device\n");
262 		return -ENOMEM;
263 	}
264 
265 	dht11 = iio_priv(iio);
266 	dht11->dev = dev;
267 
268 	ret = of_get_gpio(node, 0);
269 	if (ret < 0)
270 		return ret;
271 	dht11->gpio = ret;
272 	ret = devm_gpio_request_one(dev, dht11->gpio, GPIOF_IN, pdev->name);
273 	if (ret)
274 		return ret;
275 
276 	dht11->irq = gpio_to_irq(dht11->gpio);
277 	if (dht11->irq < 0) {
278 		dev_err(dev, "GPIO %d has no interrupt\n", dht11->gpio);
279 		return -EINVAL;
280 	}
281 
282 	dht11->timestamp = ktime_get_real_ns() - DHT11_DATA_VALID_TIME - 1;
283 	dht11->num_edges = -1;
284 
285 	platform_set_drvdata(pdev, iio);
286 
287 	init_completion(&dht11->completion);
288 	mutex_init(&dht11->lock);
289 	iio->name = pdev->name;
290 	iio->dev.parent = &pdev->dev;
291 	iio->info = &dht11_iio_info;
292 	iio->modes = INDIO_DIRECT_MODE;
293 	iio->channels = dht11_chan_spec;
294 	iio->num_channels = ARRAY_SIZE(dht11_chan_spec);
295 
296 	return devm_iio_device_register(dev, iio);
297 }
298 
299 static struct platform_driver dht11_driver = {
300 	.driver = {
301 		.name	= DRIVER_NAME,
302 		.of_match_table = dht11_dt_ids,
303 	},
304 	.probe  = dht11_probe,
305 };
306 
307 module_platform_driver(dht11_driver);
308 
309 MODULE_AUTHOR("Harald Geyer <harald@ccbib.org>");
310 MODULE_DESCRIPTION("DHT11 humidity/temperature sensor driver");
311 MODULE_LICENSE("GPL v2");
312