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