Beginner · Lesson 5 of 10

A sensor over I²C

Wire a Sensirion SHT4x to the ESP32-C5, size the pull-ups, scan the bus, read the datasheet for every command and timing, check the CRC, and keep the board's heat out of the reading.

BeginnerEspressif45 minUpdated 28 November 2026Tier 1: Builds in CI

You will learn

  • Explain START, address, ACK and STOP on an I²C bus
  • Choose pull-up resistors from the bus speed and capacitance
  • Scan a bus and interpret a missing or timed-out device
  • Find every command, timing and formula you need in a sensor datasheet
  • Keep self-heating from the board out of a temperature reading

Before this: GPIO, timers and interrupts

This lesson connects your first real sensor: a Sensirion SHT4x temperature and humidity sensor on a breakout board, wired to the ESP32-C5-DevKitC-1 over I²C (Inter-Integrated Circuit), a two-wire bus. It shows how to find the numbers your code needs in a datasheet, how to size the bus pull-up resistors, and why a sensor on a warm board reads wrong. Every SHT4x figure below comes from Sensirion’s datasheet, version 7.3 of June 2026.

How an I²C transaction works

I²C uses two lines: SDA (serial data) and SCL (serial clock). Every device drives them through an open-drain output, which can only pull a line low. A pull-up resistor on each line pulls it high whenever nobody is pulling it low. That is why an I²C bus without pull-ups does not work at all.

The controller (here the ESP32-C5) starts every transaction with a START condition: SDA falls while SCL is high. It then clocks out a 7-bit address and one direction bit, 0 for write and 1 for read. On the ninth clock pulse the controller releases SDA, and a device that recognises its address pulls SDA low to acknowledge (ACK). If SDA stays high, that is a NACK (not acknowledge). The most common reason is that no device has that address. A STOP condition, SDA rising while SCL is high, ends the transaction.

An I²C address probe of 0x44 with the write bit: START, the seven address bits 1000100, W = 0, an ACK pulled low by the sensor on the ninth clock, then STOP. This exchange is what a bus scan sends to every address.SCLSDAbitS1000100WACKP
An I²C address probe of 0x44 with the write bit: START, the seven address bits 1000100, W = 0, an ACK pulled low by the sensor on the ninth clock, then STOP. This exchange is what a bus scan sends to every address.

A full SHT4x measurement uses two transactions with a pause between them.

Step Who drives SDA Bytes
1. Write Controller START, 0x44 + W, (ACK from sensor), 0xFD, (ACK), STOP
2. Wait Nobody At least 8.3 ms while the sensor measures
3. Read Sensor, with controller ACKs START, 0x44 + R, (ACK), T high, T low, CRC, RH high, RH low, CRC, (NACK from controller), STOP

The controller ACKs each byte it reads and sends a NACK after the last one, which tells the sensor the read is over.

Wiring and pull-ups

Connect the breakout to the DevKitC-1 header: VDD to 3V3 (J1 pin 1), GND to G (J1 pin 15), SDA to GPIO8 (J1 pin 9) and SCL to GPIO9 (J1 pin 10). These two GPIOs are not strapping pins, so the sensor cannot upset the boot. The SHT4x runs from 1.08 V to 3.6 V, so 3.3 V is within range.

ESP32-C5-DevKitC-13V3 (J1-1)GPIO8 SDA (J1-9)GPIO9 SCL (J1-10)G (J1-15)SHT4x breakoutVDDSDASCLGNDRpRp100 kHz, 100 pF bus: Rp from 967 Ω to 11.8 kΩ
Wiring for this lesson. Each bus line has one pull-up resistor Rp to 3.3 V. The sizing range in the note comes from our calculation script. Our own drawing.

Check the breakout’s schematic for two resistors from SDA and SCL to VDD, and fit them if they are missing. Several breakouts on one bus put their pull-ups in parallel, which lowers the total resistance.

