SHT21 (HTU21, SI7021) датчик температуры и влажности

Изучите всё о датчике SHT21: технические характеристики, распиновка, схемы подключения, datasheet и примеры кода для ESP32, Arduino

Температура и влажность I2C

Обзор

SHT21 (также известный как HTU21 или SI7021) — это высокоточный цифровой датчик температуры и влажности с интерфейсом I2C. Датчик обеспечивает отличную точность измерений и широко используется в различных проектах IoT.

SHT21 (HTU21/SI7021) — это высокоточный датчик температуры и влажности с интерфейсом I2C. Датчик обеспечивает точность ±0.3°C и ±2% RH. Благодаря широкой доступности и низкой цене, он является популярным выбором для проектов Arduino и ESP32.

Датчик SHT21

Ключевые особенности

  • I2C интерфейс — простая интеграция
  • Высокая точность — ±0.3°C, ±2% RH
  • Совместимость — HTU21, SI7021, SHT21
  • Низкое энергопотребление

Технические характеристики SHT21

Интерфейс
I2C
Адрес I2C
0x40
Точность температуры
±0.3 °C
Точность влажности
±2 % RH

Распиновка SHT21

Вывод ESP32
VDD3.3V
GNDGND
SDAGPIO21
SCLGPIO22

Примеры кода

Arduino

#include <Wire.h>
#include <HTU21D.h>

HTU21D htu;

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

void loop() {
  float temp = htu.readTemperature();
  float humidity = htu.readHumidity();
  
  Serial.print("Температура: ");
  Serial.println(temp);
  Serial.print("Влажность: ");
  Serial.println(humidity);
  
  delay(2000);
}

ESPHome

sensor:
  - platform: htu21d
    temperature:
      name: "SHT21 Temperature"
    humidity:
      name: "SHT21 Humidity"
    update_interval: 60s

environment I2C

SHT21 / HTU21 / GY-21 / SI7021 Temperature and Humidity Sensor image

Overview

The SHT21, HTU21, GY-21, and SI7021 sensors utilize I2C for reliable communication and provide calibrated, linearized temperature and humidity readings. Their compact form factor and low power consumption make them ideal for precise environmental monitoring.

Quick Navigation

Specs Pinout Wiring Debug

Code Examples

