Skip to content
systemcoding.dev
Embedded

Use the New ESP-IDF I2C Master Driver With i2c_master_bus_add_device

Create an I2C bus with i2c_new_master_bus, attach a device with i2c_master_bus_add_device, and read registers with i2c_master_transmit_receive in ESP-IDF 5.3.

8 min read
Summarize in AI
Flat illustration of user space above the system call boundary, the kernel and the hardware, with the Espressif, Arm and C logos.

ESP-IDF v5.2 introduced a new I2C master driver that follows the same shape as the SPI master driver: you create a bus object once, then add a device object for each chip, giving each its own address and clock speed, and every transaction goes through the device handle. It replaces the older port-based calls (i2c_driver_install, i2c_master_write_to_device and the command-link API), which remain as a legacy driver. This post uses ESP-IDF v5.3 on an ESP32 to talk to an InvenSense MPU-6050, reading its WHO_AM_I register and a burst of sensor data, and explains the configuration structures, the timeout and error behavior, and the bus-sharing rules. The protocol background is in the guide to I2C in this cluster.

The two-level model

ObjectCreated withHolds
Bus (i2c_master_bus_handle_t)i2c_new_master_busThe port, the SDA and SCL pins, the clock source, glitch filter and pull-up options
Device (i2c_master_dev_handle_t)i2c_master_bus_add_deviceThe 7-bit or 10-bit address and the SCL speed for that device

All the header declarations are in driver/i2c_master.h. The bus owns the hardware controller and serializes transactions from every device handle on it, so several tasks can use different devices on the same bus safely without a mutex of their own. Different devices can have different SCL speeds, and the driver reprograms the controller's timing between transactions.

Create the bus

i2c_bus.cc
#include "driver/i2c_master.h"
#include "esp_log.h"

#define I2C_SDA_PIN  GPIO_NUM_21
#define I2C_SCL_PIN  GPIO_NUM_22

static const char *TAG = "i2c";
static i2c_master_bus_handle_t bus;

esp_err_t i2c_bus_init(void)
{
    const i2c_master_bus_config_t bus_cfg = {
        .i2c_port          = I2C_NUM_0,
        .sda_io_num        = I2C_SDA_PIN,
        .scl_io_num        = I2C_SCL_PIN,
        .clk_source        = I2C_CLK_SRC_DEFAULT,
        .glitch_ignore_cnt = 7,
        .flags.enable_internal_pullup = true,
    };
    return i2c_new_master_bus(&bus_cfg, &bus);
}

i2c_port selects the controller: the ESP32 has two, I2C_NUM_0 and I2C_NUM_1, and -1 lets the driver pick a free one. The default pins GPIO 21 (SDA) and GPIO 22 (SCL) are the usual ones on ESP32 dev boards, but the matrix lets you use almost any GPIO. glitch_ignore_cnt sets how many clock cycles of a pulse the hardware filter ignores; 7 is the value used in the IDF examples and works for ordinary buses. enable_internal_pullup turns on the ESP32's internal pull-ups (around 45 kilohms), which is acceptable for short wires at 100 kHz and not for faster or longer buses; use external 2.2 to 4.7 kilohm resistors for 400 kHz.

Add a device

i2c_device.cc
static i2c_master_dev_handle_t mpu;

esp_err_t mpu_attach(void)
{
    const i2c_device_config_t dev_cfg = {
        .dev_addr_length = I2C_ADDR_BIT_LEN_7,
        .device_address  = 0x68,              /* MPU-6050 with AD0 low */
        .scl_speed_hz    = 400000,
    };
    return i2c_master_bus_add_device(bus, &dev_cfg, &mpu);
}

The address is the 7-bit form, 0x68, not the 8-bit write byte 0xD0. The driver builds the address byte with the read or write bit itself. i2c_master_bus_add_device(bus, &config, &handle) returns the handle used for every later transaction with that chip. Adding two devices with the same address to one bus is allowed by the call but pointless; the second add may return an error depending on the version, since the address must be unique per bus.

Probe before you add

Before relying on a device, check that it answers. The driver provides i2c_master_probe (available since v5.1), which sends the address and returns ESP_OK if it was acknowledged:

i2c_probe.cc
void i2c_scan(void)
{
    for (uint8_t addr = 0x08; addr <= 0x77; addr++) {
        if (i2c_master_probe(bus, addr, 50) == ESP_OK) {
            ESP_LOGI(TAG, "device at 0x%02X", addr);
        }
    }
}
Text
I (321) i2c: device at 0x68

The last argument is the timeout in milliseconds. A return of ESP_ERR_NOT_FOUND means no device acknowledged, and ESP_ERR_TIMEOUT signals a bus problem such as a held line.

Read a register

The most common operation, write a register address and read the answer with a repeated start, is a single call:

i2c_read.cc
esp_err_t mpu_read_reg(uint8_t reg, uint8_t *out, size_t len)
{
    return i2c_master_transmit_receive(mpu, &reg, 1, out, len, 100);
}

