You are reading a single comment by @Jurand and its replies. Click here to read the full conversation.
  • You can embed the module in your code like this (and there is no need for require anymore):

    function DHT22(pin) {
      this.pin = pin;
    }
    
    DHT22.prototype.read = function (cb, n) {
      if (!n) n = 10;
      var d = '';
      var ht = this;
      digitalWrite(ht.pin, 0);
      pinMode(ht.pin, 'output');
      this.watch = setWatch(
        function (t) {
          d += 0 | (t.time - t.lastTime > 0.00005);
        },
        ht.pin,
        { edge: 'falling', repeat: true }
      );
      setTimeout(function () {
        pinMode(ht.pin, 'input_pullup');
        pinMode(ht.pin);
      }, 1);
      setTimeout(function () {
        if (ht.watch) {
          ht.watch = clearWatch(ht.watch);
        }
        var cks =
          parseInt(d.substr(2, 8), 2) +
          parseInt(d.substr(10, 8), 2) +
          parseInt(d.substr(18, 8), 2) +
          parseInt(d.substr(26, 8), 2);
        if (cks && (cks & 0xff) == parseInt(d.substr(34, 8), 2)) {
          cb({
            raw: d,
            rh: parseInt(d.substr(2, 16), 2) * 0.1,
            temp: parseInt(d.substr(19, 15), 2) * 0.2 * (0.5 - d[18]),
          });
        } else {
          if (n > 1)
            setTimeout(function () {
              ht.read(cb, --n);
            }, 500);
          else cb({ err: true, checksumError: cks > 0, raw: d, temp: -1, rh: -1 });
        }
      }, 50);
    };
    
    const dht22 = new DHT22(NodeMCU.D5);
    
    const readDHT22Sensor = () => {
      digitalWrite(D2, false);
      dht22.read(e => {
        console.log(
          '[DHT22 sensor]  ' +
            new Date().toString() +
            ' temperature: ' +
            e.temp.toString() +
            '°C, humidity: ' +
            e.rh.toString() +
            '%'
        );
        digitalWrite(D2, true);
      });
    };
    
    readDHT22Sensor();
    setInterval(() => readDHT22Sensor(), 1000);
    
About

Avatar for Jurand @Jurand started