Example Code for Arduino-Temperature and Humidity Testing

Last revision 2025/12/20

This article offers a comprehensive guide on using Arduino with a DHT22 sensor for measuring temperature and humidity. It includes software preparation, a wiring diagram, and sample code to ensure accurate sensor readings, providing a practical resource for electronics enthusiasts.

Software Preparation

Please download the Library of DHT22 at first.

Wiring Diagram

connection

Sample Code


    #include <dht.h>

    dht DHT;
    #define DHT22_PIN 7

    void setup()
    {
      Serial.begin(115200);
      Serial.println("DHT TEST PROGRAM ");
      Serial.print("LIBRARY VERSION: ");
      Serial.println(DHT_LIB_VERSION);
      Serial.println();
      Serial.println("Type,\tstatus,\tHumidity (%),\tTemperature (C)");
    }

    void loop()
    {
      Serial.print("DHT22, \t");
      int chk = DHT.read22(DHT22_PIN);  //读取数据
      switch (chk)
      {
        case DHTLIB_OK:
                    Serial.print("OK,\t");
                    break;
        case DHTLIB_ERROR_CHECKSUM:
                    Serial.print("Checksum error,\t");
                    break;
        case DHTLIB_ERROR_TIMEOUT:
                    Serial.print("Time out error,\t");
                    break;
        default:
                    Serial.print("Unknown error,\t");
                    break;
      }

      Serial.print(DHT.humidity, 1);
      Serial.print(",\t");
      Serial.println(DHT.temperature, 1);

      delay(1000);
    }

Was this article helpful?

TOP