#include "dht11.h" #include #include #include #include "defines.h" int dht11_humidity; int dht11_temperature; int dht11_read(){ // Init Timer1 for timekeeping TIMSK1=0; // no interrupt TCNT1 = 0; // start at 0 TCCR1A = 0; // nothing to do w timer TCCR1B = _BV(CS11); // start w 1us tick // BUFFER TO RECEIVE uint8_t bits[5]; uint8_t cnt = 7; uint8_t idx = 0; // EMPTY BUFFER for (int i=0; i< 5; i++) bits[i] = 0; // REQUEST SAMPLE bitSet(DHT11_DDDR,DHT11_DBIT); //pinMode(pin, OUTPUT); bitSet(DHT11_DPORT,DHT11_DBIT); // digitalWrite(pin, HIGH); _delay_ms(30); bitClear(DHT11_DPORT,DHT11_DBIT); //digitalWrite(pin, LOW); _delay_ms(18); bitSet(DHT11_DPORT,DHT11_DBIT); // digitalWrite(pin, HIGH); _delay_us(20); bitClear(DHT11_DDDR,DHT11_DBIT); //pinMode(pin, INPUT); bitSet(DHT11_DPORT,DHT11_DBIT); // ACKNOWLEDGE or TIMEOUT unsigned int loopCnt = 10000; while( bitRead(DHT11_DPIN,DHT11_DBIT) == LOW) if (loopCnt-- == 0) return DHT11_ERROR_TIMEOUT2; loopCnt = 10000; while( bitRead(DHT11_DPIN,DHT11_DBIT) == HIGH) if (loopCnt-- == 0) return DHT11_ERROR_TIMEOUT2; // READ OUTPUT - 40 BITS => 5 BYTES or TIMEOUT for (int i=0; i<40; i++) { loopCnt = 10000; while(bitRead(DHT11_DPIN,DHT11_DBIT) == LOW) if (loopCnt-- == 0) return DHT11_ERROR_TIMEOUT; unsigned long t = TCNT1; loopCnt = 10000; while(bitRead(DHT11_DPIN,DHT11_DBIT) == HIGH) if (loopCnt-- == 0) return DHT11_ERROR_TIMEOUT; unsigned long t2 = TCNT1; if ((t2 - t) > 40) bits[idx] |= (1 << cnt); if (cnt == 0) // next byte? { cnt = 7; // restart at MSB idx++; // next byte! } else cnt--; } // WRITE TO RIGHT VARS // as bits[1] and bits[3] are allways zero they are omitted in formulas. dht11_humidity = bits[0]; dht11_temperature = bits[2]; uint8_t sum = bits[0] + bits[2]; if (bits[4] != sum) return DHT11_ERROR_CHECKSUM; return DHT11_OK; }