by luca


esp_htu21d is a component for the esp-idf framework; its goal is to interface with the HTU21D temperature and humidity sensor by TE Connectivity. This sensor, with I2C interface, can measure temperatures between -40 and 125°C and relative humidity from 0 to 100%.


The source code of esp32_htu21d is available on Github.

To use it in your program, download the most recent release. In the main folder of your project, create a new subfolder named components.

Unzip the archive downloaded from Github in that folder as it follows:



First include in your program the header file of the component:

#include "htu21d.h"

Then initialize the component with the htu21d_init method:

int htu21d_init(i2c_port_t port, int sda_pin, int scl_pin, 
 gpio_pullup_t sda_internal_pullup, gpio_pullup_t scl_internal_pullup);

Its parameters are:


  • port = I2C controller to be used (can be I2C_NUM_0 or I2C_NUM_1)
  • sda_pin, scl_pin = pin numbers connected to data (SDA) and clock (SCL) lines of the I2C bus
  • sda_internal_pullup, scl_internal_pullup = enable or not the internal pullup resistors for data and clock lines (GPIO_PULLUP_ENABLE or GPIO_PULLUP_DISABLE)


All the methods of this component returns an error code, that can be:


A simple way to check for an error is therefore:

if(ret != HTU21D_ERR_OK) {	
  printf("Error %d when initializing HTU21D component\r\n", ret);

After having initialized the sensor, you can get the temperature and humidity values with:

float ht21d_read_temperature();
float ht21d_read_humidity();

You can also require a soft reset of the sensor with the following method:

int htu21d_soft_reset();

In the end, you can modify the resolution of the sensor. Four are the possible combinations:

  • Humidity 12bits, temperature 14bits (0b00000000)
  • Humidity 8bits, temperature 12bits (0b00000001)
  • Humidity 10bits, temperature 13bits (0b10000000)
  • Humidity 11bits, temperature 11bits (0b10000001)

To change the resolution, call the method:

int ht21d_set_resolution(uint8_t resolution);

passing as parameter the binary value corresponding to the required resolution, for example for 11bits/11bits:


Similary, you can get the sensor’s current resolution with:

uint8_t ht21d_get_resolution();


A full example that uses this component is described in this blog post.

Here’s a short video about the example:

[youtube id=”amb0Tdu2Lns” width=”600″ height=”350″]


Release 0.1

– First public release