The resistor value is a compromise, and the I²C specification (NXP UM10204, revision 7.0) gives both ends of it.

  • Too large, and the edges are too slow. The bus wires and pins add capacitance, Cb. The resistor charges it, and the specification limits the time from 30 % to 70 % of the supply to 1000 ns in Standard-mode (100 kHz) and 300 ns in Fast-mode (400 kHz). That gives Rp(max) = tr / (0.8473 × Cb).
  • Too small, and the outputs cannot pull the line low enough. A device must sink 3 mA while holding the line at 0.4 V or below. That gives Rp(min) = (VDD − 0.4 V) / 3 mA.

Our script examples/l05-i2c-sensor/host/i2c_numbers.py does the arithmetic. At 3.3 V, Rp(min) is 967 Ω. With 100 pF of bus capacitance, Rp(max) is 11.8 kΩ in Standard-mode but 3.54 kΩ in Fast-mode. A 4.7 kΩ pull-up therefore suits this lesson’s 100 kHz bus and is too weak for 400 kHz at that capacitance. Both values stay above the SHT4x’s own minimum pull-up of 390 Ω.

The ESP32-C5’s internal pull-ups are about 45 kΩ (typical, from the datasheet at 3.3 V and 25 °C). The same formula says 45 kΩ meets the rise time only up to 26.2 pF in Standard-mode and 7.9 pF in Fast-mode. Espressif’s driver documentation also calls them too weak for higher speeds and suggests external resistors, usually 1 kΩ to 10 kΩ. The example leaves them off on purpose, so a missing external pull-up shows up at once in the bus scan.

Scanning the bus

A scan sends the probe in the timing diagram to every usable address and records which ones ACK. The I²C specification reserves 0x00 to 0x07 and 0x78 to 0x7F, so the scan covers 0x08 to 0x77. ESP-IDF v6.1.1 provides i2c_master_probe() for this. It returns ESP_OK on an ACK and ESP_ERR_NOT_FOUND on a NACK. Espressif documents ESP_ERR_TIMEOUT as a sign of pull-up trouble, so the example stops and says so.

An SHT4x answers at 0x44, 0x45 or 0x46 depending on the part number suffix (A, B or C). The example assumes an “A” part at 0x44. If your scan finds 0x45, change SHT4X_ADDR_A in sht4x.h.

Reading the datasheet for what the code needs

Here is every number the firmware uses, with where to find it in version 7.3.

What the code needs Value Datasheet section
Supply range 1.08 V to 3.6 V 3, Table 4
Address 0x44, 0x45 or 0x46 by part 4.1 and ordering information
Measure command 0xFD: temperature and humidity, high repeatability 4.5, Table 8
Measurement time 6.9 ms typical, 8.3 ms maximum 3.1, Table 5
Busy behaviour No clock stretching. NACKs a read until the result is ready. Data can be read once 4.1
Reply format 6 bytes: temperature (2), CRC, humidity (2), CRC 4.3
Checksum CRC-8, polynomial 0x31, start value 0xFF, no reflection, no final XOR. CRC(0xBEEF) = 0x92 4.4, Table 7
Conversion T = −45 + 175 × ST / 65535 °C. RH = −6 + 125 × SRH / 65535 %RH, cropped to 0 to 100 4.6

Two details are easy to miss. The maximum timings in Table 5 were characterised at −40 °C and 1.08 V, the worst corner, so waiting 8.3 ms is safe everywhere. And the humidity formula can return values below 0 % or above 100 %, which the datasheet calls non-physical and advises cropping.

The code puts the conversion and checksum in a separate file with no ESP-IDF dependency, so the same file can be compiled on a PC and tested.

// target: esp32c5 and host sdk: esp-idf, host cc via host/test_sht4x.py tier: 2
#include "sht4x.h"

uint8_t sht4x_crc8(const uint8_t *data, size_t len)
{
    uint8_t crc = 0xFF;
    for (size_t i = 0; i < len; i++) {
        crc ^= data[i];
        for (int bit = 0; bit < 8; bit++) {
            crc = (crc & 0x80) ? (uint8_t)((crc << 1) ^ 0x31) : (uint8_t)(crc << 1);
        }
    }
    return crc;
}

