xref: /linux/drivers/iio/humidity/dht11.c (revision 44f57d78)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * DHT11/DHT22 bit banging GPIO driver
4  *
5  * Copyright (c) Harald Geyer <harald@ccbib.org>
6  */
7 
8 #include <linux/err.h>
9 #include <linux/interrupt.h>
10 #include <linux/device.h>
11 #include <linux/kernel.h>
12 #include <linux/printk.h>
13 #include <linux/slab.h>
14 #include <linux/of.h>
15 #include <linux/of_device.h>
16 #include <linux/sysfs.h>
17 #include <linux/io.h>
18 #include <linux/module.h>
19 #include <linux/platform_device.h>
20 #include <linux/wait.h>
21 #include <linux/bitops.h>
22 #include <linux/completion.h>
23 #include <linux/mutex.h>
24 #include <linux/delay.h>
25 #include <linux/gpio.h>
26 #include <linux/of_gpio.h>
27 #include <linux/timekeeping.h>
28 
29 #include <linux/iio/iio.h>
30 
31 #define DRIVER_NAME	"dht11"
32 
33 #define DHT11_DATA_VALID_TIME	2000000000  /* 2s in ns */
34 
35 #define DHT11_EDGES_PREAMBLE 2
36 #define DHT11_BITS_PER_READ 40
37 /*
38  * Note that when reading the sensor actually 84 edges are detected, but
39  * since the last edge is not significant, we only store 83:
40  */
41 #define DHT11_EDGES_PER_READ (2 * DHT11_BITS_PER_READ + \
42 			      DHT11_EDGES_PREAMBLE + 1)
43 
44 /*
45  * Data transmission timing:
46  * Data bits are encoded as pulse length (high time) on the data line.
47  * 0-bit: 22-30uS -- typically 26uS (AM2302)
48  * 1-bit: 68-75uS -- typically 70uS (AM2302)
49  * The acutal timings also depend on the properties of the cable, with
50  * longer cables typically making pulses shorter.
51  *
52  * Our decoding depends on the time resolution of the system:
53  * timeres > 34uS ... don't know what a 1-tick pulse is
54  * 34uS > timeres > 30uS ... no problem (30kHz and 32kHz clocks)
55  * 30uS > timeres > 23uS ... don't know what a 2-tick pulse is
56  * timeres < 23uS ... no problem
57  *
58  * Luckily clocks in the 33-44kHz range are quite uncommon, so we can
59  * support most systems if the threshold for decoding a pulse as 1-bit
60  * is chosen carefully. If somebody really wants to support clocks around
61  * 40kHz, where this driver is most unreliable, there are two options.
62  * a) select an implementation using busy loop polling on those systems
63  * b) use the checksum to do some probabilistic decoding
64  */
65 #define DHT11_START_TRANSMISSION_MIN	18000  /* us */
66 #define DHT11_START_TRANSMISSION_MAX	20000  /* us */
67 #define DHT11_MIN_TIMERES	34000  /* ns */
68 #define DHT11_THRESHOLD		49000  /* ns */
69 #define DHT11_AMBIG_LOW		23000  /* ns */
70 #define DHT11_AMBIG_HIGH	30000  /* ns */
71 
72 struct dht11 {
73 	struct device			*dev;
74 
75 	int				gpio;
76 	int				irq;
77 
78 	struct completion		completion;
79 	/* The iio sysfs interface doesn't prevent concurrent reads: */
80 	struct mutex			lock;
81 
82 	s64				timestamp;
83 	int				temperature;
84 	int				humidity;
85 
86 	/* num_edges: -1 means "no transmission in progress" */
87 	int				num_edges;
88 	struct {s64 ts; int value; }	edges[DHT11_EDGES_PER_READ];
89 };
90 
91 #ifdef CONFIG_DYNAMIC_DEBUG
92 /*
93  * dht11_edges_print: show the data as actually received by the
94  *                    driver.
95  */
96 static void dht11_edges_print(struct dht11 *dht11)
97 {
98 	int i;
99 
100 	dev_dbg(dht11->dev, "%d edges detected:\n", dht11->num_edges);
101 	for (i = 1; i < dht11->num_edges; ++i) {
102 		dev_dbg(dht11->dev, "%d: %lld ns %s\n", i,
103 			dht11->edges[i].ts - dht11->edges[i - 1].ts,
104 			dht11->edges[i - 1].value ? "high" : "low");
105 	}
106 }
107 #endif /* CONFIG_DYNAMIC_DEBUG */
108 
109 static unsigned char dht11_decode_byte(char *bits)
110 {
111 	unsigned char ret = 0;
112 	int i;
113 
114 	for (i = 0; i < 8; ++i) {
115 		ret <<= 1;
116 		if (bits[i])
117 			++ret;
118 	}
119 
120 	return ret;
121 }
122 
123 static int dht11_decode(struct dht11 *dht11, int offset)
124 {
125 	int i, t;
126 	char bits[DHT11_BITS_PER_READ];
127 	unsigned char temp_int, temp_dec, hum_int, hum_dec, checksum;
128 
129 	for (i = 0; i < DHT11_BITS_PER_READ; ++i) {
130 		t = dht11->edges[offset + 2 * i + 2].ts -
131 			dht11->edges[offset + 2 * i + 1].ts;
132 		if (!dht11->edges[offset + 2 * i + 1].value) {
133 			dev_dbg(dht11->dev,
134 				"lost synchronisation at edge %d\n",
135 				offset + 2 * i + 1);
136 			return -EIO;
137 		}
138 		bits[i] = t > DHT11_THRESHOLD;
139 	}
140 
141 	hum_int = dht11_decode_byte(bits);
142 	hum_dec = dht11_decode_byte(&bits[8]);
143 	temp_int = dht11_decode_byte(&bits[16]);
144 	temp_dec = dht11_decode_byte(&bits[24]);
145 	checksum = dht11_decode_byte(&bits[32]);
146 
147 	if (((hum_int + hum_dec + temp_int + temp_dec) & 0xff) != checksum) {
148 		dev_dbg(dht11->dev, "invalid checksum\n");
149 		return -EIO;
150 	}
151 
152 	dht11->timestamp = ktime_get_boot_ns();
153 	if (hum_int < 4) {  /* DHT22: 100000 = (3*256+232)*100 */
154 		dht11->temperature = (((temp_int & 0x7f) << 8) + temp_dec) *
155 					((temp_int & 0x80) ? -100 : 100);
156 		dht11->humidity = ((hum_int << 8) + hum_dec) * 100;
157 	} else if (temp_dec == 0 && hum_dec == 0) {  /* DHT11 */
158 		dht11->temperature = temp_int * 1000;
159 		dht11->humidity = hum_int * 1000;
160 	} else {
161 		dev_err(dht11->dev,
162 			"Don't know how to decode data: %d %d %d %d\n",
163 			hum_int, hum_dec, temp_int, temp_dec);
164 		return -EIO;
165 	}
166 
167 	return 0;
168 }
169 
170 /*
171  * IRQ handler called on GPIO edges
172  */
173 static irqreturn_t dht11_handle_irq(int irq, void *data)
174 {
175 	struct iio_dev *iio = data;
176 	struct dht11 *dht11 = iio_priv(iio);
177 
178 	/* TODO: Consider making the handler safe for IRQ sharing */
179 	if (dht11->num_edges < DHT11_EDGES_PER_READ && dht11->num_edges >= 0) {
180 		dht11->edges[dht11->num_edges].ts = ktime_get_boot_ns();
181 		dht11->edges[dht11->num_edges++].value =
182 						gpio_get_value(dht11->gpio);
183 
184 		if (dht11->num_edges >= DHT11_EDGES_PER_READ)
185 			complete(&dht11->completion);
186 	}
187 
188 	return IRQ_HANDLED;
189 }
190 
191 static int dht11_read_raw(struct iio_dev *iio_dev,
192 			  const struct iio_chan_spec *chan,
193 			int *val, int *val2, long m)
194 {
195 	struct dht11 *dht11 = iio_priv(iio_dev);
196 	int ret, timeres, offset;
197 
198 	mutex_lock(&dht11->lock);
199 	if (dht11->timestamp + DHT11_DATA_VALID_TIME < ktime_get_boot_ns()) {
200 		timeres = ktime_get_resolution_ns();
201 		dev_dbg(dht11->dev, "current timeresolution: %dns\n", timeres);
202 		if (timeres > DHT11_MIN_TIMERES) {
203 			dev_err(dht11->dev, "timeresolution %dns too low\n",
204 				timeres);
205 			/* In theory a better clock could become available
206 			 * at some point ... and there is no error code
207 			 * that really fits better.
208 			 */
209 			ret = -EAGAIN;
210 			goto err;
211 		}
212 		if (timeres > DHT11_AMBIG_LOW && timeres < DHT11_AMBIG_HIGH)
213 			dev_warn(dht11->dev,
214 				 "timeresolution: %dns - decoding ambiguous\n",
215 				 timeres);
216 
217 		reinit_completion(&dht11->completion);
218 
219 		dht11->num_edges = 0;
220 		ret = gpio_direction_output(dht11->gpio, 0);
221 		if (ret)
222 			goto err;
223 		usleep_range(DHT11_START_TRANSMISSION_MIN,
224 			     DHT11_START_TRANSMISSION_MAX);
225 		ret = gpio_direction_input(dht11->gpio);
226 		if (ret)
227 			goto err;
228 
229 		ret = request_irq(dht11->irq, dht11_handle_irq,
230 				  IRQF_TRIGGER_RISING | IRQF_TRIGGER_FALLING,
231 				  iio_dev->name, iio_dev);
232 		if (ret)
233 			goto err;
234 
235 		ret = wait_for_completion_killable_timeout(&dht11->completion,
236 							   HZ);
237 
238 		free_irq(dht11->irq, iio_dev);
239 
240 #ifdef CONFIG_DYNAMIC_DEBUG
241 		dht11_edges_print(dht11);
242 #endif
243 
244 		if (ret == 0 && dht11->num_edges < DHT11_EDGES_PER_READ - 1) {
245 			dev_err(dht11->dev, "Only %d signal edges detected\n",
246 				dht11->num_edges);
247 			ret = -ETIMEDOUT;
248 		}
249 		if (ret < 0)
250 			goto err;
251 
252 		offset = DHT11_EDGES_PREAMBLE +
253 				dht11->num_edges - DHT11_EDGES_PER_READ;
254 		for (; offset >= 0; --offset) {
255 			ret = dht11_decode(dht11, offset);
256 			if (!ret)
257 				break;
258 		}
259 
260 		if (ret)
261 			goto err;
262 	}
263 
264 	ret = IIO_VAL_INT;
265 	if (chan->type == IIO_TEMP)
266 		*val = dht11->temperature;
267 	else if (chan->type == IIO_HUMIDITYRELATIVE)
268 		*val = dht11->humidity;
269 	else
270 		ret = -EINVAL;
271 err:
272 	dht11->num_edges = -1;
273 	mutex_unlock(&dht11->lock);
274 	return ret;
275 }
276 
277 static const struct iio_info dht11_iio_info = {
278 	.read_raw		= dht11_read_raw,
279 };
280 
281 static const struct iio_chan_spec dht11_chan_spec[] = {
282 	{ .type = IIO_TEMP,
283 		.info_mask_separate = BIT(IIO_CHAN_INFO_PROCESSED), },
284 	{ .type = IIO_HUMIDITYRELATIVE,
285 		.info_mask_separate = BIT(IIO_CHAN_INFO_PROCESSED), }
286 };
287 
288 static const struct of_device_id dht11_dt_ids[] = {
289 	{ .compatible = "dht11", },
290 	{ }
291 };
292 MODULE_DEVICE_TABLE(of, dht11_dt_ids);
293 
294 static int dht11_probe(struct platform_device *pdev)
295 {
296 	struct device *dev = &pdev->dev;
297 	struct device_node *node = dev->of_node;
298 	struct dht11 *dht11;
299 	struct iio_dev *iio;
300 	int ret;
301 
302 	iio = devm_iio_device_alloc(dev, sizeof(*dht11));
303 	if (!iio) {
304 		dev_err(dev, "Failed to allocate IIO device\n");
305 		return -ENOMEM;
306 	}
307 
308 	dht11 = iio_priv(iio);
309 	dht11->dev = dev;
310 
311 	ret = of_get_gpio(node, 0);
312 	if (ret < 0)
313 		return ret;
314 	dht11->gpio = ret;
315 	ret = devm_gpio_request_one(dev, dht11->gpio, GPIOF_IN, pdev->name);
316 	if (ret)
317 		return ret;
318 
319 	dht11->irq = gpio_to_irq(dht11->gpio);
320 	if (dht11->irq < 0) {
321 		dev_err(dev, "GPIO %d has no interrupt\n", dht11->gpio);
322 		return -EINVAL;
323 	}
324 
325 	dht11->timestamp = ktime_get_boot_ns() - DHT11_DATA_VALID_TIME - 1;
326 	dht11->num_edges = -1;
327 
328 	platform_set_drvdata(pdev, iio);
329 
330 	init_completion(&dht11->completion);
331 	mutex_init(&dht11->lock);
332 	iio->name = pdev->name;
333 	iio->dev.parent = &pdev->dev;
334 	iio->info = &dht11_iio_info;
335 	iio->modes = INDIO_DIRECT_MODE;
336 	iio->channels = dht11_chan_spec;
337 	iio->num_channels = ARRAY_SIZE(dht11_chan_spec);
338 
339 	return devm_iio_device_register(dev, iio);
340 }
341 
342 static struct platform_driver dht11_driver = {
343 	.driver = {
344 		.name	= DRIVER_NAME,
345 		.of_match_table = dht11_dt_ids,
346 	},
347 	.probe  = dht11_probe,
348 };
349 
350 module_platform_driver(dht11_driver);
351 
352 MODULE_AUTHOR("Harald Geyer <harald@ccbib.org>");
353 MODULE_DESCRIPTION("DHT11 humidity/temperature sensor driver");
354 MODULE_LICENSE("GPL v2");
355