ESP-IDF I2C master thread-safe utilities.
One descriptor per I2C device, one bus per port, and a set of read and write
helpers on top of them. The same code runs on the legacy driver/i2c.h and on
the modern driver/i2c_master.h, so a driver written against this library does
not have to care which one the project uses.
- Documentation
- Repository
- Issues
- Discussions and questions
- Component page at the ESP Component Registry
- A device is described by a plain
i2c_dev_tstructure: port, address, pins, clock speed. The fields keep the layout of the deprecatedi2c_config_t, so the drivers of this project (and the home-grown ones written for it) work unchanged. - The bus for a port is created on the first operation and shared by every
device on that port. One port is bound to one pair of pins: an operation
from a device that asks for other pins on the same port fails with
ESP_ERR_INVALID_STATE. - Every device has a mutex, and every transaction is expected to be wrapped
with
I2C_DEV_TAKE_MUTEX()/I2C_DEV_GIVE_MUTEX()(or with the checking macros below), so several tasks may talk to the same device safely. - Transfers are retried up to four times with 20, 40 and 80 ms of backoff, and the device is re-added to the bus before every attempt.
i2cdev_get_shared_handle()hands the bus handle to native ESP-IDF components such asesp_lcd, so both sides can use one bus.- 10-bit addresses are supported where the target has
SOC_I2C_SUPPORT_10BIT_ADDR; elsewhere the address is sent as 7-bit and a warning is logged.
The header is served by two source files, and the build system picks one:
| Implementation | Underlying driver | When it is used |
|---|---|---|
i2cdev.c |
driver/i2c_master.h |
ESP-IDF v5.3 and later, by default |
i2cdev_legacy.c |
driver/i2c.h |
ESP-IDF older than v5.3, or CONFIG_I2CDEV_USE_LEGACY_DRIVER=y |
The public API is the same. The differences are in the details: the legacy
implementation is limited to CONFIG_I2CDEV_MAX_DEVICES_PER_PORT devices per
port and honours timeout_ticks, while the new one keeps a dynamic device list
and ignores that field. CONFIG_I2CDEV_AUTO_ENABLE_PULLUPS affects the new
implementation only.
Two more differences matter when a port is shared:
i2c_master based |
i2cdev_legacy.c |
|
|---|---|---|
| Second device on a port with other pins | ESP_ERR_INVALID_STATE |
the port is reconfigured for the new pins, which moves the wiring for every device already on it |
cfg.master.clk_speed |
set per device | fixed when the driver is installed: the port runs at the speed of the device that installed it, the values of the other devices are ignored and only logged at debug level |
CONFIG_I2CDEV_NOLOCK is a legacy-only option. There it removes every mutex -
the per-device one and the per-port one - and turns the locking macros into
no-ops that do not touch a semaphore at all, so the devices can be read from
interrupt context. The i2c_master based implementation always has its
per-device and per-port mutexes, and a build that selects it with
CONFIG_I2CDEV_NOLOCK=y stops with #error.
#include <i2cdev.h>
static i2c_dev_t sensor = {
.port = 0,
.addr = 0x48,
.cfg = {
.sda_io_num = GPIO_NUM_21,
.scl_io_num = GPIO_NUM_22,
.master.clk_speed = 400000,
},
};
void app_main(void)
{
// Port mutexes. No bus is created here yet.
ESP_ERROR_CHECK(i2cdev_init());
// Per-device mutex. Still no bus access.
ESP_ERROR_CHECK(i2c_dev_create_mutex(&sensor));
// The bus and the device handle appear on the first real transfer.
uint8_t id;
ESP_ERROR_CHECK(i2c_dev_read_reg(&sensor, 0x0F, &id, 1));
// Removes the device from the bus and deletes its mutex.
ESP_ERROR_CHECK(i2c_dev_delete_mutex(&sensor));
// Removes the buses and the port mutexes.
ESP_ERROR_CHECK(i2cdev_done());
}i2cdev_init() creates only the per-port mutexes. The bus for a port is
created by the first operation on that port, and the pins asked for by that
first device become the pins of the port. From then on the bus serves every
device of the port until i2cdev_done() releases it, no matter which of them
is added or removed in between: i2c_dev_delete_mutex() removes the device, not
the bus.
i2cdev_done() walks the ports and their devices, so the descriptors must stay
valid while they are registered: do not copy, move or free an i2c_dev_t that
was used for an operation. Cleanup is best effort. If a bus is still in use
(for example, its handle was handed out and the other component has not
released it), the port is left intact and the call may be repeated.
The bus is serialised by the ESP-IDF driver itself, but a device is not: the descriptor has a mutex, and every transaction on a device must be performed under it.
esp_err_t read_temperature(i2c_dev_t *dev, float *value)
{
uint8_t raw[2];
I2C_DEV_TAKE_MUTEX(dev);
I2C_DEV_CHECK(dev, i2c_dev_read_reg(dev, REG_TEMP, raw, sizeof(raw)));
I2C_DEV_GIVE_MUTEX(dev);
*value = ((raw[0] << 8) | raw[1]) * 0.0625f;
return ESP_OK;
}| Macro | Behaviour |
|---|---|
I2C_DEV_TAKE_MUTEX(dev) |
Takes the mutex, returns on failure |
I2C_DEV_GIVE_MUTEX(dev) |
Releases the mutex, returns on failure |
I2C_DEV_CHECK(dev, call) |
Runs call; on error releases the mutex and returns the error; on success the mutex stays taken |
I2C_DEV_CHECK_LOGE(dev, call, msg, ...) |
Same, and logs the failure through TAG |
CONFIG_I2CDEV_NOLOCK is a legacy-only option: it removes every mutex there,
device and port alike, the macros become no-ops that never touch a semaphore,
and serialisation becomes the caller's job - that is what makes interrupt
context access possible. Bus management, device tracking and the teardown in
i2cdev_done() still happen. The i2c_master based implementation cannot be
built with the option enabled: it always has its mutexes, so the build stops
with #error.
Most projects need nothing from this section. Components that use i2cdev
already share the bus between themselves: i2cdev keeps one bus per port, creates
it on the first operation, and every i2c_dev_t with the same port and pins
works on that bus without any extra call. Three esp-idf-lib sensors on one pair
of pins is the normal case and takes no code at all: create the mutex of each
device, use each under its own mutex, and that is it. A device described with
different pins for a port whose bus already exists is rejected with
ESP_ERR_INVALID_STATE - i2cdev never moves a live bus silently.
The handle below is for the other kind of component: one that does not use i2cdev, talks to the I2C master driver by itself, and therefore would create a second bus on the same pins (which fails) unless it is given the existing one.
Many ESP-IDF components do not know anything about i2cdev: they are built on the
I2C master driver directly and take an i2c_master_bus_handle_t to create their
own devices on it. esp_lcd panels are the usual example, and so are sensors
ported from other projects. Such a component cannot guess the bus that i2cdev
created, so the handle has to be handed to it:
i2cdev_init();
i2c_dev_t sensor = { .port = I2C_NUM_0, .addr = 0x48, .cfg = { /* pins, speed */ } };
i2c_dev_create_mutex(&sensor);
/* The bus is created lazily, by the first operation on the port, so an
* operation has to happen before the handle can be asked for. Whether the
* device answers does not matter here. */
(void)i2c_dev_check_present(&sensor);
i2c_master_bus_handle_t bus;
ESP_ERROR_CHECK(i2cdev_get_shared_handle(I2C_NUM_0, (void **)&bus));
/* The other component joins the bus: */
esp_lcd_new_panel_io_i2c(bus, &io_config, &io_handle);What is shared and what is not:
- the bus lock of the ESP-IDF driver is taken around every transfer, so transactions of i2cdev devices and of the other component never overlap on the wire;
- per-device access stays the caller's job: an
i2c_dev_tmust be used underI2C_DEV_TAKE_MUTEX()/I2C_DEV_GIVE_MUTEX(), and the other component serializes access to its own device handle.
The handle belongs to i2cdev: do not call i2c_del_master_bus() on it. Devices
added by the other component are unknown to i2cdev, so the cleanup order is:
esp_lcd_panel_io_del(io_handle); /* the external device leaves the bus */
i2c_dev_delete_mutex(&sensor); /* the i2cdev device leaves the bus */
i2cdev_done(); /* now the bus is deleted */This requires the new driver. The legacy driver/i2c.h driver owns the port
through i2c_driver_install() and has no bus handle to share, so
i2cdev_get_shared_handle() returns ESP_ERR_NOT_SUPPORTED there, and the legacy
and the new driver cannot coexist on one port. A project that has to share the bus
must use ESP-IDF 5.3 or newer without CONFIG_I2CDEV_USE_LEGACY_DRIVER.
A complete, runnable version of the snippet above is in examples/shared_bus: i2cdev probes its device, a ten-line stand-in for a third-party component adds its own device to the same bus, and the loop uses both.
| Option | Default | Meaning |
|---|---|---|
CONFIG_I2CDEV_USE_LEGACY_DRIVER |
n |
Use driver/i2c.h even on ESP-IDF v5.3 and later |
CONFIG_I2CDEV_AUTO_ENABLE_PULLUPS |
n |
Turn on internal pullups when both pullup flags are zero (new driver only) |
CONFIG_I2CDEV_DEFAULT_SDA_PIN |
21 |
SDA pin used when sda_io_num is -1 |
CONFIG_I2CDEV_DEFAULT_SCL_PIN |
22 |
SCL pin used when scl_io_num is -1 |
CONFIG_I2CDEV_MAX_DEVICES_PER_PORT |
8 |
Devices per port, legacy driver only |
CONFIG_I2CDEV_TIMEOUT |
1000 |
Timeout of a mutex wait and of a transaction, milliseconds |
CONFIG_I2CDEV_NOLOCK |
n |
Remove all mutexes (legacy driver only) |
| Function | Purpose |
|---|---|
i2cdev_init() / i2cdev_done() |
Create the port mutexes / release devices, buses and mutexes |
i2c_dev_create_mutex() / i2c_dev_delete_mutex() |
Register / unregister a device |
i2c_dev_take_mutex() / i2c_dev_give_mutex() |
Lock and unlock a device |
i2c_dev_check_present() / i2c_dev_probe() |
Check that the device ACKs (always at 100 kHz) |
i2c_dev_read() / i2c_dev_write() |
Raw transfers with an optional command prefix |
i2c_dev_read_reg() / i2c_dev_write_reg() |
Transfers with an 8-bit register address |
i2cdev_get_shared_handle() |
Bus handle for native ESP-IDF components |
The full description, with the return codes of every function, is in the
documentation and in
i2cdev.h.
- examples/default scans the buses and lists the addresses that answer.
- examples/shared_bus shows how to give the bus handle to a component that talks to the bus by itself.
idf.py add-dependency esp-idf-lib/i2cdevFor questions and discussions about the component, please use Discussions at esp-idf-lib/core.
Please read CONTRIBUTING.md at esp-idf-lib/core.