Arduino reads temperature and humidity data from DHT11, DHT22, SHTC3

This article explains how to read data from three temperature and humidity sensors—DHT11, DHT22, and SHTC3—using a NodeMCU board and send the data to the serial port. For each sensor, I have provided examples both with and without third-party libraries.

ESP8266 Development Environment Setup Guide: https://blog.zeruns.com/archives/526.html

Purchase links for the sensors used in this article can be found at the bottom of the article.

DHT11

The DHT11 is a temperature and humidity sensor with a calibrated digital signal output. Its accuracy is ±5% RH for humidity and ±2°C for temperature, with a measurement range of 20–90% RH for humidity and 0–50°C for temperature. It has low accuracy but is very inexpensive. The DHT11 uses a single-wire communication protocol and operates on a supply voltage of 3.3–5V.

Using the DHT Library

Use the DHT sensor library (must be installed manually; installation instructions are provided in the ESP8266 Development Environment Setup Guide above) to directly read data from the DHT11.

#include ``````c
#include <DHT.h>        // Include the DHT library

DHT dht(D1, DHT11);      // Set the data pin connected to IO and sensor type

void setup(){ // Initialization function, runs only once at program start
  Serial.begin(115200);   // Set serial baud rate
  dht.begin();       
}

// https://blog.zeruns.com
void loop() {
  delay(1000);                  // Delay 1000 milliseconds
  float RH = dht.readHumidity();   // Read humidity data
  float T = dht.readTemperature(); // Read temperature data
  Serial.print("Humidity:");  // Print "Humidity:" to serial
  Serial.print(RH);           // Print humidity data
  Serial.print("%");
  Serial.print("  Temperature:");
  Serial.print(T);            // Print temperature data
  Serial.println("C"); 
  Serial.println("https://blog.zeruns.com");
}

Without Using a Library

Write a program to read data directly by referring to the DHT11 datasheet.

DHT11 Datasheet: http://go.zeruns.com/G

#define data D1   // Connect DHT11's Data pin (Pin 2) to NodeMCU's D1 pin

unsigned char i;  // Unsigned 8-bit integer variable
float RH,T;       // Single-precision floating-point (32-bit)
byte RH_H,RH_L,T_H,T_L,sum,check;  // Byte variables, binary numbers

void setup() {    // Initialization function, runs only once at program start
  Serial.begin(115200);   // Set serial baud rate
}

void loop() {     // Loop function, runs continuously after initialization
  delay(1000);    // Delay 1000 milliseconds
  DHT11();        // Get temperature and humidity data
  Serial.print("Humidity:");  // Print "Humidity:" to serial
  Serial.print(RH);           // Print humidity data
  Serial.print("%");
  Serial.print("  Temperature:");
  Serial.print(T);            // Print temperature data
  Serial.println("C"); 
  Serial.println("https://blog.zeruns.com");
}

void DHT11()
{
  RH_H=0,RH_L=0,T_H=0,T_L=0,sum=0,check=0;
  pinMode(data,OUTPUT);   // Set IO pin to output mode
  digitalWrite(data,1);   // Set IO pin to high level
  delay(10);              // Delay 10 milliseconds
  digitalWrite(data,0);   // Set IO pin to low level
  delay(25);              // Delay 25 milliseconds
  digitalWrite(data,1);   // Set IO pin to high level
  pinMode(data,INPUT);    // Set IO pin to input mode
  delayMicroseconds(30);  // Delay 30 microseconds
  if(!digitalRead(data))  // Check if IO pin input is low level
  {//https://blog.zeruns.com
    while(!digitalRead(data));  // Wait until input becomes high
    while(digitalRead(data));   // Wait until input becomes low
    for(i=0;i<8;i++)            // Loop 8 times
    {   
      while(!digitalRead(data));// Wait until input becomes high   
      delayMicroseconds(28);    // Delay 28 microseconds
      if(digitalRead(data)){    // Check if IO pin input is high
        bitWrite(RH_H, 7-i, 1); // Write 1 to bit (7-i) of RH_H (counting from right)
        while(digitalRead(data));
      }
    }
    for(i=0;i<8;i++)
    {
      while(!digitalRead(data));
      delayMicroseconds(28);
      if(digitalRead(data)){
        bitWrite(RH_L, 7-i, 1);
        while(digitalRead(data));
      }
    }
    for(i=0;i<8;i++)
    {
      while(!digitalRead(data));
      delayMicroseconds(28);
      if(digitalRead(data)){  
        bitWrite(T_H, 7-i, 1);
        while(digitalRead(data));
      }
    }
    for(i=0;i<8;i++)
    {
      while(!digitalRead(data));
      delayMicroseconds(28);
      if(digitalRead(data)){  
        bitWrite(T_L, 7-i, 1);
        while(digitalRead(data));
      }
    }
    for(i=0;i<8;i++)
    {
      while(!digitalRead(data));
      delayMicroseconds(28);
      if(digitalRead(data)){  
        bitWrite(check, 7-i, 1);
        while(digitalRead(data));
      }
    }
   }
  sum=RH_H + RH_L + T_H + T_L;
  byte sum_temp=0;
  // Read the last 8 bits of sum into sum_temp
  for(i=0;i<8;i++){
    bitWrite(sum_temp,i,bitRead(sum,i)); 
  }//https://blog.zeruns.com
  if(check==sum_temp){  // Validate data
    RH=RH_H+float(RH_L)/10;
    T=T_H+float(T_L)/10;
  }
}

