Loggytronic - DHT22 Code
// Arduino DHT-22 Functions v0.9
// Copyright 2015 Chris Tallon (chris@loggytronic.com)
// Licence: GPL version 2

// TO-FIX: negative temperature

const unsigned char pinDHT = 2;

float humidity = 0.0;
float temperature = 0.0;

void setup()
{
  Serial.begin(9600);
}

void loop() // Example loop func. Serial not used within readDHT()
{
  int r = readDHT();

  if (r == 1) Serial.println("H1 failed");
  else if (r == 2) Serial.println("H2 failed");
  else if (r == 3) Serial.println("Read byte 0 failed");
  else if (r == 4) Serial.println("Read byte 1 failed");
  else if (r == 5) Serial.println("Read byte 2 failed");
  else if (r == 6) Serial.println("Read byte 3 failed");
  else if (r == 7) Serial.println("Read byte 4 failed");
  else if (r == 8) Serial.println("Checksum failed");
  else if (r == 9) Serial.println("H3 failed");
  else
  {
    Serial.print(temperature);
    Serial.print(" degC, ");
    Serial.print(humidity);
    Serial.println("%");
  }

  delay(5000);
}

int readDHT()
{
  pinMode(pinDHT, OUTPUT);
  digitalWrite(pinDHT, LOW);
  delay(25);
  digitalWrite(pinDHT, HIGH);
  pinMode(pinDHT, INPUT);

  if (!dhtWaitFor(LOW)) return 1;
  if (!dhtWaitFor(HIGH)) return 2;

  unsigned char b0, b1, b2, b3, b4;
  b0 = b1 = b2 = b3 = b4 = 0;

  if (!dhtReadByte(&b0)) return 3;
  if (!dhtReadByte(&b1)) return 4;
  if (!dhtReadByte(&b2)) return 5;
  if (!dhtReadByte(&b3)) return 6;
  if (!dhtReadByte(&b4)) return 7;

  if (!dhtWaitFor(HIGH)) return 9;
  pinMode(pinDHT, OUTPUT);
  digitalWrite(pinDHT, HIGH);

  if (((b0 + b1 + b2 + b3) & 0xFF) != b4) return 8;

  humidity = (float)((int)((b0 << 8) | b1)) / 10;
  temperature = (float)((int)((b2 << 8) | b3)) / 10;
  return 0;
}

int dhtReadByte(unsigned char* t)
{
  int lastWait = 0;
  for(int i = 0; i < 8; ++i)
  {
    if (!dhtWaitFor(LOW)) return 0; // expecting 50us LOW for start-data-bit
    if (!dhtWaitFor(HIGH)) return 0; // going HIGH for some amount of time

    lastWait = dhtWaitFor(LOW); // lastWait is now 26-28 for 0, 70 for 1
    if (lastWait == 0) return 0;
    if (lastWait > 50) *t = *t | (1 << 7-i);
  }
  return 1;
}

int dhtWaitFor(int level)
{
  unsigned long startMicros = micros();
  if (startMicros > 4294857296) return 0; // within 0.11s of wrapping, error
  while(digitalRead(pinDHT) != level)
  {
    if ((micros() - startMicros) > 100000) return 0;
  }
  return micros() - startMicros;
}

Back to main page
11378 hits since 2/Feb/15