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