Screenshot

DHT22 (AM2302)

The DHT22 (AM2302) is a temperature and humidity sensor with calibrated digital output. It has a humidity accuracy of ±2% RH and temperature accuracy of ±0.5°C, with a measurement range of 0–100% RH for humidity and -40 to 80°C for temperature. Resolution is 0.1 for both. Higher accuracy and affordable price. DHT22 uses a single-wire communication protocol. Operating voltage: 3.3–5V.

Using the DHT Library

Use the DHT sensor library to directly read DHT22 data.

#include <DHT.h>        // Include the DHT library

DHT dht(D1, DHT22);      // Set the data pin connected to IO and sensor type

void setup(){ // Initialization function, runs only once at program start
  Serial.begin(115200);   // Set serial baud rate
  dht.begin();       
}

// https://blog.zeruns.com
void loop() {
  delay(1000);                  // Delay 1000 milliseconds
  float RH = dht.readHumidity();   // Read humidity data
  float T = dht.readTemperature(); // Read temperature data
  Serial.print("Humidity:");  // Print "Humidity:" to serial
  Serial.print(RH);           // Print humidity data
  Serial.print("%");
  Serial.print("  Temperature:");
  Serial.print(T);            // Print temperature data
  Serial.println("C"); 
  Serial.println("https://blog.zeruns.com");
}

Without Using a Library

Write a program to read data directly by referring to the DHT22 datasheet.

DHT22 Datasheet: http://go.zeruns.com/H

#define data D1   // Connect DHT22's Data pin (Pin 2) to NodeMCU's D1 pin

unsigned char i;  // Unsigned 8-bit integer variable
float RH,T;       // Single-precision floating-point (32-bit)
byte RH_H,RH_L,T_H,T_L,sum,check;  // Byte variables, binary numbers

void setup() {    // Initialization function, runs only once at program start
  Serial.begin(115200);   // Set serial baud rate
}

void loop() {     // Loop function, runs continuously after initialization
  delay(1000);    // Delay 1000 milliseconds
  DHT11();        // Get temperature and humidity data
  Serial.print("Humidity:");  // Print "Humidity:" to serial
  Serial.print(RH);           // Print humidity data
  Serial.print("%");
  Serial.print("  Temperature:");
  Serial.print(T);            // Print temperature data
  Serial.println("C"); 
  Serial.println("https://blog.zeruns.com");
}

void DHT11()
{
  RH_H=0,RH_L=0,T_H=0,T_L=0,sum=0,check=0;
  pinMode(data,OUTPUT);   // Set IO pin to output mode
  digitalWrite(data,1);   // Set IO pin to high level
  delay(10);              // Delay 10 milliseconds
  digitalWrite(data,0);   // Set IO pin to low level
  delay(25);              // Delay 25 milliseconds
  digitalWrite(data,1);   // Set IO pin to high level
  pinMode(data,INPUT);    // Set IO pin to input mode
  delayMicroseconds(30);  // Delay 30 microseconds
  if(!digitalRead(data))  // Check if IO pin input is low level
  {//https://blog.zeruns.com
    while(!digitalRead(data));  // Wait until input becomes high
    while(digitalRead(data));   // Wait until input becomes low
    for(i=0;i<8;i++)            // Loop 8 times
    {   
      while(!digitalRead(data));// Wait until input becomes high   
      delayMicroseconds(28);    // Delay 28 microseconds
      if(digitalRead(data)){    // Check if IO pin input is high
        bitWrite(RH_H, 7-i, 1); // Write 1 to bit (7-i) of RH_H (counting from right)
        while(digitalRead(data));
      }
    }
    for(i=0;i<8;i++)
    {
      while(!digitalRead(data));
      delayMicroseconds(28);
      if(digitalRead(data)){
        bitWrite(RH_L, 7-i, 1);
        while(digitalRead(data));
      }
    }
    for(i=0;i<8;i++)
    {
      while(!digitalRead(data));
      delayMicroseconds(28);
      if(digitalRead(data)){  
        bitWrite(T_H, 7-i, 1);
        while(digitalRead(data));
      }
    }
    for(i=0;i<8;i++)
    {
      while(!digitalRead(data));
      delayMicroseconds(28);
      if(digitalRead(data)){  
        bitWrite(T_L, 7-i, 1);
        while(digitalRead(data));
      }
    }
    for(i=0;i<8;i++)
    {
      while(!digitalRead(data));
      delayMicroseconds(28);
      if(digitalRead(data)){  
        bitWrite(check, 7-i, 1);
        while(digitalRead(data));
      }
    }
   }
  sum=RH_H + RH_L + T_H + T_L;
  byte sum_temp=0;
  // Read the last 8 bits of sum into sum_temp
  for(i=0;i<8;i++){
    bitWrite(sum_temp,i,bitRead(sum,i)); 
  }//https://blog.zeruns.com
  if(check==sum_temp){
    if(bitRead(RH_H,7)==1){ // Check if temperature is negative
      T=-(float(T_H<<8)+float(T_L))/10;
    }else{
      T=(float(T_H<<8)+float(T_L))/10;
    }
    RH=(float(RH_H<<8)+float(RH_L))/10;
  }  
}

