• Thanks! It looks good... if you wanted, you could try formatting it like a module, and then we could add it so others can do var d = require("DHT11").connect(A0); d.read(callback). There's some info on that here.

    I've quickly hacked it up but haven't tested so it's almost certainly buggy I'm afraid :)

    The only strange bit is having to set var dht=this; because when you're in a timeout, this is set to something else.

    function DHT11(pin) {
      this.pin = pin;
    }
    
    DHT11.prototype.read = function (a) {
        this.onreadf=a;
        this.i=0;
        this.out=0;
        this.badbits=0;
        digitalPulse(this.pin,1,0.08);
        var dht = this;
        setTimeout(function() {pinMode(dht.pin,'input_pullup');dht.watch=setWatch(function(t) {dht.onwatch(t);},dht.pin,{repeat:true});},0.07);
        setTimeout(function() {dht.onread(dht.endRead());},50);
    };
    DHT11.prototype.onread= function(d) {
        if (d.temp==-1) {
            dht.read(dht.onreadf);
        } else {
            dht.onreadf(d);
        }
    };
    DHT11.prototype.onwatch = function(t) {
        if (t.state) {
            this.pstart=t.time;
        } else {
            var tt=t.time-pstart;
            if (tt < 0.000044) {
                this.badbits = 1;
            }
            if (this.badbits) {
                this.out=(this.out<<1) | ((tt > 0.000044) && (tt < 0.0001));
            }
            this.i++;
        }
    };
    DHT11.prototype.endRead = function() {
        clearWatch(this.watch);
        if (this.badbits && this.i > 32) {
            rh=(this.out>>(this.i-10))&0xFF;
            temp=(this.out>>(this.i-26))&0xFF;
            return {"temp":temp,"rh":rh};
        } else {
            return {temp:-1,rh:-1};
        }
    };
    
    var d = new DHT11(C6);
    d.read(function(a) { print(a); });
    

    Looking at it, if it's not vital that you get exactly a 0.08ms pulse, I'd consider just writing:

    pinMode(dht.pin,'output');
    digitalWrite(dht.pin, 1);
    setTimeout(function() {
      pinMode(dht.pin,'input_pullup');
      ...
    }, 0.1);
    

    I'm not sure if that does quite what you want - but it's not guaranteed that the setTimeout will happen at exactly the same time as the digitalPulse ends (because another task might jump in there first)

About

Avatar for Gordon @Gordon started