void app_main(void)
{
    ESP_ERROR_CHECK(i2c_bus_init());
    ESP_ERROR_CHECK(mpu_attach());

    uint8_t id;
    ESP_ERROR_CHECK(mpu_read_reg(0x75, &id, 1));
    ESP_LOGI(TAG, "WHO_AM_I = 0x%02X", id);
}
Text
I (335) i2c: WHO_AM_I = 0x68

i2c_master_transmit_receive(dev, write_buf, write_size, read_buf, read_size, timeout_ms) sends the write buffer, issues a repeated start, then reads. A timeout of -1 waits forever; use a finite value so a hung bus returns an error instead of freezing the task.

The two single-direction calls are i2c_master_transmit(dev, buf, len, timeout_ms) and i2c_master_receive(dev, buf, len, timeout_ms). A register write needs the register number and the data in one buffer:

i2c_write.cc
esp_err_t mpu_write_reg(uint8_t reg, uint8_t value)
{
    uint8_t buf[2] = { reg, value };
    return i2c_master_transmit(mpu, buf, sizeof buf, 100);
}

/* the MPU-6050 starts in sleep mode: clear the SLEEP bit in PWR_MGMT_1 (0x6B) */
ESP_ERROR_CHECK(mpu_write_reg(0x6B, 0x00));

Then read the 14 bytes starting at ACCEL_XOUT_H (0x3B) in one transaction, using the sensor's auto-increment:

i2c_burst.cc
void mpu_read_motion(void)
{
    uint8_t raw[14];
    ESP_ERROR_CHECK(mpu_read_reg(0x3B, raw, sizeof raw));

    int16_t ax = (int16_t)((raw[0] << 8) | raw[1]);
    int16_t ay = (int16_t)((raw[2] << 8) | raw[3]);
    int16_t az = (int16_t)((raw[4] << 8) | raw[5]);
    int16_t t  = (int16_t)((raw[6] << 8) | raw[7]);

    ESP_LOGI(TAG, "ax=%d ay=%d az=%d temp=%.1f C", ax, ay, az, t / 340.0 + 36.53);
}
Text
I (410) i2c: ax=-312 ay=124 az=16804 temp=29.6 C

The temperature formula raw / 340 + 36.53 is from the MPU-6050 register map. At the default full-scale range of plus or minus 2 g, 16384 counts equal 1 g, so az = 16804 means the board is lying flat with gravity on the Z axis. Your values will differ.

Timeouts, errors and recovery

The driver returns standard esp_err_t codes:

ReturnMeaning
ESP_OKSuccess
ESP_ERR_INVALID_ARGA parameter is wrong, such as a null buffer
ESP_ERR_TIMEOUTThe transaction did not complete in time: bus held, device stretching too long
ESP_ERR_NOT_FOUNDFrom i2c_master_probe: no device acknowledged the address
ESP_ERR_INVALID_STATEThe bus is busy or in an invalid state
Other non-zero codesA NACK or hardware error during a transfer; read the IDF documentation for your version

On a timeout the controller may be left mid-transaction. i2c_master_bus_reset(bus) resets the bus state so the controller can be used again; if a slave still holds SDA low afterwards, run the nine-clock recovery from the dedicated post on stuck buses. Call the reset when a transaction times out and retry once:

i2c_retry.cc
esp_err_t mpu_read_reg_safe(uint8_t reg, uint8_t *out, size_t len)
{
    esp_err_t err = i2c_master_transmit_receive(mpu, &reg, 1, out, len, 100);
    if (err == ESP_ERR_TIMEOUT) {
        i2c_master_bus_reset(bus);
        err = i2c_master_transmit_receive(mpu, &reg, 1, out, len, 100);
    }
    return err;
}

Clock speed and pull-ups

scl_speed_hz is the target SCL frequency for that device, with the driver choosing a divider from the clock source (80 MHz APB on the ESP32 by default). For 400 kHz that divides cleanly. The maximum supported by the hardware is 400 kHz in fast mode on the ESP32; higher rates are not available. If a bus has devices with different maximums, give each its own scl_speed_hz; the driver reconfigures the timing per transaction. The internal pull-ups are only adequate for 100 kHz on a short bus, so for 400 kHz rely on external resistors computed from the bus capacitance, as in the guide.

Mixing with the legacy driver

The old and new drivers cannot manage the same controller at once. A project that links a library which calls i2c_driver_install on I2C_NUM_0 while your code uses i2c_new_master_bus on the same port fails at start-up with a "driver conflict" error. Give each driver its own controller (I2C_NUM_0 and I2C_NUM_1) or migrate the library. When updating older code, the mapping is: i2c_param_config and i2c_driver_install become i2c_new_master_bus; the command-link functions (i2c_cmd_link_create, i2c_master_start and friends) become i2c_master_transmit, i2c_master_receive and i2c_master_transmit_receive; the device address moves from each call into the device config.

Where the new driver is not the right tool

Operations that the three calls cannot express, such as a sequence with several repeated starts in one transaction, are impossible through the new API, where the legacy command links allowed arbitrary sequences. The new driver also needs a heap allocation for each bus and device, so it is not suited to a design that creates and destroys devices constantly. For slave mode use driver/i2c_slave.h (a separate API). And for very long transfers the driver's internal buffers and the controller's FIFO of 32 bytes set a sizing consideration; the driver handles splitting, but each transaction has overhead.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.