Screenshot

SHTC3

The SHTC3 is a calibrated digital temperature and humidity sensor. It offers humidity accuracy of ±2% RH and temperature accuracy of ±0.2°C, with a measurement range of 0–100% RH for humidity and -40 to 125°C for temperature. Resolution is 0.01 for both. High precision and relatively low cost, but limited documentation available. SHTC3 uses I2C (IIC) communication. Operating voltage: 1.62–3.6V.

SHTC3 Datasheet: http://go.zeruns.com/I

Using the Wire (I2C) Library

Use the Wire library to communicate with and read data from the SHTC3.

/* https://blog.zeruns.com
 * Connection Method
 * SHTC3    Development Board
 * SCL      SCL (NodeMcu development board uses D1)
 * SDA      SDA (NodeMcu development board uses D2)
 */
#include <Wire.h>

#define SHTC3_ADDRESS 0x70  // Define the I2C device address of SHTC3 as 0x70
float T,RH;

void setup() {    // Initialization function, runs only once at the start of the program
  Serial.begin(115200);   // Set serial baud rate
  Wire.begin();   // Initialize as I2C master
}

void loop() {     // Loop function, continuously runs after initialization
  delay(1000);    // Delay 1000 milliseconds
  SHTC3();        // Get temperature and humidity data
  Serial.print("Humidity:");  // Print "Humidity:" to serial
  Serial.print(RH);           // Print humidity data to serial
  Serial.print("%");
  Serial.print("  Temperature:");
  Serial.print(T);            // Print temperature data to serial
  Serial.println("C"); 
  Serial.println("https://blog.zeruns.com");
}

void SHTC3(){   // Get temperature and humidity data
  Wire.beginTransmission(SHTC3_ADDRESS); // Start transmission to I2C slave device at address 0x70.
  Wire.write(byte(0xE0));       // Send write command
  Wire.endTransmission();       // Stop transmission to slave
  Wire.beginTransmission(SHTC3_ADDRESS);
  Wire.write(byte(0x35));       // Send high byte of wake-up command
  Wire.write(byte(0x17));       // Send low byte of wake-up command
  Wire.endTransmission();
  delayMicroseconds(300);       // Delay 300 microseconds
  Wire.beginTransmission(SHTC3_ADDRESS);
  Wire.write(byte(0xE0));
  Wire.endTransmission();
  Wire.beginTransmission(SHTC3_ADDRESS);
  Wire.write(byte(0x7C));       // Send high byte of measurement command
  Wire.write(byte(0xA2));       // Send low byte of measurement command
  Wire.endTransmission();
  Wire.beginTransmission(SHTC3_ADDRESS);
  Wire.write(byte(0xE1));       // Send read command
  Wire.endTransmission();
  Wire.requestFrom(SHTC3_ADDRESS,6);     // Request data from slave
  uint16_t T_temp,RH_temp,T_CRC,RH_CRC;
  if (2 <= Wire.available()) {
    T_temp = Wire.read();     // Receive high byte of temperature
    T_temp = T_temp << 8;     // Left shift by 8 bits
    T_temp |= Wire.read();    // Bitwise OR of shifted high byte and received low byte
    T_CRC = Wire.read();      // Receive CRC checksum
    if(SHTC3_CRC_CHECK(T_temp,T_CRC)){  // Validate data
      T =float(T_temp) * 175 / 65536 - 45;  // Calculate temperature
    }
  }//https://blog.zeruns.com
  if (2 <= Wire.available()) {
    RH_temp = Wire.read();     // Receive high byte of humidity
    RH_temp = RH_temp << 8;     // Left shift by 8 bits
    RH_temp |= Wire.read();    // Bitwise OR of shifted high byte and received low byte
    RH_CRC = Wire.read();
    if(SHTC3_CRC_CHECK(RH_temp,RH_CRC)){
      RH =float(RH_temp) * 100 / 65536;
    }
  }
}
//https://blog.zeruns.com
uint8_t SHTC3_CRC_CHECK(uint16_t DAT,uint8_t CRC_DAT) // SHTC3 CRC check
{
    uint8_t i,t,temp;
    uint8_t CRC_BYTE;  
    CRC_BYTE = 0xFF;  
    temp = (DAT>>8) & 0xFF;  
    for(t = 0;t < 2;t ++)
    {
        CRC_BYTE ^= temp;
        for(i = 0;i < 8;i ++)
        {
            if(CRC_BYTE & 0x80)
            {
                CRC_BYTE <<= 1;         
                CRC_BYTE ^= 0x31;  
            }else{
                CRC_BYTE <<= 1;  
            }
        }  
        if(t == 0)
        {
            temp = DAT & 0xFF; 
        }
    }//https://blog.zeruns.com  
    if(CRC_BYTE == CRC_DAT)
    {
        temp = 1;  
    }else{
        temp = 0;  
    }   
    return temp;
}

