dht11.c 8.9 KB

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