float sht4x_temp_c(uint16_t s_t)
{
    return -45.0f + 175.0f * (float)s_t / 65535.0f;
}

float sht4x_rh_percent(uint16_t s_rh)
{
    float rh = -6.0f + 125.0f * (float)s_rh / 65535.0f;
    if (rh < 0.0f) {
        rh = 0.0f;
    }
    if (rh > 100.0f) {
        rh = 100.0f;
    }
    return rh;
}

int sht4x_parse(const uint8_t rx[6], float *temp_c, float *rh_percent)
{
    if (sht4x_crc8(&rx[0], 2) != rx[2] || sht4x_crc8(&rx[3], 2) != rx[5]) {
        return -1;
    }
    *temp_c = sht4x_temp_c((uint16_t)((rx[0] << 8) | rx[1]));
    *rh_percent = sht4x_rh_percent((uint16_t)((rx[3] << 8) | rx[4]));
    return 0;
}

The firmware scans the bus, then reads the sensor every 5 seconds.

// target: esp32c5 sdk: esp-idf tier: 1
// Scan the I2C bus, then read an SHT4x (address 0x44) every 5 s on the ESP32-C5-DevKitC-1.
// Wiring: SDA to GPIO8 (J1 pin 9), SCL to GPIO9 (J1 pin 10), VDD to 3V3, GND to G.
// The breakout must have pull-up resistors on SDA and SCL (see the lesson).
#include <inttypes.h>
#include <stdio.h>

#include "driver/i2c_master.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "sht4x.h"

#define I2C_SDA_GPIO 8
#define I2C_SCL_GPIO 9
#define I2C_HZ 100000            // standard mode, the most forgiving speed
#define USE_INTERNAL_PULLUPS 0   // about 45 kOhm: too weak except for a short, slow bus
#define XFER_TIMEOUT_MS 50

// vTaskDelay(n) can return up to one tick early, and pdMS_TO_TICKS rounds down
// (at the default 100 Hz tick, pdMS_TO_TICKS(9) is 0). Round up, then add a tick.
static TickType_t ticks_at_least_ms(uint32_t ms)
{
    return (TickType_t)((ms * configTICK_RATE_HZ + 999) / 1000) + 1;
}

static void scan(i2c_master_bus_handle_t bus)
{
    printf("Scanning 0x08..0x77\n");
    int found = 0;
    for (uint16_t addr = 0x08; addr <= 0x77; addr++) {  // 0x00-0x07 and 0x78-0x7F are reserved
        esp_err_t err = i2c_master_probe(bus, addr, XFER_TIMEOUT_MS);
        if (err == ESP_OK) {
            printf("  device at 0x%02X\n", addr);
            found++;
        } else if (err == ESP_ERR_TIMEOUT) {
            printf("  bus timeout at 0x%02X: check pull-ups and wiring\n", addr);
            return;
        }
    }
    printf("%d device(s) found\n", found);
}

void app_main(void)
{
    i2c_master_bus_config_t bus_cfg = {
        .i2c_port = -1,  // pick any free controller
        .sda_io_num = I2C_SDA_GPIO,
        .scl_io_num = I2C_SCL_GPIO,
        .clk_source = I2C_CLK_SRC_DEFAULT,
        .glitch_ignore_cnt = 7,
        .flags.enable_internal_pullup = USE_INTERNAL_PULLUPS,
    };
    i2c_master_bus_handle_t bus;
    ESP_ERROR_CHECK(i2c_new_master_bus(&bus_cfg, &bus));
    scan(bus);

    i2c_device_config_t dev_cfg = {
        .dev_addr_length = I2C_ADDR_BIT_LEN_7,
        .device_address = SHT4X_ADDR_A,
        .scl_speed_hz = I2C_HZ,
    };
    i2c_master_dev_handle_t sht;
    ESP_ERROR_CHECK(i2c_master_bus_add_device(bus, &dev_cfg, &sht));

    const uint8_t cmd = SHT4X_CMD_MEASURE_HIGH;
    uint8_t rx[6];
    for (;;) {
        esp_err_t err = i2c_master_transmit(sht, &cmd, 1, XFER_TIMEOUT_MS);
        if (err == ESP_OK) {
            // The sensor does not stretch the clock: it NACKs reads until it is done.
            vTaskDelay(ticks_at_least_ms(SHT4X_MEAS_HIGH_MAX_MS));
            err = i2c_master_receive(sht, rx, sizeof rx, XFER_TIMEOUT_MS);
        }
        float t, rh;
        if (err != ESP_OK) {
            printf("I2C error: %s\n", esp_err_to_name(err));
        } else if (sht4x_parse(rx, &t, &rh) != 0) {
            printf("CRC mismatch: %02X %02X %02X %02X %02X %02X\n", rx[0], rx[1], rx[2], rx[3], rx[4], rx[5]);
        } else {
            printf("T = %.2f C, RH = %.2f %%\n", t, rh);
        }
        vTaskDelay(pdMS_TO_TICKS(5000));  // slow readings keep the sensor from warming itself
    }
}