### Using the SHTC3 Library

First, install the `SparkFun SHTC3` library.

```c
/* https://blog.zeruns.com
 * Connection Method
 * SHTC3    Development Board
 * SCL      SCL (NodeMcu development board uses D1)
 * SDA      SDA (NodeMcu development board uses D2)
 */

#include <SparkFun_SHTC3.h>

SHTC3 mySHTC3;

void setup(){ // Initialization function, runs only once at the start of the program
  Serial.begin(115200);   // Set serial baud rate
  while(Serial == false){};   // Wait for serial connection to start
  Wire.begin();           // Initialize Wire (I2C) library
  unsigned char i=0;
  errorDecoder(mySHTC3.begin());// To start the sensor you must call "begin()", the default settings use Wire (default Arduino I2C port)
}
//https://blog.zeruns.com
void loop() {
  float RH,T;
  delay(1000);                  // Delay 1000 milliseconds
  SHTC3_Status_TypeDef result = mySHTC3.update();
  if(mySHTC3.lastStatus == SHTC3_Status_Nominal)   // Check if SHTC3 status is normal
  {
    RH = mySHTC3.toPercent();   // Read humidity data                
    T = mySHTC3.toDegC();       // Read temperature data             
  }else{
    Serial.print("Update failed, error: ");
    errorDecoder(mySHTC3.lastStatus); // Output error reason
    Serial.println();
  }
  Serial.print("Humidity:");  // Print "Humidity:" to serial
  Serial.print(RH);           // Print humidity data to serial
  Serial.print("%");
  Serial.print("  Temperature:");
  Serial.print(T);            // Print temperature data to serial
  Serial.println("C"); 
  Serial.println("https://blog.zeruns.com");
}

void errorDecoder(SHTC3_Status_TypeDef message) // The errorDecoder function prints "SHTC3_Status_TypeDef" results in a human-friendly way
{
  switch(message)
  {
    case SHTC3_Status_Nominal : Serial.print("Nominal"); break;
    case SHTC3_Status_Error : Serial.print("Error"); break;
    case SHTC3_Status_CRC_Fail : Serial.print("CRC Fail"); break;
    default : Serial.print("Unknown return code"); break;
  }
}

Screenshot

Sensor Purchase

DHT11: Copy $Lk3h1Mx8UTO$ to open Taobao app and order immediately

DHT22: Copy $kr2T1MxkUKY$ to open Taobao app and order immediately

SHTC3: Copy $UD4D1Mx6N3R$ to open Taobao app and order immediately

Recommended Reading:

  • Recommended high-performance and affordable VPS/cloud servers: https://blog.zeruns.com/archives/383.html
  • Set up an internal network penetration server with a web panel: https://blog.zeruns.com/archives/397.html
  • Build your own cloud storage with Cloudreve: https://blog.zeruns.com/archives/515.html
  • How to set up a personal blog: https://blog.zeruns.com/archives/218.html
  • Student discount benefits guide: https://blog.zeruns.com/archives/321.html
  • Share a small game that can earn money: https://blog.zeruns.com/archives/472.html
1 Like