[

Arduino Core

Arduino

C++ Framework

](#arduino)[

ESP-IDF

ESP-IDF

Native Framework

](#esp-idf)[

ESPHome

ESPHome

YAML Configuration

](#esphome)[

PlatformIO

PlatformIO

IDE & Toolchain

](#platformio)[

MicroPython

MicroPython

Python Framework

](#micropython)

About SHT21 / HTU21 / GY-21 / SI7021 Temperature and Humidity Sensor

The SHT21, HTU21, GY-21, and SI7021 are compact digital temperature and humidity sensors that provide high-precision measurements. Using the I²C communication protocol, they are ideal for HVAC systems, data loggers, weather stations, and consumer electronics.

Key Features

  • High Accuracy & Stability – Reliable temperature and humidity sensing.
  • I²C Communication – Easy integration with ESP32, Arduino, and other microcontrollers.
  • Compact & Energy-Efficient – Ideal for low-power and battery-powered applications.
  • Versatile Applications – Used in climate control, weather monitoring, and industrial automation.

🔗 Looking for alternatives in the SHT series? Check out:

  • SHT20 – Cost-effective option.
  • SHT25 – Improved accuracy.
  • SHT30 – Enhanced performance and additional features.

Where to Buy

Get Your SHT21 / HTU21 / GY-21 / SI7021

SHT21 / HTU21 / GY-21 / SI7021 Temperature and Humidity Sensor

Starting from

$5 per unit

Amazon comAmazon deAliexpress

Prices are subject to change. We earn from qualifying purchases as an Amazon Associate.

Technical Specs

SHT21 / HTU21 / GY-21 / SI7021 Specifications

Complete technical specification details for SHT21 / HTU21 / GY-21 / SI7021 Temperature and Humidity Sensor

📊 Technical Parameters

Operating Voltage 2.1V to 3.6V

Temperature Range -40°C to 125°C

Humidity Range 0% to 100% RH

Temperature Accuracy ±0.3°C

Humidity Accuracy ±2% RH

Interface I2C

Dimensions 3mm x 3mm x 1.1mm

Download Full Datasheet

Pin Configuration

SHT21 / HTU21 / GY-21 / SI7021 Pinout

The SHT21/HTU21/GY-21/SI7021 sensors use standard I²C communication with 4 pins.

Visual Pinout Diagram

Pinout Diagram Primary

SHT21 / HTU21 / GY-21 / SI7021 Temperature and Humidity Sensor pinout

4

Total Pins

Pin Types

Power

2

Communication

2

Quick Tips

🔌

Standard I²C interface for easy integration,📡 Default I²C address is 0x40

💡

Multiple sensor names (SHT21/HTU21/GY-21/SI7021) - same chip,⚡ Pull-up resistors (10kΩ) recommended on SDA/SCL

🌡️

High accuracy: ±0.3°C temperature, ±3% humidity

Pin Descriptions

Pin Name

Type

Description

Notes

1 VCC

Power

Power supply input (2.1V to 3.6V)

Low voltage operation for battery applications

2 GND

Power

Ground connection

Connect to ESP32 ground

3 SDA

Communication

I²C data line

Bidirectional data communication

4 SCL

Communication

I²C clock line

Clock signal from master device

Connection Guide

Wiring SHT21 / HTU21 / GY-21 / SI7021 to ESP32

Connect the SHT21/HTU21/GY-21/SI7021 using standard I²C interface.

Visual Wiring Diagram

Wiring Diagram Recommended

SHT21 / HTU21 / GY-21 / SI7021 Temperature and Humidity Sensor wiring with ESP32

4

Connections

Connection Status

Required

4

Protocol

I2C

Pin Connections

SHT21 / HTU21 / GY-21 / SI7021 Pin

Connection

ESP32 Pin

Description

1 VCC Required

3.3V

Power supply (2.1V to 3.6V)

2 GND Required

GND

Ground connection

3 SDA Required

GPIO21

I²C data line (default SDA)

4 SCL Required

GPIO22

I²C clock line (default SCL)

💡

GPIO21/22 are default I²C pins on ESP32

🔧

I²C address is 0x40 (standard for this sensor)

Add 10kΩ pull-up resistors on SDA/SCL if needed

📡

Compatible with SHT20 libraries and code

Help & Support

SHT21 / HTU21 / GY-21 / SI7021 Troubleshooting

Common issues and solutions to help you get your sensor working

Common Issues

💻 Compilation Errors with SHT21 Library

Issue: When compiling code that interfaces with the SHT21 sensor using the LibHumidity library, errors such as 'class TwoWire' has no member named 'send' and 'class TwoWire' has no member named 'receive' are encountered.

Possible causes include the use of outdated functions in the library that are incompatible with the current Wire library, which now uses write() and read() methods instead of send() and receive().

Solution: Update the LibHumidity library by replacing instances of send() with write() and receive() with read(). Alternatively, consider using a more recent library that supports the SHT21 sensor and is compatible with the current Wire library implementation.

🔒 Permission Denied Error on Raspberry Pi

Issue: When running a Python script to read data from the SHT21 sensor on a Raspberry Pi, the error [Errno 13] Permission denied: '/dev/i2c-1' is encountered.

Possible causes include insufficient permissions to access the I2C bus device file.

Solution: Execute the Python script with elevated privileges by prefixing the command with sudo. For example, run sudo python sht21.py to grant the necessary permissions to access the I2C bus.

⚠️ Incorrect Temperature and Humidity Readings

Issue: The SHT21 sensor returns incorrect temperature and humidity values, such as 988 instead of the expected readings.

Possible causes include improper wiring, incorrect I2C address configuration, or sensor initialization issues.

Solution: Verify that the sensor is correctly wired to the microcontroller, ensuring proper connections for power, ground, and I2C data lines. Confirm that the correct I2C address (typically 0x40) is specified in your code. Ensure that the sensor is properly initialized in the software, and consider using a reliable library compatible with the SHT21 sensor.

🔌 Interfacing Issues with SHT21 Sensor

Issue: Difficulty in establishing I2C communication with the SHT21 sensor, leading to unsuccessful data retrieval.

Possible causes include incorrect I2C initialization, improper sensor configuration, or timing issues in the communication protocol.

Solution: Ensure that the I2C bus is correctly initialized with the appropriate settings, including clock speed and addressing. Review the sensor’s datasheet to confirm proper configuration and command sequences. Implement necessary delays as specified in the sensor’s communication protocol to accommodate timing requirements.

Debugging Tips

Serial Monitor

Use the Serial Monitor to check for error messages and verify the sensor’s output. Add debug prints in your code to track the sensor’s state.

Voltage Checks

Use a multimeter to verify voltage levels and check for continuity in your connections. Ensure the power supply is stable and within the sensor’s requirements.

Additional Resources

[

Datasheet

Technical specifications and guidelines

](https://sensirion.com/media/documents/120BBE4C/63500094/Sensirion_Datasheet_Humidity_Sensor_SHT21.pdf)

Code Examples

SHT21 / HTU21 / GY-21 / SI7021 Programming Examples

Ready-to-use code examples for different platforms and frameworks

Arduino Example

Compatible with Arduino IDE and ESP32 boards

C++

#include <Wire.h>#include "SHT21.h"SHT21 sht;void setup() {  Wire.begin();  Serial.begin(9600);}void loop() {  float temperature = sht.getTemperature();  float humidity = sht.getHumidity();  Serial.print("Temperature: ");  Serial.print(temperature);  Serial.println(" °C");  Serial.print("Humidity: ");  Serial.print(humidity);  Serial.println(" %");  delay(2000);}

This Arduino sketch demonstrates how to interface with these sensors using the SHT21 library. It initializes the sensor and reads temperature and humidity data every 2 seconds, printing the results to the Serial Monitor. Ensure that the SHT21 library is installed in your Arduino IDE.

ESP-IDF Example

Official Espressif IoT Development Framework

C++

#include <stdio.h>#include "freertos/FreeRTOS.h"#include "freertos/task.h"#include "driver/i2c.h"#define I2C_MASTER_SCL_IO    22    /*!< GPIO number used for I2C master clock */#define I2C_MASTER_SDA_IO    21    /*!< GPIO number used for I2C master data */#define I2C_MASTER_NUM       I2C_NUM_0 /*!< I2C master I2C port number */#define I2C_MASTER_FREQ_HZ   100000     /*!< I2C master clock frequency */#define SHT21_SENSOR_ADDR    0x40       /*!< I2C address */void read_sensor() {    uint8_t data[3];    uint8_t cmd = 0xF5; // Humidity command    i2c_master_write_to_device(I2C_MASTER_NUM, SHT21_SENSOR_ADDR, &cmd, 1, pdMS_TO_TICKS(1000));    vTaskDelay(pdMS_TO_TICKS(50));    i2c_master_read_from_device(I2C_MASTER_NUM, SHT21_SENSOR_ADDR, data, 3, pdMS_TO_TICKS(1000));    uint16_t raw_humidity = (data[0] << 8) | (data[1] & 0xFC);    float humidity = -6.0 + 125.0 * (raw_humidity / 65536.0);    cmd = 0xF3; // Temperature command    i2c_master_write_to_device(I2C_MASTER_NUM, SHT21_SENSOR_ADDR, &cmd, 1, pdMS_TO_TICKS(1000));    vTaskDelay(pdMS_TO_TICKS(50));    i2c_master_read_from_device(I2C_MASTER_NUM, SHT21_SENSOR_ADDR, data, 3, pdMS_TO_TICKS(1000));    uint16_t raw_temperature = (data[0] << 8) | (data[1] & 0xFC);    float temperature = -46.85 + 175.72 * (raw_temperature / 65536.0);    printf("Temperature: %.2f °C\n", temperature);    printf("Humidity: %.2f %%\n", humidity);}void app_main() {    // Initialize I2C    i2c_config_t conf = {        .mode = I2C_MODE_MASTER,        .sda_io_num = I2C_MASTER_SDA_IO,        .scl_io_num = I2C_MASTER_SCL_IO,        .sda_pullup_en = GPIO_PULLUP_ENABLE,        .scl_pullup_en = GPIO_PULLUP_ENABLE,        .master.clk_speed = I2C_MASTER_FREQ_HZ,    };    i2c_param_config(I2C_MASTER_NUM, &conf);    i2c_driver_install(I2C_MASTER_NUM, conf.mode, 0, 0, 0);    while (1) {        read_sensor();        vTaskDelay(pdMS_TO_TICKS(2000));    }}

This ESP-IDF code demonstrates how to read temperature and humidity data from the SHT21-compatible sensors. It sends commands to initiate measurements, retrieves the raw data over I2C, and calculates the actual values based on datasheet formulas. Results are printed to the console every 2 seconds.

ESPHome Example

Home Assistant ESPHome configuration

YAML

sensor:  - platform: sht3x    address: 0x40    temperature:      name: "Room Temperature"    humidity:      name: "Room Humidity"    update_interval: 60s

This ESPHome configuration uses the `sht3x` platform for SHT21-compatible sensors. It defines two sensor entities for temperature and humidity, with human-readable names. The `update_interval` is set to 60 seconds, ensuring periodic updates of the readings.

PlatformIO Example

Professional development environment

C++

platformio.ini

[env:esp32dev]platform = espressif32board = esp32devframework = arduinolib_deps =     DFRobot/SHT21 @ ^1.0.0monitor_speed = 115200

main.cpp

#include <Wire.h>#include "SHT21.h"SHT21 sht;void setup() {    Wire.begin();    Serial.begin(115200);    Serial.println("SHT21 Sensor Example");}void loop() {    float temperature = sht.getTemperature();    float humidity = sht.getHumidity();    if (!isnan(temperature) && !isnan(humidity)) {        Serial.print("Temperature: ");        Serial.print(temperature);        Serial.println(" °C");        Serial.print("Humidity: ");        Serial.print(humidity);        Serial.println(" %");    } else {        Serial.println("Failed to read from sensor");    }    delay(2000);}

This PlatformIO example uses the DFRobot SHT21 library to interact with the sensor. It reads temperature and humidity every 2 seconds and prints the values to the Serial Monitor, ensuring easy integration with ESP32 and other Arduino-compatible boards.

🐍

MicroPython Example

Python for microcontrollers

Python

from machine import Pin, I2Cfrom time import sleepSENSOR_ADDR = 0x40CMD_TEMP = 0xF3CMD_HUM = 0xF5def read_sensor(i2c, cmd):    i2c.writeto(SENSOR_ADDR, bytearray([cmd]))    sleep(0.05)    data = i2c.readfrom(SENSOR_ADDR, 3)    return (data[0] << 8 | data[1]) & 0xFFFCdef calc_temperature(raw_temp):    return -46.85 + 175.72 * (raw_temp / 65536.0)def calc_humidity(raw_hum):    return -6.0 + 125.0 * (raw_hum / 65536.0)i2c = I2C(0, scl=Pin(22), sda=Pin(21))while True:    raw_temp = read_sensor(i2c, CMD_TEMP)    raw_hum = read_sensor(i2c, CMD_HUM)    temperature = calc_temperature(raw_temp)    humidity = calc_humidity(raw_hum)    print("Temperature: {:.2f} °C".format(temperature))    print("Humidity: {:.2f} %".format(humidity))    sleep(2)

This MicroPython script interfaces with SHT21-compatible sensors over I2C. It retrieves raw temperature and humidity data, processes it using datasheet equations, and displays the results on the console every 2 seconds.

Summary

Wrapping Up SHT21 / HTU21 / GY-21 / SI7021

The ESP32 SHT21 / HTU21 / GY-21 / SI7021 Temperature and Humidity Sensor is a powerful environment sensor that offers excellent performance and reliability. With support for multiple development platforms including Arduino, ESP-IDF, ESPHome, PlatformIO, and MicroPython, it’s a versatile choice for your IoT projects.

Best Practices

For optimal performance, ensure proper wiring and follow the recommended configuration for your chosen development platform.

Safety First

Always verify power supply requirements and pin connections before powering up your project to avoid potential damage.

Ready to Start Building?

Now that you have all the information you need, it’s time to integrate the SHT21 / HTU21 / GY-21 / SI7021 into your ESP32 project and bring your ideas to life!

View Code Examples Download Datasheet

Similar Options

Explore Alternative Sensors

Looking for alternatives to the SHT21 / HTU21 / GY-21 / SI7021? Check out these similar sensors that might fit your project needs.

SHT41 / SHT41-D / GY-SHT41-D Temperature and Humidity Sensor

SHT41 / SHT41-D / GY-SHT41-D Temperature and Humidity Sensor

ENVIRONMENT I2C

The SHT41 sensor is part of Sensirion’s SHT4x series and offers high-accuracy temperature and humidity measurements. It is factory…

View Details

BMP280 Barometric Pressure and Temperature Sensor

BMP280 Barometric Pressure and Temperature Sensor

ENVIRONMENT I2C,SPI

The BMP280 is a high-precision digital barometric pressure and temperature sensor, ideal for weather monitoring, altimetry, and navigation…

View Details

DHT20 Temperature and Humidity Sensor

DHT20 Temperature and Humidity Sensor

ENVIRONMENT I2C

The DHT20 is a high-precision digital temperature and humidity sensor with an I²C interface. It features low power consumption, fast…

View Details

Contents