Note ticks_at_least_ms(). At ESP-IDF’s default tick rate of 100 Hz, pdMS_TO_TICKS(9) rounds down to zero ticks, and a one-tick delay can end almost at once. Without the rounding, the read could arrive before the measurement is done, and the sensor would NACK it. The function rounds up and adds a tick, so the wait is never shorter than 9 ms.

Testing the maths on your PC

Conversion and checksum bugs are silent: the program prints a plausible wrong number. The host test has a Python reference written from the datasheet text, checks it against the datasheet’s worked example, CRC(0xBEEF) = 0x92, then compiles sht4x.c with the PC’s C compiler and compares the two over all 65,536 possible raw values. It also flips one bit in a valid reply and checks that sht4x_parse() rejects it. Run it with python test_sht4x.py. Our example checker runs it, so this part reaches tier 2, “Runs in CI”. The firmware stays at tier 1 until it has run on our bench.

# target: host sdk: python tier: 2
"""Host-side tests for the SHT4x conversion maths in ../esp-idf/main/sht4x.c.

1. A Python reference written straight from the SHT4x datasheet (v7.3, June 2026),
   checked against the datasheet's own worked example: CRC(0xBEEF) = 0x92.
2. The firmware's C file, compiled for the host with the system C compiler and
   loaded with ctypes, compared against the reference over all 65,536 raw values.
Run from anywhere: python test_sht4x.py
"""
from __future__ import annotations

import ctypes
import shutil
import subprocess
import sys
import tempfile
from pathlib import Path

C_SRC = Path(__file__).resolve().parent.parent / "esp-idf" / "main" / "sht4x.c"


# ---- reference implementation, from the datasheet text -------------------------
def crc8(data: bytes) -> int:
    """CRC-8, polynomial 0x31, initialisation 0xFF, no reflection, final XOR 0x00."""
    crc = 0xFF
    for byte in data:
        crc ^= byte
        for _ in range(8):
            crc = ((crc << 1) ^ 0x31) & 0xFF if crc & 0x80 else (crc << 1) & 0xFF
    return crc


def temp_c(s_t: int) -> float:
    return -45 + 175 * s_t / 65535  # equation (2)


def rh_percent(s_rh: int) -> float:
    return min(100.0, max(0.0, -6 + 125 * s_rh / 65535))  # equation (1), cropped


def frame(s_t: int, s_rh: int) -> bytes:
    """Build the 6-byte reply the sensor would send for these raw values."""
    t, h = s_t.to_bytes(2, "big"), s_rh.to_bytes(2, "big")
    return t + bytes([crc8(t)]) + h + bytes([crc8(h)])


