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