dht11.c 9.6 KB

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