# ---- tests ----------------------------------------------------------------------
def test_reference() -> None:
    assert crc8(b"\xbe\xef") == 0x92, "datasheet example CRC(0xBEEF) = 0x92"
    assert temp_c(0) == -45.0 and temp_c(65535) == 130.0
    assert rh_percent(0) == 0.0 and rh_percent(65535) == 100.0  # -6 and 119 before cropping
    # Raw value that gives 0 %RH before cropping: 6/125 of full scale.
    assert abs((-6 + 125 * 3146 / 65535) - 0.0) < 0.01
    # The datasheet allows dividing by 2^16 instead of 2^16 - 1: error < 0.003 C and < 0.002 %RH.
    worst_t = max(abs(temp_c(s) - (-45 + 175 * s / 65536)) for s in range(65536))
    worst_rh = max(abs((-6 + 125 * s / 65535) - (-6 + 125 * s / 65536)) for s in range(65536))
    assert worst_t < 0.003 and worst_rh < 0.002, (worst_t, worst_rh)
    print(f"reference ok: CRC example matches; 2^16 shortcut error {worst_t:.4f} C, {worst_rh:.4f} %RH")


def build_c_library(tmp: Path) -> ctypes.CDLL:
    cc = shutil.which("cc") or shutil.which("gcc") or shutil.which("clang")
    if cc is None:
        sys.exit("FAIL: no host C compiler found, cannot test the firmware's C code")
    lib = tmp / ("libsht4x.dylib" if sys.platform == "darwin" else "libsht4x.so")
    subprocess.run([cc, "-std=c11", "-O2", "-Wall", "-Wextra", "-Werror", "-shared", "-fPIC",
                    "-o", str(lib), str(C_SRC)], check=True)
    so = ctypes.CDLL(str(lib))
    so.sht4x_crc8.restype, so.sht4x_crc8.argtypes = ctypes.c_uint8, [ctypes.c_char_p, ctypes.c_size_t]
    so.sht4x_temp_c.restype, so.sht4x_temp_c.argtypes = ctypes.c_float, [ctypes.c_uint16]
    so.sht4x_rh_percent.restype, so.sht4x_rh_percent.argtypes = ctypes.c_float, [ctypes.c_uint16]
    so.sht4x_parse.restype = ctypes.c_int
    so.sht4x_parse.argtypes = [ctypes.c_char_p, ctypes.POINTER(ctypes.c_float), ctypes.POINTER(ctypes.c_float)]
    return so


def test_c_matches_reference(so: ctypes.CDLL) -> None:
    assert so.sht4x_crc8(b"\xbe\xef", 2) == 0x92
    worst_t = worst_rh = 0.0
    for s in range(65536):
        worst_t = max(worst_t, abs(so.sht4x_temp_c(s) - temp_c(s)))
        worst_rh = max(worst_rh, abs(so.sht4x_rh_percent(s) - rh_percent(s)))
        if s % 257 == 0:  # CRC over a spread of words
            w = s.to_bytes(2, "big")
            assert so.sht4x_crc8(w, 2) == crc8(w), hex(s)
    # Single-precision float keeps the error far below the sensor's 0.01 resolution.
    assert worst_t < 1e-4 and worst_rh < 1e-4, (worst_t, worst_rh)
    print(f"C conversion ok over 65,536 raw values: worst error {worst_t:.2e} C, {worst_rh:.2e} %RH")


def test_c_parse(so: ctypes.CDLL) -> None:
    t, h = ctypes.c_float(), ctypes.c_float()
    good = frame(0x6666, 0x8000)  # 0x6666 = 26214 -> 25.00 C; 0x8000 -> 56.50 %RH
    assert so.sht4x_parse(good, ctypes.byref(t), ctypes.byref(h)) == 0
    assert abs(t.value - temp_c(0x6666)) < 1e-4 and abs(t.value - 25.0) < 0.01, t.value
    assert abs(h.value - rh_percent(0x8000)) < 1e-4, h.value
    bad = bytearray(good)
    bad[1] ^= 0x01  # one flipped bit in the temperature word
    assert so.sht4x_parse(bytes(bad), ctypes.byref(t), ctypes.byref(h)) == -1
    bad = bytearray(good)
    bad[5] ^= 0x80  # corrupted humidity checksum
    assert so.sht4x_parse(bytes(bad), ctypes.byref(t), ctypes.byref(h)) == -1
    print(f"C parse ok: {good.hex(' ')} -> {t.value:.2f} C, {h.value:.2f} %RH; corrupted frames rejected")


