root/drivers/iio/humidity/dht11.c

/* [<][>][^][v][top][bottom][index][help] */

DEFINITIONS

This source file includes following definitions.
  1. dht11_edges_print
  2. dht11_decode_byte
  3. dht11_decode
  4. dht11_handle_irq
  5. dht11_read_raw
  6. dht11_probe

   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         /* TODO: Consider making the handler safe for IRQ sharing */
 178         if (dht11->num_edges < DHT11_EDGES_PER_READ && dht11->num_edges >= 0) {
 179                 dht11->edges[dht11->num_edges].ts = ktime_get_boottime_ns();
 180                 dht11->edges[dht11->num_edges++].value =
 181                                                 gpiod_get_value(dht11->gpiod);
 182 
 183                 if (dht11->num_edges >= DHT11_EDGES_PER_READ)
 184                         complete(&dht11->completion);
 185         }
 186 
 187         return IRQ_HANDLED;
 188 }
 189 
 190 static int dht11_read_raw(struct iio_dev *iio_dev,
 191                           const struct iio_chan_spec *chan,
 192                         int *val, int *val2, long m)
 193 {
 194         struct dht11 *dht11 = iio_priv(iio_dev);
 195         int ret, timeres, offset;
 196 
 197         mutex_lock(&dht11->lock);
 198         if (dht11->timestamp + DHT11_DATA_VALID_TIME < ktime_get_boottime_ns()) {
 199                 timeres = ktime_get_resolution_ns();
 200                 dev_dbg(dht11->dev, "current timeresolution: %dns\n", timeres);
 201                 if (timeres > DHT11_MIN_TIMERES) {
 202                         dev_err(dht11->dev, "timeresolution %dns too low\n",
 203                                 timeres);
 204                         /* In theory a better clock could become available
 205                          * at some point ... and there is no error code
 206                          * that really fits better.
 207                          */
 208                         ret = -EAGAIN;
 209                         goto err;
 210                 }
 211                 if (timeres > DHT11_AMBIG_LOW && timeres < DHT11_AMBIG_HIGH)
 212                         dev_warn(dht11->dev,
 213                                  "timeresolution: %dns - decoding ambiguous\n",
 214                                  timeres);
 215 
 216                 reinit_completion(&dht11->completion);
 217 
 218                 dht11->num_edges = 0;
 219                 ret = gpiod_direction_output(dht11->gpiod, 0);
 220                 if (ret)
 221                         goto err;
 222                 usleep_range(DHT11_START_TRANSMISSION_MIN,
 223                              DHT11_START_TRANSMISSION_MAX);
 224                 ret = gpiod_direction_input(dht11->gpiod);
 225                 if (ret)
 226                         goto err;
 227 
 228                 ret = request_irq(dht11->irq, dht11_handle_irq,
 229                                   IRQF_TRIGGER_RISING | IRQF_TRIGGER_FALLING,
 230                                   iio_dev->name, iio_dev);
 231                 if (ret)
 232                         goto err;
 233 
 234                 ret = wait_for_completion_killable_timeout(&dht11->completion,
 235                                                            HZ);
 236 
 237                 free_irq(dht11->irq, iio_dev);
 238 
 239 #ifdef CONFIG_DYNAMIC_DEBUG
 240                 dht11_edges_print(dht11);
 241 #endif
 242 
 243                 if (ret == 0 && dht11->num_edges < DHT11_EDGES_PER_READ - 1) {
 244                         dev_err(dht11->dev, "Only %d signal edges detected\n",
 245                                 dht11->num_edges);
 246                         ret = -ETIMEDOUT;
 247                 }
 248                 if (ret < 0)
 249                         goto err;
 250 
 251                 offset = DHT11_EDGES_PREAMBLE +
 252                                 dht11->num_edges - DHT11_EDGES_PER_READ;
 253                 for (; offset >= 0; --offset) {
 254                         ret = dht11_decode(dht11, offset);
 255                         if (!ret)
 256                                 break;
 257                 }
 258 
 259                 if (ret)
 260                         goto err;
 261         }
 262 
 263         ret = IIO_VAL_INT;
 264         if (chan->type == IIO_TEMP)
 265                 *val = dht11->temperature;
 266         else if (chan->type == IIO_HUMIDITYRELATIVE)
 267                 *val = dht11->humidity;
 268         else
 269                 ret = -EINVAL;
 270 err:
 271         dht11->num_edges = -1;
 272         mutex_unlock(&dht11->lock);
 273         return ret;
 274 }
 275 
 276 static const struct iio_info dht11_iio_info = {
 277         .read_raw               = dht11_read_raw,
 278 };
 279 
 280 static const struct iio_chan_spec dht11_chan_spec[] = {
 281         { .type = IIO_TEMP,
 282                 .info_mask_separate = BIT(IIO_CHAN_INFO_PROCESSED), },
 283         { .type = IIO_HUMIDITYRELATIVE,
 284                 .info_mask_separate = BIT(IIO_CHAN_INFO_PROCESSED), }
 285 };
 286 
 287 static const struct of_device_id dht11_dt_ids[] = {
 288         { .compatible = "dht11", },
 289         { }
 290 };
 291 MODULE_DEVICE_TABLE(of, dht11_dt_ids);
 292 
 293 static int dht11_probe(struct platform_device *pdev)
 294 {
 295         struct device *dev = &pdev->dev;
 296         struct dht11 *dht11;
 297         struct iio_dev *iio;
 298 
 299         iio = devm_iio_device_alloc(dev, sizeof(*dht11));
 300         if (!iio) {
 301                 dev_err(dev, "Failed to allocate IIO device\n");
 302                 return -ENOMEM;
 303         }
 304 
 305         dht11 = iio_priv(iio);
 306         dht11->dev = dev;
 307         dht11->gpiod = devm_gpiod_get(dev, NULL, GPIOD_IN);
 308         if (IS_ERR(dht11->gpiod))
 309                 return PTR_ERR(dht11->gpiod);
 310 
 311         dht11->irq = gpiod_to_irq(dht11->gpiod);
 312         if (dht11->irq < 0) {
 313                 dev_err(dev, "GPIO %d has no interrupt\n", desc_to_gpio(dht11->gpiod));
 314                 return -EINVAL;
 315         }
 316 
 317         dht11->timestamp = ktime_get_boottime_ns() - DHT11_DATA_VALID_TIME - 1;
 318         dht11->num_edges = -1;
 319 
 320         platform_set_drvdata(pdev, iio);
 321 
 322         init_completion(&dht11->completion);
 323         mutex_init(&dht11->lock);
 324         iio->name = pdev->name;
 325         iio->dev.parent = &pdev->dev;
 326         iio->info = &dht11_iio_info;
 327         iio->modes = INDIO_DIRECT_MODE;
 328         iio->channels = dht11_chan_spec;
 329         iio->num_channels = ARRAY_SIZE(dht11_chan_spec);
 330 
 331         return devm_iio_device_register(dev, iio);
 332 }
 333 
 334 static struct platform_driver dht11_driver = {
 335         .driver = {
 336                 .name   = DRIVER_NAME,
 337                 .of_match_table = dht11_dt_ids,
 338         },
 339         .probe  = dht11_probe,
 340 };
 341 
 342 module_platform_driver(dht11_driver);
 343 
 344 MODULE_AUTHOR("Harald Geyer <harald@ccbib.org>");
 345 MODULE_DESCRIPTION("DHT11 humidity/temperature sensor driver");
 346 MODULE_LICENSE("GPL v2");

/* [<][>][^][v][top][bottom][index][help] */