1 // SPDX-License-Identifier: GPL-2.0-or-later
3 * DHT11/DHT22 bit banging GPIO driver
5 * Copyright (c) Harald Geyer <harald@ccbib.org>
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>
15 #include <linux/of_device.h>
16 #include <linux/sysfs.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>
29 #include <linux/iio/iio.h>
31 #define DRIVER_NAME "dht11"
33 #define DHT11_DATA_VALID_TIME 2000000000 /* 2s in ns */
35 #define DHT11_EDGES_PREAMBLE 2
36 #define DHT11_BITS_PER_READ 40
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:
41 #define DHT11_EDGES_PER_READ (2 * DHT11_BITS_PER_READ + \
42 DHT11_EDGES_PREAMBLE + 1)
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.
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
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
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 */
78 struct completion completion;
79 /* The iio sysfs interface doesn't prevent concurrent reads: */
86 /* num_edges: -1 means "no transmission in progress" */
88 struct {s64 ts; int value; } edges[DHT11_EDGES_PER_READ];
91 #ifdef CONFIG_DYNAMIC_DEBUG
93 * dht11_edges_print: show the data as actually received by the
96 static void dht11_edges_print(struct dht11 *dht11)
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");
107 #endif /* CONFIG_DYNAMIC_DEBUG */
109 static unsigned char dht11_decode_byte(char *bits)
111 unsigned char ret = 0;
114 for (i = 0; i < 8; ++i) {
123 static int dht11_decode(struct dht11 *dht11, int offset)
126 char bits[DHT11_BITS_PER_READ];
127 unsigned char temp_int, temp_dec, hum_int, hum_dec, checksum;
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) {
134 "lost synchronisation at edge %d\n",
138 bits[i] = t > DHT11_THRESHOLD;
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]);
147 if (((hum_int + hum_dec + temp_int + temp_dec) & 0xff) != checksum) {
148 dev_dbg(dht11->dev, "invalid checksum\n");
152 dht11->timestamp = ktime_get_boottime_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;
162 "Don't know how to decode data: %d %d %d %d\n",
163 hum_int, hum_dec, temp_int, temp_dec);
171 * IRQ handler called on GPIO edges
173 static irqreturn_t dht11_handle_irq(int irq, void *data)
175 struct iio_dev *iio = data;
176 struct dht11 *dht11 = iio_priv(iio);
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_boottime_ns();
181 dht11->edges[dht11->num_edges++].value =
182 gpio_get_value(dht11->gpio);
184 if (dht11->num_edges >= DHT11_EDGES_PER_READ)
185 complete(&dht11->completion);
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)
195 struct dht11 *dht11 = iio_priv(iio_dev);
196 int ret, timeres, offset;
198 mutex_lock(&dht11->lock);
199 if (dht11->timestamp + DHT11_DATA_VALID_TIME < ktime_get_boottime_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",
205 /* In theory a better clock could become available
206 * at some point ... and there is no error code
207 * that really fits better.
212 if (timeres > DHT11_AMBIG_LOW && timeres < DHT11_AMBIG_HIGH)
214 "timeresolution: %dns - decoding ambiguous\n",
217 reinit_completion(&dht11->completion);
219 dht11->num_edges = 0;
220 ret = gpio_direction_output(dht11->gpio, 0);
223 usleep_range(DHT11_START_TRANSMISSION_MIN,
224 DHT11_START_TRANSMISSION_MAX);
225 ret = gpio_direction_input(dht11->gpio);
229 ret = request_irq(dht11->irq, dht11_handle_irq,
230 IRQF_TRIGGER_RISING | IRQF_TRIGGER_FALLING,
231 iio_dev->name, iio_dev);
235 ret = wait_for_completion_killable_timeout(&dht11->completion,
238 free_irq(dht11->irq, iio_dev);
240 #ifdef CONFIG_DYNAMIC_DEBUG
241 dht11_edges_print(dht11);
244 if (ret == 0 && dht11->num_edges < DHT11_EDGES_PER_READ - 1) {
245 dev_err(dht11->dev, "Only %d signal edges detected\n",
252 offset = DHT11_EDGES_PREAMBLE +
253 dht11->num_edges - DHT11_EDGES_PER_READ;
254 for (; offset >= 0; --offset) {
255 ret = dht11_decode(dht11, offset);
265 if (chan->type == IIO_TEMP)
266 *val = dht11->temperature;
267 else if (chan->type == IIO_HUMIDITYRELATIVE)
268 *val = dht11->humidity;
272 dht11->num_edges = -1;
273 mutex_unlock(&dht11->lock);
277 static const struct iio_info dht11_iio_info = {
278 .read_raw = dht11_read_raw,
281 static const struct iio_chan_spec dht11_chan_spec[] = {
283 .info_mask_separate = BIT(IIO_CHAN_INFO_PROCESSED), },
284 { .type = IIO_HUMIDITYRELATIVE,
285 .info_mask_separate = BIT(IIO_CHAN_INFO_PROCESSED), }
288 static const struct of_device_id dht11_dt_ids[] = {
289 { .compatible = "dht11", },
292 MODULE_DEVICE_TABLE(of, dht11_dt_ids);
294 static int dht11_probe(struct platform_device *pdev)
296 struct device *dev = &pdev->dev;
297 struct device_node *node = dev->of_node;
302 iio = devm_iio_device_alloc(dev, sizeof(*dht11));
304 dev_err(dev, "Failed to allocate IIO device\n");
308 dht11 = iio_priv(iio);
311 ret = of_get_gpio(node, 0);
315 ret = devm_gpio_request_one(dev, dht11->gpio, GPIOF_IN, pdev->name);
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);
325 dht11->timestamp = ktime_get_boottime_ns() - DHT11_DATA_VALID_TIME - 1;
326 dht11->num_edges = -1;
328 platform_set_drvdata(pdev, iio);
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);
339 return devm_iio_device_register(dev, iio);
342 static struct platform_driver dht11_driver = {
345 .of_match_table = dht11_dt_ids,
347 .probe = dht11_probe,
350 module_platform_driver(dht11_driver);
352 MODULE_AUTHOR("Harald Geyer <harald@ccbib.org>");
353 MODULE_DESCRIPTION("DHT11 humidity/temperature sensor driver");
354 MODULE_LICENSE("GPL v2");