1Inter-Integrated Circuit (I2C)
2==============================
3
4:link_to_translation:`zh_CN:[中文]`
5
6Overview
7--------
8
9I2C is a serial, synchronous, half-duplex communication protocol that allows co-existence of multiple masters and slaves on the same bus. The I2C bus consists of two lines: serial data line (SDA) and serial clock (SCL). Both lines require pull-up resistors.
10
11With such advantages as simplicity and low manufacturing cost, I2C is mostly used for communication of low-speed peripheral devices over short distances (within one foot).
12
13.. only:: esp32c3
14
15    {IDF_TARGET_NAME} has only one I2C controller (also referred to as port) which is responsible for handling communications on I2C bus. The I2C controller can operate as master or slave.
16
17.. only:: not esp32c3
18
19    {IDF_TARGET_NAME} has two I2C controllers (also referred to as ports) which are responsible for handling communications on the I2C bus. Each I2C controller can operate as master or slave. As an example, one controller can act as a master and the other as a slave at the same time.
20
21Driver Features
22---------------
23
24I2C driver governs communications of devices over the I2C bus. The driver supports the following features:
25
26- Reading and writing bytes in Master mode
27- Slave mode
28- Reading and writing to registers which are in turn read/written by the master
29
30
31Driver Usage
32------------
33
34The following sections describe typical steps of configuring and operating the I2C driver:
35
361. :ref:`i2c-api-configure-driver` - set the initialization parameters (master or slave mode, GPIO pins for SDA and SCL, clock speed, etc.)
372. :ref:`i2c-api-install-driver`- activate the driver on one of the two I2C controllers as a master or slave
383. Depending on whether you configure the driver for a master or slave, choose the appropriate item
39
40   a) :ref:`i2c-api-master-mode` - handle communications (master)
41   b) :ref:`i2c-api-slave-mode` - respond to messages from the master (slave)
42
434. :ref:`i2c-api-interrupt-handling` - configure and service I2C interrupts
445. :ref:`i2c-api-customized-configuration` - adjust default I2C communication parameters (timings, bit order, etc.)
456. :ref:`i2c-api-error-handling` - how to recognize and handle driver configuration and communication errors
467. :ref:`i2c-api-delete-driver`- release resources used by the I2C driver when communication ends
47
48
49.. _i2c-api-configure-driver:
50
51Configuration
52^^^^^^^^^^^^^
53
54To establish I2C communication, start by configuring the driver. This is done by setting the parameters of the structure :cpp:type:`i2c_config_t`:
55
56- Set I2C **mode of operation** - slave or master from :cpp:type:`i2c_mode_t`
57- Configure **communication pins**
58
59    - Assign GPIO pins for SDA and SCL signals
60    - Set whether to enable {IDF_TARGET_NAME}'s internal pull-ups
61
62- (Master only) Set I2C **clock speed**
63- (Slave only) Configure the following
64
65    * Whether to enable **10 bit address mode**
66    * Define **slave address**
67
68After that, initialize the configuration for a given I2C port. For this, call the function :cpp:func:`i2c_param_config` and pass to it the port number and the structure :cpp:type:`i2c_config_t`.
69
70Configuration example (master):
71
72.. code-block:: c
73
74    int i2c_master_port = 0;
75    i2c_config_t conf = {
76        .mode = I2C_MODE_MASTER,
77        .sda_io_num = I2C_MASTER_SDA_IO,         // select GPIO specific to your project
78        .sda_pullup_en = GPIO_PULLUP_ENABLE,
79        .scl_io_num = I2C_MASTER_SCL_IO,         // select GPIO specific to your project
80        .scl_pullup_en = GPIO_PULLUP_ENABLE,
81        .master.clk_speed = I2C_MASTER_FREQ_HZ,  // select frequency specific to your project
82        // .clk_flags = 0,          /*!< Optional, you can use I2C_SCLK_SRC_FLAG_* flags to choose i2c source clock here. */
83    };
84
85Configuration example (slave):
86
87.. code-block:: c
88
89    int i2c_slave_port = I2C_SLAVE_NUM;
90    i2c_config_t conf_slave = {
91        .sda_io_num = I2C_SLAVE_SDA_IO,          // select GPIO specific to your project
92        .sda_pullup_en = GPIO_PULLUP_ENABLE,
93        .scl_io_num = I2C_SLAVE_SCL_IO,          // select GPIO specific to your project
94        .scl_pullup_en = GPIO_PULLUP_ENABLE,
95        .mode = I2C_MODE_SLAVE,
96        .slave.addr_10bit_en = 0,
97        .slave.slave_addr = ESP_SLAVE_ADDR,      // address of your project
98    };
99
100At this stage, :cpp:func:`i2c_param_config` also sets a few other I2C configuration parameters to default values that are defined by the I2C specification. For more details on the values and how to modify them, see :ref:`i2c-api-customized-configuration`.
101
102Source Clock Configuration
103^^^^^^^^^^^^^^^^^^^^^^^^^^
104
105**Clock sources allocator** is added for supporting different clock sources. The clock allocator will choose one clock source that meets all the requirements of frequency and capability (as requested in :cpp:member:`i2c_config_t::clk_flags`).
106
107When :cpp:member:`i2c_config_t::clk_flags` is 0, the clock allocator will select only according to the desired frequency. If no special capabilities are needed, such as APB, you can configure the clock allocator to select the source clock only according to the desired frequency. For this, set :cpp:member:`i2c_config_t::clk_flags` to 0. For clock characteristics, see the table below.
108
109.. note::
110
111    A clock is not a valid option, if it doesn't meet the requested capabilities, i.e. any bit of requested capabilities (clk_flags) is 0 in the clock's capabilities.
112
113.. only:: esp32
114
115    .. list-table:: Characteristics of {IDF_TARGET_NAME} clock sources
116       :widths: 5 5 50 20
117       :header-rows: 1
118
119       * - Clock name
120         - Clock frequency
121         - MAX freq for SCL
122         - Clock capabilities
123       * - APB clock
124         - 80 MHz
125         - 4 MHz
126         - /
127
128.. only:: esp32s2
129
130    .. list-table:: Characteristics of {IDF_TARGET_NAME} clock sources
131       :widths: 5 5 50 100
132       :header-rows: 1
133
134       * - Clock name
135         - Clock frequency
136         - MAX freq for SCL
137         - Clock capabilities
138       * - APB clock
139         - 80 MHz
140         - 4 MHz
141         - /
142       * - REF_TICK
143         - 1 MHz
144         - 50 KHz
145         - :c:macro:`I2C_SCLK_SRC_FLAG_AWARE_DFS`, :c:macro:`I2C_SCLK_SRC_FLAG_LIGHT_SLEEP`
146
147    Explanations for :cpp:member:`i2c_config_t::clk_flags` are as follows:
148    1. :c:macro:`I2C_SCLK_SRC_FLAG_AWARE_DFS`: Clock's baud rate will not change while APB clock is changing.
149    2. :c:macro:`I2C_SCLK_SRC_FLAG_LIGHT_SLEEP`: It supports Light-sleep mode, which APB clock cannot do.
150
151.. only:: esp32s3
152
153    .. list-table:: Characteristics of {IDF_TARGET_NAME} clock sources
154       :widths: 5 5 50 20
155       :header-rows: 1
156
157       * - Clock name
158         - Clock frequency
159         - MAX freq for SCL
160         - Clock capabilities
161       * - XTAL clock
162         - 40 MHz
163         - 2 MHz
164         - /
165       * - RTC clock
166         - 20 MHz
167         - 1 MHz
168         - :c:macro:`I2C_SCLK_SRC_FLAG_AWARE_DFS`, :c:macro:`I2C_SCLK_SRC_FLAG_LIGHT_SLEEP`
169
170.. only:: esp32c3
171
172    .. list-table:: Characteristics of {IDF_TARGET_NAME} clock sources
173       :widths: 5 5 50 100
174       :header-rows: 1
175
176       * - Clock name
177         - Clock frequency
178         - MAX freq for SCL
179         - Clock capabilities
180       * - XTAL clock
181         - 40 MHz
182         - 2 MHz
183         - /
184       * - RTC clock
185         - 20 MHz
186         - 1 MHz
187         - :c:macro:`I2C_SCLK_SRC_FLAG_AWARE_DFS`, :c:macro:`I2C_SCLK_SRC_FLAG_LIGHT_SLEEP`
188
189Explanations for :cpp:member:`i2c_config_t::clk_flags` are as follows:
190
1911. :c:macro:`I2C_SCLK_SRC_FLAG_AWARE_DFS`: Clock's baud rate will not change while APB clock is changing.
1922. :c:macro:`I2C_SCLK_SRC_FLAG_LIGHT_SLEEP`: It supports Light-sleep mode, which APB clock cannot do.
1933. Some flags may not be supported on {IDF_TARGET_NAME}, reading technical reference manual before using it.
194
195.. note::
196
197    The clock frequency of SCL in master mode should not be lager than max frequency for SCL mentioned in the table above.
198
199.. _i2c-api-install-driver:
200
201Install Driver
202^^^^^^^^^^^^^^
203
204After the I2C driver is configured, install it by calling the function :cpp:func:`i2c_driver_install` with the following parameters:
205
206- Port number, one of the two port numbers from :cpp:type:`i2c_port_t`
207- Master or slave, selected from :cpp:type:`i2c_mode_t`
208- (Slave only) Size of buffers to allocate for sending and receiving data. As I2C is a master-centric bus, data can only go from the slave to the master at the master's request. Therefore, the slave will usually have a send buffer where the slave application writes data. The data remains in the send buffer to be read by the master at the master's own discretion.
209- Flags for allocating the interrupt (see ESP_INTR_FLAG_* values in :component_file:`esp_hw_support/include/esp_intr_alloc.h`)
210
211.. _i2c-api-master-mode:
212
213Communication as Master
214^^^^^^^^^^^^^^^^^^^^^^^
215
216After installing the I2C driver, {IDF_TARGET_NAME} is ready to communicate with other I2C devices.
217
218{IDF_TARGET_NAME}'s I2C controller operating as master is responsible for establishing communication with I2C slave devices and sending commands to trigger a slave to action, for example, to take a measurement and send the readings back to the master.
219
220For better process organization, the driver provides a container, called a "command link", that should be populated with a sequence of commands and then passed to the I2C controller for execution.
221
222
223Master Write
224""""""""""""
225
226The example below shows how to build a command link for an I2C master to send *n* bytes to a slave.
227
228.. blockdiag:: ../../../_static/diagrams/i2c-command-link-master-write-blockdiag.diag
229    :scale: 100
230    :caption: I2C command link - master write example
231    :align: center
232
233
234The following describes how a command link for a "master write" is set up and what comes inside:
235
2361. Create a command link with :cpp:func:`i2c_cmd_link_create`.
237
238    Then, populate it with the series of data to be sent to the slave:
239
240   a) **Start bit** - :cpp:func:`i2c_master_start`
241   b) **Slave address** - :cpp:func:`i2c_master_write_byte`. The single byte address is provided as an argument of this function call.
242   c) **Data** - One or more bytes as an argument of :cpp:func:`i2c_master_write`
243   d) **Stop bit** - :cpp:func:`i2c_master_stop`
244
245    Both functions :cpp:func:`i2c_master_write_byte` and :cpp:func:`i2c_master_write` have an additional argument specifying whether the master should ensure that it has received the ACK bit.
246
2472. Trigger the execution of the command link by I2C controller by calling :cpp:func:`i2c_master_cmd_begin`. Once the execution is triggered, the command link cannot be modified.
2483. After the commands are transmitted, release the resources used by the command link by calling :cpp:func:`i2c_cmd_link_delete`.
249
250
251Master Read
252"""""""""""
253
254The example below shows how to build a command link for an I2C master to read *n* bytes from a slave.
255
256.. blockdiag:: ../../../_static/diagrams/i2c-command-link-master-read-blockdiag.diag
257    :scale: 100
258    :caption: I2C command link - master read example
259    :align: center
260
261
262Compared to writing data, the command link is populated in Step 4 not with ``i2c_master_write...`` functions but with :cpp:func:`i2c_master_read_byte` and / or :cpp:func:`i2c_master_read`. Also, the last read in Step 5 is configured so that the master does not provide the ACK bit.
263
264
265Indicating Write or Read
266""""""""""""""""""""""""
267
268After sending a slave address (see Step 3 on both diagrams above), the master either writes or reads from the slave.
269
270The information on what the master will actually do is hidden in the least significant bit of the slave's address.
271
272For this reason, the command link sent by the master to write data to the slave contains the address ``(ESP_SLAVE_ADDR << 1) | I2C_MASTER_WRITE`` and looks as follows:
273
274.. code-block:: c
275
276    i2c_master_write_byte(cmd, (ESP_SLAVE_ADDR << 1) | I2C_MASTER_WRITE, ACK_EN);
277
278Likewise, the command link to read from the slave looks as follows:
279
280.. code-block:: c
281
282    i2c_master_write_byte(cmd, (ESP_SLAVE_ADDR << 1) | I2C_MASTER_READ, ACK_EN);
283
284
285.. _i2c-api-slave-mode:
286
287Communication as Slave
288^^^^^^^^^^^^^^^^^^^^^^
289
290After installing the I2C driver, {IDF_TARGET_NAME} is ready to communicate with other I2C devices.
291
292The API provides the following functions for slaves
293
294- :cpp:func:`i2c_slave_read_buffer`
295
296    Whenever the master writes data to the slave, the slave will automatically store it in the receive buffer. This allows the slave application to call the function :cpp:func:`i2c_slave_read_buffer` at its own discretion. This function also has a parameter to specify block time if no data is in the receive buffer. This will allow the slave application to wait with a specified timeout for data to arrive to the buffer.
297
298- :cpp:func:`i2c_slave_write_buffer`
299
300    The send buffer is used to store all the data that the slave wants to send to the master in FIFO order. The data stays there until the master requests for it. The function :cpp:func:`i2c_slave_write_buffer` has a parameter to specify block time if the send buffer is full. This will allow the slave application to wait with a specified timeout for the adequate amount of space to become available in the send buffer.
301
302A code example showing how to use these functions can be found in :example:`peripherals/i2c`.
303
304
305.. _i2c-api-interrupt-handling:
306
307Interrupt Handling
308^^^^^^^^^^^^^^^^^^
309
310During driver installation, an interrupt handler is installed by default. However, you can register your own interrupt handler instead of the default one by calling the function :cpp:func:`i2c_isr_register`. When implementing your own interrupt handler, refer to *{IDF_TARGET_NAME} Technical Reference Manual* > *I2C Controller (I2C)* > *Interrupts* [`PDF <{IDF_TARGET_TRM_EN_URL}#i2c>`__] for the description of interrupts triggered by the I2C controller.
311
312To delete an interrupt handler, call :cpp:func:`i2c_isr_free`.
313
314.. _i2c-api-customized-configuration:
315
316Customized Configuration
317^^^^^^^^^^^^^^^^^^^^^^^^
318
319As mentioned at the end of Section :ref:`i2c-api-configure-driver`, when the function :cpp:func:`i2c_param_config` initializes the driver configuration for an I2C port, it also sets several I2C communication parameters to default values defined in the `I2C specification <https://www.nxp.com/docs/en/user-guide/UM10204.pdf>`_. Some other related parameters are pre-configured in registers of the I2C controller.
320
321All these parameters can be changed to user-defined values by calling dedicated functions given in the table below. Please note that the timing values are defined in APB clock cycles. The frequency of APB is specified in :cpp:type:`I2C_APB_CLK_FREQ`.
322
323.. list-table:: Other Configurable I2C Communication Parameters
324   :widths: 65 35
325   :header-rows: 1
326
327   * - Parameters to Change
328     - Function
329   * - High time and low time for SCL pulses
330     - :cpp:func:`i2c_set_period`
331   * - SCL and SDA signal timing used during generation of **start** signals
332     - :cpp:func:`i2c_set_start_timing`
333   * - SCL and SDA signal timing used during generation of **stop** signals
334     - :cpp:func:`i2c_set_stop_timing`
335   * - Timing relationship between SCL and SDA signals when slave samples, as well as when master toggles
336     - :cpp:func:`i2c_set_data_timing`
337   * - I2C timeout
338     - :cpp:func:`i2c_set_timeout`
339   * - Choice between transmitting / receiving the LSB or MSB first, choose one of the modes defined in :cpp:type:`i2c_trans_mode_t`
340     - :cpp:func:`i2c_set_data_mode`
341
342
343Each of the above functions has a *_get_* counterpart to check the currently set value. For example, to check the I2C timeout value, call :cpp:func:`i2c_get_timeout`.
344
345To check the default parameter values which are set during the driver configuration process, please refer to the file :component_file:`driver/i2c.c` and look for defines with the suffix ``_DEFAULT``.
346
347You can also select different pins for SDA and SCL signals and alter the configuration of pull-ups with the function :cpp:func:`i2c_set_pin`. If you want to modify already entered values, use the function :cpp:func:`i2c_param_config`.
348
349.. note::
350
351    {IDF_TARGET_NAME}'s internal pull-ups are in the range of tens of kOhm, which is, in most cases, insufficient for use as I2C pull-ups. Users are advised to use external pull-ups with values described in the `I2C specification <https://www.nxp.com/docs/en/user-guide/UM10204.pdf>`_.
352
353
354.. _i2c-api-error-handling:
355
356Error Handling
357^^^^^^^^^^^^^^
358
359The majority of I2C driver functions either return ``ESP_OK`` on successful completion or a specific error code on failure. It is a good practice to always check the returned values and implement error handling. The driver also prints out log messages that contain error details, e.g., when checking the validity of entered configuration. For details please refer to the file :component_file:`driver/i2c.c` and look for defines with the suffix ``_ERR_STR``.
360
361Use dedicated interrupts to capture communication failures. For instance, if a slave stretches the clock for too long while preparing the data to send back to master, the interrupt ``I2C_TIME_OUT_INT`` will be triggered. For detailed information, see :ref:`i2c-api-interrupt-handling`.
362
363In case of a communication failure, you can reset the internal hardware buffers by calling the functions :cpp:func:`i2c_reset_tx_fifo` and :cpp:func:`i2c_reset_rx_fifo` for the send and receive buffers respectively.
364
365
366.. _i2c-api-delete-driver:
367
368Delete Driver
369^^^^^^^^^^^^^
370
371When the I2C communication is established with the function :cpp:func:`i2c_driver_install` and is not required for some substantial amount of time, the driver may be deinitialized to release allocated resources by calling :cpp:func:`i2c_driver_delete`.
372
373Before calling :cpp:func:`i2c_driver_delete` to remove i2c driver, please make sure that all threads have stopped using the driver in any way, because this function does not guarantee thread safety.
374
375Application Example
376-------------------
377
378I2C master and slave example: :example:`peripherals/i2c`.
379
380
381API Reference
382-------------
383
384.. include-build-file:: inc/i2c.inc
385.. include-build-file:: inc/i2c_types.inc
386