def main() -> int:
    test_reference()
    with tempfile.TemporaryDirectory() as tmp:
        so = build_c_library(Path(tmp))
        test_c_matches_reference(so)
        test_c_parse(so)
    print("all SHT4x tests passed")
    return 0


if __name__ == "__main__":
    sys.exit(main())

On a Raspberry Pi Pico 2 W, sht4x.c works unchanged. The Pico SDK’s pico2_w board definition puts the default I²C pins on GP4 (SDA) and GP5 (SCL).

Self-heating: keep the board’s heat out

A temperature sensor measures its own temperature, including heat from everything near it. Sensirion’s design guide gives an example: at 90 % relative humidity, a 1 °C error in temperature turns into about 5 %RH of humidity error.

The SHT4x itself adds almost nothing. It draws 320 µA (typical) while measuring and averages 2.2 µA at one high-repeatability reading per second. With the datasheet’s thermal resistance of 297 K/W, our script puts the steady-state rise at no more than 0.31 K even if it measured continuously at 3.3 V, and no more than about 2 mK at one reading per second. The heat comes from the board instead. The ESP32-C5 chip alone draws up to 87 mA peak while receiving on 2.4 GHz Wi-Fi, at 3.3 V, and the devkit’s regulator and USB bridge add more. Sensirion names heat conducted through the circuit board from processors as the most common source of temperature error.

  • Put the sensor on a short cable away from the devkit, not plugged directly onto it.
  • Read slowly. This example reads every 5 seconds, and a battery sensor would read less often still.
  • Leave the sensor’s built-in heater off for normal readings. It runs at up to 200 mW for 0.1 s or 1 s, the specifications do not hold while it is on, and Sensirion limits it to a 10 % duty cycle. It exists to drive off condensation, not to measure.

For makers

Run the bus scan every time you wire something new. It separates wiring and pull-up problems from code problems. Keep the sensor away from the board on a cable, and compare its reading with the Wi-Fi off and on. The difference is your self-heating.

For product teams

Treat every number from the bus as untrusted: check the CRC, bound-check the converted value, and count failures in telemetry. Size pull-ups from the measured bus capacitance of the real harness, not from a breakout. Design the sensor’s placement with the PCB layout, using distance, thin traces and slots, and confirm it with a thermal test in the enclosure. Keep conversion code in a hardware-free module so it can be unit-tested in CI, as here.

Exercise

  1. Wire the sensor, flash the example and record the scan output. Remove the sensor’s pull-ups (or use a breakout without them) and record what the scan reports now.
  2. Plug the breakout directly beside the ESP32-C5 module, read for ten minutes, then move it 20 cm away on wires and read for ten more. Write down the difference in temperature and humidity.
  3. Change the command to 0xE0 (low repeatability) and use the datasheet to find the new maximum measurement time. Update the wait and check the readings still pass the CRC.
  4. Add a test case to test_sht4x.py for the raw temperature value closest to 0 °C. Work it out on paper first.

Summary

  • I²C transactions start with START, an address and a direction bit, and every byte is acknowledged on the ninth clock. A NACK to an address usually means nothing is there.
  • Pull-ups are required. Size them between Rp(min) = (VDD − 0.4 V) / 3 mA and Rp(max) = tr / (0.8473 × Cb). The ESP32-C5’s 45 kΩ internal pull-ups are too weak for most real buses.
  • The SHT4x needs one command byte, at least 8.3 ms of waiting, six bytes back, two CRC checks and two formulas, all in the datasheet.
  • Test conversion code on the host. Here it is checked against the datasheet example and over every raw value.
  • Board heat, not the sensor’s own current, causes most temperature error. Distance and slow reading rates reduce it.

Further reading

  • Sensirion, Datasheet SHT4x, version 7.3, sections 3 and 4.
  • NXP Semiconductors, UM10204 I²C-bus specification and user manual, revision 7.0, sections 3.1 and 7.1.
  • Sensirion, Design Guide for Humidity and Temperature Sensors, version 2, section 3.
  • Espressif Systems, ESP-IDF Programming Guide v6.1.1 for ESP32-C5, “I2C Interface”.