i2c.rst 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548
  1. Inter-Integrated Circuit (I2C)
  2. ==============================
  3. Introduction
  4. ------------
  5. I2C is a serial, synchronous, multi-device, half-duplex communication protocol that allows co-existence of multiple masters and slaves on the same bus. I2C uses two bidirectional open-drain lines: serial data line (SDA) and serial clock line (SCL), pulled up by resistors.
  6. {IDF_TARGET_NAME} has {IDF_TARGET_SOC_I2C_NUM} I2C controller (also called port), responsible for handling communication on the I2C bus. A single I2C controller can be a master or a slave.
  7. Typically, an I2C slave device has a 7-bit address or 10-bit address. {IDF_TARGET_NAME} supports both I2C Standard-mode (Sm) and Fast-mode (Fm) which can go up to 100KHz and 400KHz respectively.
  8. .. warning::
  9. The clock frequency of SCL in master mode should not be larger than 400 KHz
  10. .. note::
  11. The frequency of SCL is influenced by both the pull-up resistor and the wire capacitance. Therefore, users are strongly recommended to choose appropriate pull-up resistors to make the frequency accurate. The recommended value for pull-up resistors usually ranges from 1K Ohms to 10K Ohms.
  12. Keep in mind that the higher the frequency, the smaller the pull-up resistor should be (but not less than 1 KOhms). Indeed, large resistors will decline the current, which will increase the clock switching time and reduce the frequency. We usually recommend a range of 2 KOhms to 5 KOhms, but users may also need to make some adjustments depending on their current draw requirements.
  13. I2C Clock Configuration
  14. -----------------------
  15. .. list::
  16. - :cpp:enumerator:`i2c_clock_source_t::I2C_CLK_SRC_DEFAULT`: Default I2C source clock.
  17. :SOC_I2C_SUPPORT_XTAL: - :cpp:enumerator:`i2c_clock_source_t::I2C_CLK_SRC_XTAL`: External crystal for I2C clock source.
  18. :SOC_I2C_SUPPORT_RTC: - :cpp:enumerator:`i2c_clock_source_t::I2C_CLK_RC_FAST`: Internal 20MHz rc oscillator for I2C clock source.
  19. :SOC_I2C_SUPPORT_APB: - :cpp:enumerator:`i2c_clock_source_t::I2C_CLK_SRC_APB`: APB clock as I2C clock source.
  20. :SOC_I2C_SUPPORT_REF_TICK: - :cpp:enumerator:`i2c_clock_source_t::I2C_CLK_SRC_REF_TICK`: 1MHZ clock.
  21. I2C File Structure
  22. ------------------
  23. .. figure:: ../../../_static/diagrams/i2c/i2c_code_structure.png
  24. :align: center
  25. :alt: I2C file structure
  26. I2C file structure
  27. **Public headers that need to be included in the I2C application**
  28. - ``i2c.h``: The header file of legacy I2C APIs (for apps using legacy driver).
  29. - ``i2c_master.h``: The header file that provides standard communication mode specific APIs (for apps using new driver with master mode).
  30. - ``i2c_slave.h``: The header file that provides standard communication mode specific APIs (for apps using new driver with slave mode).
  31. .. note::
  32. The legacy driver can't coexist with the new driver. Include ``i2c.h`` to use the legacy driver or the other two headers to use the new driver. Please keep in mind that the legacy driver is now deprecated and will be removed in future.
  33. **Public headers that have been included in the headers above**
  34. - ``i2c_types_legacy.h``: The legacy public types that only used in the legacy driver.
  35. - ``i2c_types.h``: The header file that provides public types.
  36. Functional Overview
  37. -------------------
  38. The I2C driver offers following services:
  39. - `Resource Allocation <#resource-allocation>`__ - covers how to allocate I2C bus with properly set of configurations. It also covers how to recycle the resources when they finished working.
  40. - `I2C Master Controller <#i2c_master_controller>`__ - covers behavior of I2C master controller. Introduce data transmit, data receive, and data transmit and receive.
  41. - `I2C Slave Controller <#i2c_slave_controller>`__ - covers behavior of I2C slave controller. Involve data transmit and data receive.
  42. - `Power Management <#power-management>`__ - describes how different source clock will affect power consumption.
  43. - `IRAM Safe <#iram-safe>`__ - describes tips on how to make the I2C interrupt work better along with a disabled cache.
  44. - `Thread Safety <#thread-safety>`__ - lists which APIs are guaranteed to be thread safe by the driver.
  45. - `Kconfig Options <#kconfig-options>`__ - lists the supported Kconfig options that can bring different effects to the driver.
  46. Resource Allocation
  47. ^^^^^^^^^^^^^^^^^^^
  48. Both I2C master bus and I2C slave bus, when supported, are represented by :cpp:type:`i2c_bus_handle_t` in the driver. The available ports are managed in a resource pool that allocates a free port on request.
  49. Install I2C master bus and device
  50. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  51. The I2C master is designed based on bus-device model. So :cpp:type:`i2c_master_bus_config_t` and :cpp:type:`i2c_device_config_t` are required separately to allocate the I2C master bus instance and I2C device instance.
  52. .. figure:: ../../../_static/diagrams/i2c/i2c_master_module.png
  53. :align: center
  54. :alt: I2C master bus-device module
  55. I2C master bus-device module
  56. I2C master bus requires the configuration that specified by :cpp:type:`i2c_master_bus_config_t`:
  57. - :cpp:member:`i2c_master_bus_config_t::i2c_port` sets the I2C port used by the controller.
  58. - :cpp:member:`i2c_master_bus_config_t::sda_io_num` sets the GPIO number for the serial data bus (SDA).
  59. - :cpp:member:`i2c_master_bus_config_t::scl_io_num` sets the GPIO number for the serial clock bus (SCL).
  60. - :cpp:member:`i2c_master_bus_config_t::clk_source` selects the source clock for I2C bus. The available clocks are listed in :cpp:type:`i2c_clock_source_t`. For the effect on power consumption of different clock source, please refer to `Power Management <#power-management>`__ section.
  61. - :cpp:member:`i2c_master_bus_config_t::glitch_ignore_cnt` sets the glitch period of master bus, if the glitch period on the line is less than this value, it can be filtered out, typically value is 7.
  62. - :cpp:member:`i2c_master_bus_config_t::intr_priority` Set the priority of the interrupt. If set to ``0`` , then the driver will use a interrupt with low or medium priority (priority level may be one of 1,2 or 3), otherwise use the priority indicated by :cpp:member:`i2c_master_bus_config_t::intr_priority` Please use the number form (1,2,3) , not the bitmask form ((1<<1),(1<<2),(1<<3)).
  63. - :cpp:member:`i2c_master_bus_config_t::trans_queue_depth` Depth of internal transfer queue. Only valid in asynchronous transaction.
  64. - :cpp:member:`i2c_master_bus_config_t::enable_internal_pullup` Enable internal pullups. Note: This is not strong enough to pullup buses under high-speed frequency. A suitable external pullup is recommended.
  65. If the configurations in :cpp:type:`i2c_master_bus_config_t` is specified, users can call :cpp:func:`i2c_new_master_bus` to allocate and initialize an I2C master bus. This function will return an I2C bus handle if it runs correctly. Specifically, when there are no more I2C port available, this function will return :c:macro:`ESP_ERR_NOT_FOUND` error.
  66. I2C master device requires the configuration that specified by :cpp:type:`i2c_device_config_t`:
  67. - :cpp:member:`i2c_device_config_t::dev_addr_length` configure the address bit length of the slave device. User can choose from enumerator :cpp:enumerator:`I2C_ADDR_BIT_LEN_7` or :cpp:enumerator:`I2C_ADDR_BIT_LEN_10` (if supported).
  68. - :cpp:member:`i2c_device_config_t::device_address` I2C device raw address. Please parse the device address to this member directly. For example, the device address is 0x28, then parse 0x28 to :cpp:member:`i2c_device_config_t::device_address`, don't carry a write/read bit.
  69. - :cpp:member:`i2c_device_config_t::scl_speed_hz` set the scl line frequency of this device.
  70. Once the :cpp:type:`i2c_device_config_t` structure is populated with mandatory parameters, users can call :cpp:func:`i2c_master_bus_add_device` to allocate an I2C device instance and mounted to the master bus then. This function will return an I2C device handle if it runs correctly. Specifically, when the I2C bus is not initialized properly, calling this function will result in a :c:macro:`ESP_ERR_INVALID_ARG` error.
  71. .. code:: c
  72. #include "driver/i2c_master.h"
  73. i2c_master_bus_config_t i2c_mst_config = {
  74. .clk_source = I2C_CLK_SRC_DEFAULT,
  75. .i2c_port = TEST_I2C_PORT,
  76. .scl_io_num = I2C_MASTER_SCL_IO,
  77. .sda_io_num = I2C_MASTER_SDA_IO,
  78. .glitch_ignore_cnt = 7,
  79. .flags.enable_internal_pullup = true,
  80. };
  81. i2c_master_bus_handle_t bus_handle;
  82. ESP_ERROR_CHECK(i2c_new_master_bus(&i2c_mst_config, &bus_handle));
  83. i2c_device_config_t dev_cfg = {
  84. .dev_addr_length = I2C_ADDR_BIT_LEN_7,
  85. .device_address = 0x58,
  86. .scl_speed_hz = 100000,
  87. };
  88. i2c_master_dev_handle_t dev_handle;
  89. ESP_ERROR_CHECK(i2c_master_bus_add_device(bus_handle, &dev_cfg, &dev_handle));
  90. Uninstall I2C master bus and device
  91. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  92. If a previously installed I2C bus or device is no longer needed, it's recommended to recycle the resource by calling :cpp:func:`i2c_master_bus_rm_device` or :cpp:func:`i2c_del_master_bus`, so that to release the underlying hardware.
  93. Install I2C slave device
  94. ~~~~~~~~~~~~~~~~~~~~~~~~
  95. I2C slave requires the configuration that specified by :cpp:type:`i2c_slave_config_t`:
  96. .. list::
  97. - :cpp:member:`i2c_slave_config_t::i2c_port` sets the I2C port used by the controller.
  98. - :cpp:member:`i2c_slave_config_t::sda_io_num` sets the GPIO number for serial data bus (SDA).
  99. - :cpp:member:`i2c_slave_config_t::scl_io_num` sets the GPIO number for serial clock bus (SCL).
  100. - :cpp:member:`i2c_slave_config_t::clk_source` selects the source clock for I2C bus. The available clocks are listed in :cpp:type:`i2c_clock_source_t`. For the effect on power consumption of different clock source, please refer to `Power Management <#power-management>`__ section.
  101. - :cpp:member:`i2c_slave_config_t::send_buf_depth` sets the sending buffer length.
  102. - :cpp:member:`i2c_slave_config_t::slave_addr` sets the slave address
  103. - :cpp:member:`i2c_master_bus_config_t::intr_priority` Set the priority of the interrupt. If set to ``0`` , then the driver will use a interrupt with low or medium priority (priority level may be one of 1,2 or 3), otherwise use the priority indicated by :cpp:member:`i2c_master_bus_config_t::intr_priority` Please use the number form (1,2,3) , not the bitmask form ((1<<1),(1<<2),(1<<3)). Please pay attention that once the interrupt priority is set, it cannot be changed until :cpp:func:`i2c_del_master_bus` is called.
  104. - :cpp:member:`i2c_slave_config_t::addr_bit_len` sets true if you need the slave to have a 10-bit address.
  105. :SOC_I2C_SLAVE_CAN_GET_STRETCH_CAUSE: - :cpp:member:`i2c_slave_config_t::stretch_en` Set true if you want the slave controller stretch works, please refer to [`TRM <{IDF_TARGET_TRM_EN_URL}#i2c>`__] to learn how I2C stretch works.
  106. :SOC_I2C_SLAVE_CAN_GET_STRETCH_CAUSE: - :cpp:member:`i2c_slave_config_t::broadcast_en` Set true to enable the slave broadcase. When the slave receives the general call address 0x00 from the master and the R/W bit followed is 0, it responds to the master regardless of its own address.
  107. :SOC_I2C_SLAVE_SUPPORT_I2CRAM_ACCESS: - :cpp:member:`i2c_slave_config_t::access_ram_en` Set true to enable the non-fifo mode. Thus the I2C data fifo can be used as RAM, and double addressing will be synchronised opened.
  108. :SOC_I2C_SLAVE_SUPPORT_SLAVE_UNMATCH: - :cpp:member:`i2c_slave_config_t::slave_unmatch_en` Set true to enable the slave unmatch interrupt. If master send command address cannot match the slave address, and unmatch interrupt will be triggered.
  109. Once the :cpp:type:`i2c_slave_config_t` structure is populated with mandatory parameters, users can call :cpp:func:`i2c_new_slave_device` to allocate and initialize an I2C master bus. This function will return an I2C bus handle if it runs correctly. Specifically, when there are no more I2C port available, this function will return :c:macro:`ESP_ERR_NOT_FOUND` error.
  110. .. code:: c
  111. i2c_slave_config_t i2c_slv_config = {
  112. .addr_bit_len = I2C_ADDR_BIT_LEN_7,
  113. .clk_source = I2C_CLK_SRC_DEFAULT,
  114. .i2c_port = TEST_I2C_PORT,
  115. .send_buf_depth = 256,
  116. .scl_io_num = I2C_SLAVE_SCL_IO,
  117. .sda_io_num = I2C_SLAVE_SDA_IO,
  118. .slave_addr = 0x58,
  119. };
  120. i2c_slave_dev_handle_t slave_handle;
  121. ESP_ERROR_CHECK(i2c_new_slave_device(&i2c_slv_config, &slave_handle));
  122. Uninstall I2C slave device
  123. ~~~~~~~~~~~~~~~~~~~~~~~~~~
  124. If a previously installed I2C bus is no longer needed, it's recommended to recycle the resource by calling :cpp:func:`i2c_del_slave_device`, so that to release the underlying hardware.
  125. I2C Master Controller
  126. ^^^^^^^^^^^^^^^^^^^^^
  127. After installing the i2c master driver by :cpp:func:`i2c_new_master_bus`, {IDF_TARGET_NAME} is ready to communicate with other I2C devices. I2C APIs allow the standard transactions. Like the wave as follows:
  128. .. wavedrom:: /../_static/diagrams/i2c/i2c_trans_wave.json
  129. I2C Master Write
  130. ~~~~~~~~~~~~~~~~
  131. After installing I2C master bus successfully, you can simply call :cpp:func:`i2c_master_transmit` to write data to the slave device. The principle of this function can be explained by following chart.
  132. In order to organize the process, the driver uses a command link, that should be populated with a sequence of commands and then passed to I2C controller for execution.
  133. .. figure:: ../../../_static/diagrams/i2c/i2c_master_write_slave.png
  134. :align: center
  135. :alt: I2C master write to slave
  136. I2C master write to slave
  137. Simple example for writing data to slave:
  138. .. code:: c
  139. #define DATA_LENGTH 100
  140. i2c_master_bus_config_t i2c_mst_config = {
  141. .clk_source = I2C_CLK_SRC_DEFAULT,
  142. .i2c_port = I2C_PORT_NUM_0,
  143. .scl_io_num = I2C_MASTER_SCL_IO,
  144. .sda_io_num = I2C_MASTER_SDA_IO,
  145. .glitch_ignore_cnt = 7,
  146. };
  147. i2c_master_bus_handle_t bus_handle;
  148. ESP_ERROR_CHECK(i2c_new_master_bus(&i2c_mst_config, &bus_handle));
  149. i2c_device_config_t dev_cfg = {
  150. .dev_addr_length = I2C_ADDR_BIT_LEN_7,
  151. .device_address = 0x58,
  152. .scl_speed_hz = 100000,
  153. };
  154. i2c_master_dev_handle_t dev_handle;
  155. ESP_ERROR_CHECK(i2c_master_bus_add_device(bus_handle, &dev_cfg, &dev_handle));
  156. ESP_ERROR_CHECK(i2c_master_transmit(dev_handle, data_wr, DATA_LENGTH, -1));
  157. I2C Master Read
  158. ~~~~~~~~~~~~~~~
  159. After installing I2C master bus successfully, you can simply call :cpp:func:`i2c_master_receive` to read data from the slave device. The principle of this function can be explained by following chart.
  160. .. figure:: ../../../_static/diagrams/i2c/i2c_master_read_slave.png
  161. :align: center
  162. :alt: I2C master read from slave
  163. I2C master read from slave
  164. Simple example for reading data from slave:
  165. .. code:: c
  166. #define DATA_LENGTH 100
  167. i2c_master_bus_config_t i2c_mst_config = {
  168. .clk_source = I2C_CLK_SRC_DEFAULT,
  169. .i2c_port = I2C_PORT_NUM_0,
  170. .scl_io_num = I2C_MASTER_SCL_IO,
  171. .sda_io_num = I2C_MASTER_SDA_IO,
  172. .glitch_ignore_cnt = 7,
  173. };
  174. i2c_master_bus_handle_t bus_handle;
  175. ESP_ERROR_CHECK(i2c_new_master_bus(&i2c_mst_config, &bus_handle));
  176. i2c_device_config_t dev_cfg = {
  177. .dev_addr_length = I2C_ADDR_BIT_LEN_7,
  178. .device_address = 0x58,
  179. .scl_speed_hz = 100000,
  180. };
  181. i2c_master_dev_handle_t dev_handle;
  182. ESP_ERROR_CHECK(i2c_master_bus_add_device(bus_handle, &dev_cfg, &dev_handle));
  183. i2c_master_receive(dev_handle, data_rd, DATA_LENGTH, -1);
  184. I2C Master Write and Read
  185. ~~~~~~~~~~~~~~~~~~~~~~~~~
  186. Some I2C device needs write configurations before reading data from it, therefore, an interface called :cpp:func:`i2c_master_transmit_receive` can help. The principle of this function can be explained by following chart.
  187. .. figure:: ../../../_static/diagrams/i2c/i2c_master_write_read_slave.png
  188. :align: center
  189. :alt: I2C master write to slave and read from slave
  190. I2C master write to slave and read from slave
  191. Simple example for writing and reading from slave:
  192. .. code:: c
  193. i2c_device_config_t dev_cfg = {
  194. .dev_addr_length = I2C_ADDR_BIT_LEN_7,
  195. .device_address = 0x58,
  196. .scl_speed_hz = 100000,
  197. };
  198. i2c_master_dev_handle_t dev_handle;
  199. ESP_ERROR_CHECK(i2c_master_bus_add_device(I2C_PORT_NUM_0, &dev_cfg, &dev_handle));
  200. uint8_t buf[20] = {0x20};
  201. uint8_t buffer[2];
  202. ESP_ERROR_CHECK(i2c_master_transmit_receive(i2c_bus_handle, buf, sizeof(buf), buffer, 2, -1));
  203. I2C Master Probe
  204. ~~~~~~~~~~~~~~~~
  205. I2C driver can use :cpp:func:`i2c_master_probe` to detect whether the specific device has been connected on I2C bus. If this function return ``ESP_OK``, that means the device has been detected.
  206. .. figure:: ../../../_static/diagrams/i2c/i2c_master_probe.png
  207. :align: center
  208. :alt: I2C master probe
  209. I2C master probe
  210. Simple example for probing an I2C device:
  211. .. code:: c
  212. i2c_master_bus_config_t i2c_mst_config_1 = {
  213. .clk_source = I2C_CLK_SRC_DEFAULT,
  214. .i2c_port = TEST_I2C_PORT,
  215. .scl_io_num = I2C_MASTER_SCL_IO,
  216. .sda_io_num = I2C_MASTER_SDA_IO,
  217. .glitch_ignore_cnt = 7,
  218. .flags.enable_internal_pullup = true,
  219. };
  220. i2c_master_bus_handle_t bus_handle;
  221. ESP_ERROR_CHECK(i2c_new_master_bus(&i2c_mst_config_1, &bus_handle));
  222. ESP_ERROR_CHECK(i2c_master_probe(bus_handle, 0x22, -1));
  223. ESP_ERROR_CHECK(i2c_del_master_bus(bus_handle));
  224. I2C Slave Controller
  225. ^^^^^^^^^^^^^^^^^^^^
  226. After installing the i2c slave driver by :cpp:func:`i2c_new_slave_device`, {IDF_TARGET_NAME} is ready to communicate with other I2C master as a slave.
  227. I2C Slave Write
  228. ~~~~~~~~~~~~~~~
  229. The send buffer of the I2C slave is used as a FIFO to store the data to be sent. The data will queue up until the master requests them. You can call :cpp:func:`i2c_slave_transmit` to transfer data.
  230. Simple example for writing data to FIFO:
  231. .. code:: c
  232. uint8_t *data_wr = (uint8_t *) malloc(DATA_LENGTH);
  233. i2c_slave_config_t i2c_slv_config = {
  234. .addr_bit_len = I2C_ADDR_BIT_LEN_7, // 7-bit address
  235. .clk_source = I2C_CLK_SRC_DEFAULT, // set the clock source
  236. .i2c_port = 0, // set I2C port number
  237. .send_buf_depth = 256, // set tx buffer length
  238. .scl_io_num = 2, // SCL gpio number
  239. .sda_io_num = 1, // SDA gpio number
  240. .slave_addr = 0x58, // slave address
  241. };
  242. i2c_bus_handle_t i2c_bus_handle;
  243. ESP_ERROR_CHECK(i2c_new_slave_device(&i2c_slv_config, &i2c_bus_handle));
  244. for (int i = 0; i < DATA_LENGTH; i++) {
  245. data_wr[i] = i;
  246. }
  247. ESP_ERROR_CHECK(i2c_slave_transmit(i2c_bus_handle, data_wr, DATA_LENGTH, 10000));
  248. I2C Slave Read
  249. ~~~~~~~~~~~~~~
  250. Whenever the master writes data to the slave, the slave will automatically store data in the receive buffer. This allows the slave application to call the function :cpp:func:`i2c_slave_receive` as its own discretion. As :cpp:func:`i2c_slave_receive` is designed as a non-blocking interface. So the user needs to register callback :cpp:func:`i2c_slave_register_event_callbacks` to know when the receive has finished.
  251. .. code:: c
  252. static IRAM_ATTR bool i2c_slave_rx_done_callback(i2c_slave_dev_handle_t channel, const i2c_slave_rx_done_event_data_t *edata, void *user_data)
  253. {
  254. BaseType_t high_task_wakeup = pdFALSE;
  255. QueueHandle_t receive_queue = (QueueHandle_t)user_data;
  256. xQueueSendFromISR(receive_queue, edata, &high_task_wakeup);
  257. return high_task_wakeup == pdTRUE;
  258. }
  259. uint8_t *data_rd = (uint8_t *) malloc(DATA_LENGTH);
  260. uint32_t size_rd = 0;
  261. i2c_slave_config_t i2c_slv_config = {
  262. .addr_bit_len = I2C_ADDR_BIT_LEN_7,
  263. .clk_source = I2C_CLK_SRC_DEFAULT,
  264. .i2c_port = TEST_I2C_PORT,
  265. .send_buf_depth = 256,
  266. .scl_io_num = I2C_SLAVE_SCL_IO,
  267. .sda_io_num = I2C_SLAVE_SDA_IO,
  268. .slave_addr = 0x58,
  269. };
  270. i2c_slave_dev_handle_t slave_handle;
  271. ESP_ERROR_CHECK(i2c_new_slave_device(&i2c_slv_config, &slave_handle));
  272. s_receive_queue = xQueueCreate(1, sizeof(i2c_slave_rx_done_event_data_t));
  273. i2c_slave_event_callbacks_t cbs = {
  274. .on_recv_done = i2c_slave_rx_done_callback,
  275. };
  276. ESP_ERROR_CHECK(i2c_slave_register_event_callbacks(slave_handle, &cbs, s_receive_queue));
  277. i2c_slave_rx_done_event_data_t rx_data;
  278. ESP_ERROR_CHECK(i2c_slave_receive(slave_handle, data_rd, DATA_LENGTH));
  279. xQueueReceive(s_receive_queue, &rx_data, pdMS_TO_TICKS(10000));
  280. // Receive done.
  281. .. only:: SOC_I2C_SLAVE_SUPPORT_I2CRAM_ACCESS
  282. Put Data In I2C Slave RAM
  283. ~~~~~~~~~~~~~~~~~~~~~~~~~
  284. I2C slave fifo mentioned above can be used as RAM, which means user can access the RAM directly via address fields. For example, writing data to the 3rd ram block with following graph. Before using this, please note that :cpp:member:`i2c_slave_config_t::access_ram_en` needs to be set to true.
  285. .. figure:: ../../../_static/diagrams/i2c/i2c_slave_write_slave_ram.png
  286. :align: center
  287. :alt: Put data in I2C slave RAM
  288. Put data in I2C slave RAM
  289. .. code:: c
  290. uint8_t data_rd[DATA_LENGTH_RAM] = {0};
  291. i2c_slave_config_t i2c_slv_config = {
  292. .addr_bit_len = I2C_ADDR_BIT_LEN_7,
  293. .clk_source = I2C_CLK_SRC_DEFAULT,
  294. .i2c_port = TEST_I2C_PORT,
  295. .send_buf_depth = 256,
  296. .scl_io_num = I2C_SLAVE_SCL_IO,
  297. .sda_io_num = I2C_SLAVE_SDA_IO,
  298. .slave_addr = 0x58,
  299. .flags.access_ram_en = true,
  300. };
  301. // Master write to slave.
  302. i2c_slave_dev_handle_t slave_handle;
  303. ESP_ERROR_CHECK(i2c_new_slave_device(&i2c_slv_config, &slave_handle));
  304. ESP_ERROR_CHECK(i2c_slave_read_ram(slave_handle, 0x5, data_rd, DATA_LENGTH_RAM));
  305. ESP_ERROR_CHECK(i2c_del_slave_device(slave_handle));
  306. Get Data From I2C Slave RAM
  307. ~~~~~~~~~~~~~~~~~~~~~~~~~~~
  308. Data can be stored in the RAM with a specific offset by the slave controller, and the master can read this data directly via the RAM address. For example, if the data is stored in 3rd ram block, master can read this data by following graph. Before using this, please note that :cpp:member:`i2c_slave_config_t::access_ram_en` needs to be set to true.
  309. .. figure:: ../../../_static/diagrams/i2c/i2c_slave_read_slave_ram.png
  310. :align: center
  311. :alt: Get data from I2C slave RAM
  312. Get data from I2C slave RAM
  313. .. code:: c
  314. uint8_t data_wr[DATA_LENGTH_RAM] = {0};
  315. i2c_slave_config_t i2c_slv_config = {
  316. .addr_bit_len = I2C_ADDR_BIT_LEN_7,
  317. .clk_source = I2C_CLK_SRC_DEFAULT,
  318. .i2c_port = TEST_I2C_PORT,
  319. .send_buf_depth = 256,
  320. .scl_io_num = I2C_SLAVE_SCL_IO,
  321. .sda_io_num = I2C_SLAVE_SDA_IO,
  322. .slave_addr = 0x58,
  323. .flags.access_ram_en = true,
  324. };
  325. i2c_slave_dev_handle_t slave_handle;
  326. ESP_ERROR_CHECK(i2c_new_slave_device(&i2c_slv_config, &slave_handle));
  327. ESP_ERROR_CHECK(i2c_slave_write_ram(slave_handle, 0x2, data_wr, DATA_LENGTH_RAM));
  328. ESP_ERROR_CHECK(i2c_del_slave_device(slave_handle));
  329. Register Event Callbacks
  330. ^^^^^^^^^^^^^^^^^^^^^^^^
  331. I2C master callbacks
  332. ~~~~~~~~~~~~~~~~~~~~
  333. When an I2C master bus triggers an interrupt, a specific event will be generated and notify the CPU. If you have some functions that need to be called when those events occurred, you can hook your functions to the ISR (Interrupt Service Routine) by calling :cpp:func:`i2c_master_register_event_callbacks`. Since the registered callback functions are called in the interrupt context, user should ensure the callback function doesn't attempt to block (e.g. by making sure that only FreeRTOS APIs with ``ISR`` suffix are called from within the function). The callback functions are required to return a boolean value, to tell the ISR whether a high priority task is woke up by it.
  334. I2C master event callbacks are listed in the :cpp:type:`i2c_master_event_callbacks_t`.
  335. Although I2C is a synchronous communication protocol, we also support asynchronous behavior by registering above callback. In this way, I2C APIs will be non-blocking interface. But note that on the same bus, only one device can adopt asynchronous operation.
  336. .. important::
  337. I2C master asynchronous transaction is still an experimental feature. (The issue is when asynchronous transaction is very large, it will cause memory problem.)
  338. - :cpp:member:`i2c_master_event_callbacks_t::on_recv_done` sets a callback function for master "transaction-done" event. The function prototype is declared in :cpp:type:`i2c_master_callback_t`.
  339. I2C slave callbacks
  340. ~~~~~~~~~~~~~~~~~~~
  341. When an I2C slave bus triggers an interrupt, a specific event will be generated and notify the CPU. If you have some function that needs to be called when those events occurred, you can hook your function to the ISR (Interrupt Service Routine) by calling :cpp:func:`i2c_slave_register_event_callbacks`. Since the registered callback functions are called in the interrupt context, user should ensure the callback function doesn't attempt to block (e.g. by making sure that only FreeRTOS APIs with ``ISR`` suffix are called from within the function). The callback function has a boolean return value, to tell the caller whether a high priority task is woke up by it.
  342. I2C slave event callbacks are listed in the :cpp:type:`i2c_slave_event_callbacks_t`.
  343. .. list::
  344. - :cpp:member:`i2c_slave_event_callbacks_t::on_recv_done` sets a callback function for "receive-done" event. The function prototype is declared in :cpp:type:`i2c_slave_received_callback_t`.
  345. :SOC_I2C_SLAVE_CAN_GET_STRETCH_CAUSE: - :cpp:member:`i2c_slave_event_callbacks_t::on_stretch_occur` sets a callback function for "stretch" cause. The function prototype is declared in :cpp:type:`i2c_slave_stretch_callback_t`.
  346. Power Management
  347. ^^^^^^^^^^^^^^^^
  348. .. only:: SOC_I2C_SUPPORT_APB
  349. When the power management is enabled (i.e. :ref:`CONFIG_PM_ENABLE` is on), the system will adjust or stop the source clock of I2C fifo before going into light sleep, thus potentially changing the I2C signals and leading to transmitting or receiving invalid data.
  350. However, the driver can prevent the system from changing APB frequency by acquiring a power management lock of type :cpp:enumerator:`ESP_PM_APB_FREQ_MAX`. Whenever user creates an I2C bus that has selected :cpp:enumerator:`I2C_CLK_SRC_APB` as the clock source, the driver will guarantee that the power management lock is acquired when I2C operations begin and release the lock automatically when I2C operations finish.
  351. .. only:: SOC_I2C_SUPPORT_REF_TICK
  352. If the controller clock source is selected to :cpp:enumerator:`I2C_CLK_SRC_REF_TICK`, then the driver won't install power management lock for it, which is more suitable for a low power application as long as the source clock can still provide sufficient resolution.
  353. .. only:: SOC_I2C_SUPPORT_XTAL
  354. If the controller clock source is selected to :cpp:enumerator:`I2C_CLK_SRC_XTAL`, then the driver won't install power management lock for it, which is more suitable for a low power application as long as the source clock can still provide sufficient resolution.
  355. IRAM Safe
  356. ^^^^^^^^^
  357. By default, the I2C interrupt will be deferred when the Cache is disabled for reasons like writing/erasing Flash. Thus the event callback functions will not get executed in time, which is not expected in a real-time application.
  358. There's a Kconfig option :ref:`CONFIG_I2C_ISR_IRAM_SAFE` that will:
  359. 1. Enable the interrupt being serviced even when cache is disabled
  360. 2. Place all functions that used by the ISR into IRAM
  361. 3. Place driver object into DRAM (in case it's mapped to PSRAM by accident)
  362. This will allow the interrupt to run while the cache is disabled but will come at the cost of increased IRAM consumption.
  363. Thread Safety
  364. ^^^^^^^^^^^^^
  365. The factory function :cpp:func:`i2c_new_master_bus` and :cpp:func:`i2c_new_slave_device` are guaranteed to be thread safe by the driver, which means, user can call them from different RTOS tasks without protection by extra locks. Other public I2C APIs are not thread safe. which means the user should avoid calling them from multiple tasks, if user strongly needs to call them in multiple tasks, please add extra lock.
  366. Kconfig Options
  367. ^^^^^^^^^^^^^^^
  368. - :ref:`CONFIG_I2C_ISR_IRAM_SAFE` controls whether the default ISR handler can work when cache is disabled, see also `IRAM Safe <#iram-safe>`__ for more information.
  369. - :ref:`CONFIG_I2C_ENABLE_DEBUG_LOG` is used to enable the debug log at the cost of increased firmware binary size.
  370. API Reference
  371. -------------
  372. .. include-build-file:: inc/i2c_master.inc
  373. .. only:: SOC_I2C_SUPPORT_SLAVE
  374. .. include-build-file:: inc/i2c_slave.inc
  375. .. include-build-file:: inc/components/driver/i2c/include/driver/i2c_types.inc
  376. .. include-build-file:: inc/components/hal/include/hal/i2c_types.inc