i2c_master.c 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102
  1. /*
  2. * SPDX-FileCopyrightText: 2023 Espressif Systems (Shanghai) CO LTD
  3. *
  4. * SPDX-License-Identifier: Apache-2.0
  5. */
  6. #include <string.h>
  7. #include <sys/param.h>
  8. #include <sys/lock.h>
  9. #include "sdkconfig.h"
  10. #include "esp_types.h"
  11. #include "esp_attr.h"
  12. #include "esp_check.h"
  13. #if CONFIG_I2C_ENABLE_DEBUG_LOG
  14. // The local log level must be defined before including esp_log.h
  15. // Set the maximum log level for this source file
  16. #define LOG_LOCAL_LEVEL ESP_LOG_DEBUG
  17. #endif
  18. #include "esp_log.h"
  19. #include "esp_intr_alloc.h"
  20. #include "freertos/FreeRTOS.h"
  21. #include "freertos/semphr.h"
  22. #include "soc/i2c_periph.h"
  23. #include "esp_private/periph_ctrl.h"
  24. #include "esp_private/esp_clk.h"
  25. #include "esp_rom_gpio.h"
  26. #include "driver/i2c_master.h"
  27. #include "i2c_private.h"
  28. #include "driver/gpio.h"
  29. #include "clk_ctrl_os.h"
  30. #include "hal/i2c_types.h"
  31. #include "hal/i2c_hal.h"
  32. #include "hal/gpio_hal.h"
  33. #include "esp_memory_utils.h"
  34. #include "freertos/idf_additions.h"
  35. static const char *TAG = "i2c.master";
  36. static _lock_t s_i2c_bus_acquire;
  37. #define DIM(array) (sizeof(array)/sizeof(*array))
  38. #define I2C_ADDRESS_TRANS_WRITE(device_address) (((device_address) << 1) | 0)
  39. #define I2C_ADDRESS_TRANS_READ(device_address) (((device_address) << 1) | 1)
  40. static esp_err_t s_i2c_master_clear_bus(i2c_bus_handle_t handle)
  41. {
  42. #if !SOC_I2C_SUPPORT_HW_FSM_RST
  43. const int scl_half_period = 5; // use standard 100kHz data rate
  44. int i = 0;
  45. gpio_set_direction(handle->scl_num, GPIO_MODE_OUTPUT_OD);
  46. gpio_set_direction(handle->sda_num, GPIO_MODE_INPUT_OUTPUT_OD);
  47. // If a SLAVE device was in a read operation when the bus was interrupted, the SLAVE device is controlling SDA.
  48. // The only bit during the 9 clock cycles of a READ byte the MASTER(ESP32) is guaranteed control over is during the ACK bit
  49. // period. If the slave is sending a stream of ZERO bytes, it will only release SDA during the ACK bit period.
  50. // So, this reset code needs to synchronous the bit stream with, Either, the ACK bit, Or a 1 bit to correctly generate
  51. // a STOP condition.
  52. gpio_set_level(handle->scl_num, 0);
  53. gpio_set_level(handle->sda_num, 1);
  54. esp_rom_delay_us(scl_half_period);
  55. while (!gpio_get_level(handle->sda_num) && (i++ < 9)) {
  56. gpio_set_level(handle->scl_num, 1);
  57. esp_rom_delay_us(scl_half_period);
  58. gpio_set_level(handle->scl_num, 0);
  59. esp_rom_delay_us(scl_half_period);
  60. }
  61. gpio_set_level(handle->sda_num, 0); // setup for STOP
  62. gpio_set_level(handle->scl_num, 1);
  63. esp_rom_delay_us(scl_half_period);
  64. gpio_set_level(handle->sda_num, 1); // STOP, SDA low -> high while SCL is HIGH
  65. i2c_common_set_pins(handle);
  66. #else
  67. i2c_hal_context_t *hal = &handle->hal;
  68. i2c_ll_master_clr_bus(hal->dev, I2C_LL_RESET_SLV_SCL_PULSE_NUM_DEFAULT);
  69. #endif
  70. return ESP_OK;
  71. }
  72. /**
  73. * @brief Reset I2C hardware fsm.
  74. * 1. Store filter and timing stuff(they are I2C hardware configure stuff)
  75. * so, the configuration is same after reset.
  76. *
  77. * @param[in] i2c_master I2C master handle
  78. */
  79. static esp_err_t s_i2c_hw_fsm_reset(i2c_master_bus_handle_t i2c_master)
  80. {
  81. i2c_hal_context_t *hal = &i2c_master->base->hal;
  82. i2c_hal_timing_config_t timing_config;
  83. uint8_t filter_cfg;
  84. i2c_hal_get_timing_config(hal, &timing_config);
  85. i2c_ll_master_get_filter(hal->dev, &filter_cfg);
  86. //to reset the I2C hw module, we need re-enable the hw
  87. s_i2c_master_clear_bus(i2c_master->base);
  88. periph_module_disable(i2c_periph_signal[i2c_master->base->port_num].module);
  89. periph_module_enable(i2c_periph_signal[i2c_master->base->port_num].module);
  90. i2c_hal_master_init(hal);
  91. i2c_ll_disable_intr_mask(hal->dev, I2C_LL_INTR_MASK);
  92. i2c_ll_clear_intr_mask(hal->dev, I2C_LL_INTR_MASK);
  93. i2c_hal_set_timing_config(hal, &timing_config);
  94. i2c_ll_master_set_filter(hal->dev, filter_cfg);
  95. return ESP_OK;
  96. }
  97. //////////////////////////////////////I2C operation functions////////////////////////////////////////////
  98. /**
  99. * @brief This function is used to send I2C write command, which is divided in two parts.
  100. * -1. If write buffer is smaller than hardware fifo, it can be sent out in one single time,
  101. * so the hardware command(step) is simply like start(1)->write(2)->end(3)
  102. * -2. If write buffer is larger than hardware fifo, it cannot be sent out in one time, so it needs
  103. * to be separated in to different transactions by interrupt. In this time, the hardware command(step)
  104. * simply looks like start(1)->write_part(2)--interrupt--...--write(1)->end(2).
  105. *
  106. * @param[in] i2c_master I2C master handle
  107. * @param[in] i2c_operation Pointer to I2C trans operation structure.
  108. * @param[in] fifo_fill will be populated with the number of bytes written to the harware FIFO by this function
  109. * @param[in] address_fill I2C device address with read or write information.
  110. */
  111. static bool s_i2c_write_command(i2c_master_bus_handle_t i2c_master, i2c_operation_t *i2c_operation, uint8_t *fifo_fill, uint8_t *address_fill, BaseType_t *do_yield)
  112. {
  113. i2c_master->async_break = false;
  114. const size_t remaining_bytes = i2c_operation->total_bytes - i2c_operation->bytes_used;
  115. const i2c_ll_hw_cmd_t hw_end_cmd = {
  116. .op_code = I2C_LL_CMD_END
  117. };
  118. uint8_t *write_pr = NULL;
  119. i2c_hal_context_t *hal = &i2c_master->base->hal;
  120. i2c_bus_handle_t handle = i2c_master->base;
  121. i2c_ll_hw_cmd_t hw_cmd = i2c_operation->hw_cmd;
  122. uint8_t data_fill = 0;
  123. // data_fill refers to the length to fill the data
  124. data_fill = MIN(remaining_bytes, SOC_I2C_FIFO_LEN - *address_fill);
  125. write_pr = i2c_operation->data + i2c_operation->bytes_used;
  126. i2c_operation->bytes_used += data_fill;
  127. hw_cmd.byte_num = data_fill + *address_fill;
  128. *address_fill = 0;
  129. atomic_store(&i2c_master->status, I2C_STATUS_WRITE);
  130. portENTER_CRITICAL_SAFE(&handle->spinlock);
  131. i2c_ll_write_txfifo(hal->dev, write_pr, data_fill);
  132. i2c_ll_master_write_cmd_reg(hal->dev, hw_cmd, i2c_master->cmd_idx);
  133. portEXIT_CRITICAL_SAFE(&handle->spinlock);
  134. i2c_master->w_r_size = data_fill;
  135. #if SOC_I2C_STOP_INDEPENDENT
  136. i2c_ll_master_write_cmd_reg(hal->dev, hw_end_cmd, i2c_master->cmd_idx + 1);
  137. i2c_master->cmd_idx = 0;
  138. if (i2c_master->i2c_trans.ops[i2c_master->trans_idx].total_bytes == i2c_master->i2c_trans.ops[i2c_master->trans_idx].bytes_used) {
  139. i2c_master->i2c_trans.cmd_count--;
  140. i2c_master->trans_idx++;
  141. }
  142. portENTER_CRITICAL_SAFE(&handle->spinlock);
  143. if (i2c_master->asnyc_trans == false) {
  144. i2c_hal_master_trans_start(hal);
  145. } else {
  146. i2c_master->async_break = true;
  147. }
  148. portEXIT_CRITICAL_SAFE(&handle->spinlock);
  149. #else
  150. // If data cannot be sent in one time, send data out. Otherwise, continue configuring command.
  151. if ((remaining_bytes - data_fill) != 0) {
  152. portENTER_CRITICAL_SAFE(&handle->spinlock);
  153. i2c_ll_master_write_cmd_reg(hal->dev, hw_end_cmd, i2c_master->cmd_idx + 1);
  154. portEXIT_CRITICAL_SAFE(&handle->spinlock);
  155. i2c_master->cmd_idx = 0;
  156. if (i2c_master->asnyc_trans == false) {
  157. i2c_hal_master_trans_start(hal);
  158. } else {
  159. i2c_master->async_break = true;
  160. }
  161. } else {
  162. i2c_master->cmd_idx++;
  163. i2c_master->trans_idx++;
  164. i2c_master->i2c_trans.cmd_count--;
  165. if (i2c_master->asnyc_trans == false) {
  166. if (xPortInIsrContext()) {
  167. xSemaphoreGiveFromISR(i2c_master->cmd_semphr, do_yield);
  168. } else {
  169. xSemaphoreGive(i2c_master->cmd_semphr);
  170. }
  171. }
  172. }
  173. #endif
  174. *fifo_fill = data_fill;
  175. return i2c_master->async_break;
  176. }
  177. /**
  178. * @brief This function is used to send I2C read command, which is divided in three parts.
  179. * -1. If read buffer is smaller than hardware fifo, it can be sent out in one single time,
  180. * so the hardware command(step) is simply like start(1)->read_ack(2)->read_nack(3)->end(4)
  181. * -2. If read buffer is larger than hardware fifo, it cannot be sent out in one time, so it needs
  182. * to be separated in to different transactions by interrupt. In this time, the hardware command(step)
  183. * simply looks like start(1)->read_part(2)--interrupt--...--read(1)->end(2).
  184. * -3. If only one byte is waiting to be read. only send nack command. like start(1)->read_nack(2)->end(3)
  185. *
  186. * @param[in] i2c_master I2C master handle
  187. * @param[in] i2c_operation Pointer to I2C trans operation structure.
  188. * @param[out] fifo_fill Pointer to read buffer length
  189. */
  190. static bool s_i2c_read_command(i2c_master_bus_handle_t i2c_master, i2c_operation_t *i2c_operation, uint8_t *fifo_fill, BaseType_t *do_yield)
  191. {
  192. i2c_master->async_break = false;
  193. const size_t remaining_bytes = i2c_operation->total_bytes - i2c_operation->bytes_used;
  194. const i2c_ll_hw_cmd_t hw_end_cmd = {
  195. .op_code = I2C_LL_CMD_END
  196. };
  197. i2c_hal_context_t *hal = &i2c_master->base->hal;
  198. i2c_bus_handle_t handle = i2c_master->base;
  199. i2c_ll_hw_cmd_t hw_cmd = i2c_operation->hw_cmd;
  200. *fifo_fill = MIN(remaining_bytes, SOC_I2C_FIFO_LEN - i2c_master->read_len_static);
  201. i2c_master->rx_cnt = *fifo_fill;
  202. hw_cmd.byte_num = *fifo_fill;
  203. i2c_master->contains_read = true;
  204. #if !SOC_I2C_STOP_INDEPENDENT
  205. if (remaining_bytes < SOC_I2C_FIFO_LEN - 1) {
  206. if (i2c_operation->hw_cmd.ack_val == ACK_VAL) {
  207. if (remaining_bytes != 0) {
  208. i2c_ll_master_write_cmd_reg(hal->dev, hw_cmd, i2c_master->cmd_idx);
  209. i2c_master->read_len_static = i2c_master->rx_cnt;
  210. i2c_master->cmd_idx++;
  211. }
  212. i2c_master->read_buf_pos = i2c_master->trans_idx;
  213. } else {
  214. i2c_ll_master_write_cmd_reg(hal->dev, hw_cmd, i2c_master->cmd_idx);
  215. i2c_master->cmd_idx++;
  216. }
  217. i2c_master->trans_idx++;
  218. i2c_master->i2c_trans.cmd_count--;
  219. if (i2c_master->asnyc_trans == false) {
  220. if (xPortInIsrContext()) {
  221. xSemaphoreGiveFromISR(i2c_master->cmd_semphr, do_yield);
  222. } else {
  223. xSemaphoreGive(i2c_master->cmd_semphr);
  224. }
  225. }
  226. } else {
  227. atomic_store(&i2c_master->status, I2C_STATUS_READ);
  228. portENTER_CRITICAL_SAFE(&handle->spinlock);
  229. i2c_ll_master_write_cmd_reg(hal->dev, hw_cmd, i2c_master->cmd_idx);
  230. i2c_ll_master_write_cmd_reg(hal->dev, hw_end_cmd, i2c_master->cmd_idx + 1);
  231. if (i2c_master->asnyc_trans == false) {
  232. i2c_hal_master_trans_start(hal);
  233. } else {
  234. i2c_master->async_break = true;
  235. }
  236. portEXIT_CRITICAL_SAFE(&handle->spinlock);
  237. }
  238. #else
  239. portENTER_CRITICAL_SAFE(&handle->spinlock);
  240. i2c_ll_master_write_cmd_reg(hal->dev, hw_cmd, i2c_master->cmd_idx);
  241. i2c_ll_master_write_cmd_reg(hal->dev, hw_end_cmd, i2c_master->cmd_idx + 1);
  242. portEXIT_CRITICAL_SAFE(&handle->spinlock);
  243. i2c_master->status = I2C_STATUS_READ;
  244. portENTER_CRITICAL_SAFE(&handle->spinlock);
  245. if (i2c_master->asnyc_trans == false) {
  246. i2c_hal_master_trans_start(hal);
  247. } else {
  248. i2c_master->async_break = true;
  249. }
  250. portEXIT_CRITICAL_SAFE(&handle->spinlock);
  251. #endif
  252. return i2c_master->async_break;
  253. }
  254. /**
  255. * @brief This function is used to send I2C start or stop command, which is divided in two parts.
  256. * If start command is accepted, a write address command must be followed. So prepared one address
  257. * data here. Send with write or read command.
  258. *
  259. * @param[in] i2c_master I2C master handle
  260. * @param[in] i2c_operation Pointer to I2C trans operation structure.
  261. * @param[in] address_fill I2C device address with read or write information.
  262. */
  263. static void s_i2c_start_end_command(i2c_master_bus_handle_t i2c_master, i2c_operation_t *i2c_operation, uint8_t *address_fill, BaseType_t *do_yield)
  264. {
  265. i2c_hal_context_t *hal = &i2c_master->base->hal;
  266. i2c_ll_hw_cmd_t hw_cmd = i2c_operation->hw_cmd;
  267. #if SOC_I2C_SUPPORT_10BIT_ADDR
  268. uint8_t cmd_address = (i2c_master->addr_10bits_bus == I2C_ADDR_BIT_LEN_7) ? i2c_master->i2c_trans.device_address : ((i2c_master->i2c_trans.device_address >> 8) | 0x78);
  269. uint8_t addr_byte = (i2c_master->addr_10bits_bus == I2C_ADDR_BIT_LEN_7) ? 1 : 2;
  270. #else
  271. uint8_t cmd_address = i2c_master->i2c_trans.device_address;
  272. uint8_t addr_byte = 1;
  273. #endif
  274. uint8_t addr_write[addr_byte];
  275. uint8_t addr_read[addr_byte];
  276. addr_write[0] = I2C_ADDRESS_TRANS_WRITE(cmd_address);
  277. addr_read[0] = I2C_ADDRESS_TRANS_READ(cmd_address);
  278. #if SOC_I2C_SUPPORT_10BIT_ADDR
  279. if (i2c_master->addr_10bits_bus == I2C_ADDR_BIT_LEN_10) {
  280. addr_write[1] = i2c_master->i2c_trans.device_address & 0xff;
  281. addr_read[1] = i2c_master->i2c_trans.device_address & 0xff;
  282. }
  283. #endif
  284. portENTER_CRITICAL_SAFE(&i2c_master->base->spinlock);
  285. i2c_ll_master_write_cmd_reg(hal->dev, hw_cmd, i2c_master->cmd_idx);
  286. i2c_master->cmd_idx++;
  287. portEXIT_CRITICAL_SAFE(&i2c_master->base->spinlock);
  288. if (i2c_operation->hw_cmd.op_code == I2C_LL_CMD_RESTART) {
  289. if (i2c_master->i2c_trans.ops[i2c_master->trans_idx + 1].hw_cmd.op_code != I2C_LL_CMD_WRITE) {
  290. #if SOC_I2C_SUPPORT_10BIT_ADDR
  291. if (i2c_master->addr_10bits_bus == I2C_ADDR_BIT_LEN_10) {
  292. i2c_ll_hw_cmd_t hw_write_cmd = {
  293. .ack_en = false,
  294. .op_code = I2C_LL_CMD_WRITE,
  295. .byte_num = 2,
  296. };
  297. portENTER_CRITICAL_SAFE(&i2c_master->base->spinlock);
  298. i2c_ll_write_txfifo(hal->dev, addr_write, sizeof(addr_write));
  299. i2c_ll_master_write_cmd_reg(hal->dev, hw_write_cmd, i2c_master->cmd_idx);
  300. i2c_master->cmd_idx++;
  301. portEXIT_CRITICAL_SAFE(&i2c_master->base->spinlock);
  302. const i2c_ll_hw_cmd_t hw_start_cmd = {
  303. .op_code = I2C_LL_CMD_RESTART,
  304. };
  305. portENTER_CRITICAL_SAFE(&i2c_master->base->spinlock);
  306. i2c_ll_master_write_cmd_reg(hal->dev, hw_start_cmd, i2c_master->cmd_idx);
  307. i2c_master->cmd_idx++;
  308. portEXIT_CRITICAL_SAFE(&i2c_master->base->spinlock);
  309. }
  310. #endif
  311. i2c_ll_hw_cmd_t hw_write_cmd = {
  312. .ack_en = false,
  313. .op_code = I2C_LL_CMD_WRITE,
  314. .byte_num = 1,
  315. };
  316. portENTER_CRITICAL_SAFE(&i2c_master->base->spinlock);
  317. i2c_ll_write_txfifo(hal->dev, addr_read, sizeof(addr_read));
  318. i2c_ll_master_write_cmd_reg(hal->dev, hw_write_cmd, i2c_master->cmd_idx);
  319. i2c_master->cmd_idx++;
  320. portEXIT_CRITICAL_SAFE(&i2c_master->base->spinlock);
  321. } else {
  322. /* The next transaction is a WRITE, we can merge the device address byte
  323. * with the next write command. No need to write the `cmd_reg` as the next
  324. * command will do it for us, we only need to add the device address byte
  325. * in the TX FIFO. */
  326. portENTER_CRITICAL_SAFE(&i2c_master->base->spinlock);
  327. i2c_ll_write_txfifo(hal->dev, addr_write, sizeof(addr_write));
  328. *address_fill += sizeof(addr_write);
  329. portEXIT_CRITICAL_SAFE(&i2c_master->base->spinlock);
  330. }
  331. if (i2c_master->asnyc_trans == false) {
  332. if (xPortInIsrContext()) {
  333. xSemaphoreGiveFromISR(i2c_master->cmd_semphr, do_yield);
  334. } else {
  335. xSemaphoreGive(i2c_master->cmd_semphr);
  336. }
  337. }
  338. } else {
  339. atomic_store(&i2c_master->status, I2C_STATUS_STOP);
  340. }
  341. portENTER_CRITICAL_SAFE(&i2c_master->base->spinlock);
  342. i2c_master->trans_idx++;
  343. i2c_master->i2c_trans.cmd_count--;
  344. portEXIT_CRITICAL_SAFE(&i2c_master->base->spinlock);
  345. }
  346. static void s_i2c_send_commands(i2c_master_bus_handle_t i2c_master, TickType_t ticks_to_wait)
  347. {
  348. i2c_hal_context_t *hal = &i2c_master->base->hal;
  349. uint8_t fifo_fill = 0;
  350. uint8_t address_fill = 0;
  351. while (i2c_master->i2c_trans.cmd_count) {
  352. if (xSemaphoreTake(i2c_master->cmd_semphr, ticks_to_wait) != pdTRUE) {
  353. // Software timeout, clear the command link and finish this transaction.
  354. i2c_master->cmd_idx = 0;
  355. i2c_master->trans_idx = 0;
  356. return;
  357. }
  358. if (i2c_master->status == I2C_STATUS_TIMEOUT) {
  359. s_i2c_hw_fsm_reset(i2c_master);
  360. i2c_master->cmd_idx = 0;
  361. i2c_master->trans_idx = 0;
  362. xSemaphoreGive(i2c_master->cmd_semphr);
  363. return;
  364. }
  365. if (i2c_master->status == I2C_STATUS_ACK_ERROR) {
  366. const i2c_ll_hw_cmd_t hw_stop_cmd = {
  367. .op_code = I2C_LL_CMD_STOP,
  368. };
  369. i2c_ll_master_write_cmd_reg(hal->dev, hw_stop_cmd, 0);
  370. i2c_hal_master_trans_start(hal);
  371. return;
  372. }
  373. i2c_operation_t *i2c_operation = &i2c_master->i2c_trans.ops[i2c_master->trans_idx];
  374. if (i2c_operation->hw_cmd.op_code == I2C_LL_CMD_WRITE) {
  375. s_i2c_write_command(i2c_master, i2c_operation, &fifo_fill, &address_fill, NULL);
  376. } else if (i2c_operation->hw_cmd.op_code == I2C_LL_CMD_READ) {
  377. s_i2c_read_command(i2c_master, i2c_operation, &fifo_fill, NULL);
  378. } else {
  379. s_i2c_start_end_command(i2c_master, i2c_operation, &address_fill, NULL);
  380. }
  381. }
  382. i2c_hal_master_trans_start(hal);
  383. // For blocking implementation, we must wait `done` interrupt to update the status.
  384. while (i2c_master->trans_done == false) {};
  385. atomic_store(&i2c_master->status, I2C_STATUS_DONE);
  386. xSemaphoreGive(i2c_master->cmd_semphr);
  387. }
  388. static void s_i2c_send_command_async(i2c_master_bus_handle_t i2c_master, BaseType_t *do_yield)
  389. {
  390. i2c_hal_context_t *hal = &i2c_master->base->hal;
  391. uint8_t address_fill = 0;
  392. bool needs_start = false;
  393. if (i2c_master->i2c_trans.cmd_count == 0) {
  394. // No extra commands.
  395. i2c_master->trans_finish = true;
  396. i2c_master->in_progress = false;
  397. if (i2c_master->queue_trans) {
  398. i2c_master->new_queue = true;
  399. xQueueSendFromISR(i2c_master->trans_queues[I2C_TRANS_QUEUE_COMPLETE], &i2c_master->i2c_trans, do_yield);
  400. }
  401. i2c_master->sent_all = true;
  402. return;
  403. }
  404. while(i2c_ll_is_bus_busy(hal->dev)){}
  405. while (i2c_master->i2c_trans.cmd_count && !needs_start) {
  406. i2c_master->in_progress = true;
  407. i2c_master->sent_all = false;
  408. i2c_operation_t *i2c_operation = &i2c_master->i2c_trans.ops[i2c_master->trans_idx];
  409. uint8_t fifo_fill = 0;
  410. if (i2c_operation->hw_cmd.op_code == I2C_LL_CMD_WRITE) {
  411. needs_start = s_i2c_write_command(i2c_master, i2c_operation, &fifo_fill, &address_fill, do_yield);
  412. } else if (i2c_operation->hw_cmd.op_code == I2C_LL_CMD_READ) {
  413. needs_start = s_i2c_read_command(i2c_master, i2c_operation, &fifo_fill, do_yield);
  414. } else {
  415. s_i2c_start_end_command(i2c_master, i2c_operation, &address_fill, do_yield);
  416. }
  417. }
  418. i2c_hal_master_trans_start(hal);
  419. }
  420. static esp_err_t s_i2c_transaction_start(i2c_master_dev_handle_t i2c_dev, int xfer_timeout_ms)
  421. {
  422. i2c_master_bus_handle_t i2c_master = i2c_dev->master_bus;
  423. i2c_hal_context_t *hal = &i2c_master->base->hal;
  424. TickType_t ticks_to_wait = (xfer_timeout_ms == -1) ? portMAX_DELAY : pdMS_TO_TICKS(xfer_timeout_ms);
  425. // Sometimes when the FSM get stuck, the ACK_ERR interrupt will occur endlessly until we reset the FSM and clear bus.
  426. esp_err_t ret = ESP_OK;
  427. if (i2c_master->status == I2C_STATUS_TIMEOUT || i2c_ll_is_bus_busy(hal->dev)) {
  428. s_i2c_hw_fsm_reset(i2c_master);
  429. }
  430. if (i2c_master->base->pm_lock) {
  431. ESP_RETURN_ON_ERROR(esp_pm_lock_acquire(i2c_master->base->pm_lock), TAG, "acquire pm_lock failed");
  432. }
  433. portENTER_CRITICAL(&i2c_master->base->spinlock);
  434. atomic_init(&i2c_master->trans_idx, 0);
  435. atomic_store(&i2c_master->status, I2C_STATUS_IDLE);
  436. i2c_master->cmd_idx = 0;
  437. i2c_master->rx_cnt = 0;
  438. i2c_master->read_len_static = 0;
  439. i2c_hal_set_bus_timing(hal, i2c_dev->scl_speed_hz, i2c_master->base->clk_src, i2c_master->base->clk_src_freq_hz);
  440. i2c_ll_master_set_fractional_divider(hal->dev, 0, 0);
  441. i2c_ll_update(hal->dev);
  442. i2c_ll_txfifo_rst(hal->dev);
  443. i2c_ll_rxfifo_rst(hal->dev);
  444. i2c_ll_enable_intr_mask(hal->dev, I2C_LL_MASTER_EVENT_INTR);
  445. portEXIT_CRITICAL(&i2c_master->base->spinlock);
  446. if (i2c_master->asnyc_trans == true) {
  447. s_i2c_send_command_async(i2c_master, NULL);
  448. } else {
  449. s_i2c_send_commands(i2c_master, ticks_to_wait);
  450. // Wait event bits
  451. if (i2c_master->status != I2C_STATUS_DONE) {
  452. ret = ESP_ERR_INVALID_STATE;
  453. }
  454. }
  455. if (i2c_master->base->pm_lock) {
  456. ESP_RETURN_ON_ERROR(esp_pm_lock_release(i2c_master->base->pm_lock), TAG, "release pm_lock failed");
  457. }
  458. return ret;
  459. }
  460. ///////////////////////////////I2C DRIVERS//////////////////////////////////////////////////////////////
  461. IRAM_ATTR static void i2c_isr_receive_handler(i2c_master_bus_t *i2c_master)
  462. {
  463. i2c_hal_context_t *hal = &i2c_master->base->hal;
  464. while(i2c_ll_is_bus_busy(hal->dev)){}
  465. if (i2c_master->status == I2C_STATUS_READ) {
  466. i2c_operation_t *i2c_operation = &i2c_master->i2c_trans.ops[i2c_master->trans_idx];
  467. portENTER_CRITICAL_ISR(&i2c_master->base->spinlock);
  468. i2c_ll_read_rxfifo(hal->dev, i2c_operation->data + i2c_operation->bytes_used, i2c_master->rx_cnt);
  469. /* rx_cnt bytes have just been read, increment the number of bytes used from the buffer */
  470. i2c_master->w_r_size = i2c_master->rx_cnt;
  471. i2c_operation->bytes_used += i2c_master->rx_cnt;
  472. i2c_master->cmd_idx = 0;
  473. /* Test if there are still some remaining bytes to send. */
  474. if (i2c_operation->bytes_used == i2c_operation->total_bytes) {
  475. i2c_master->i2c_trans.cmd_count--;
  476. i2c_master->read_buf_pos = i2c_master->trans_idx;
  477. i2c_master->trans_idx++;
  478. i2c_operation->bytes_used = 0;
  479. }
  480. portEXIT_CRITICAL_ISR(&i2c_master->base->spinlock);
  481. }
  482. #if !SOC_I2C_STOP_INDEPENDENT
  483. else {
  484. i2c_operation_t *i2c_operation = &i2c_master->i2c_trans.ops[i2c_master->read_buf_pos];
  485. portENTER_CRITICAL_ISR(&i2c_master->base->spinlock);
  486. i2c_ll_read_rxfifo(hal->dev, i2c_operation->data + i2c_operation->bytes_used, i2c_master->read_len_static);
  487. i2c_ll_read_rxfifo(hal->dev, i2c_master->i2c_trans.ops[i2c_master->read_buf_pos + 1].data, 1);
  488. i2c_master->w_r_size = i2c_master->read_len_static + 1;
  489. i2c_master->contains_read = false;
  490. portEXIT_CRITICAL_ISR(&i2c_master->base->spinlock);
  491. }
  492. #endif
  493. }
  494. static void IRAM_ATTR i2c_master_isr_handler_default(void *arg)
  495. {
  496. i2c_master_bus_handle_t i2c_master = (i2c_master_bus_t*) arg;
  497. i2c_hal_context_t *hal = &i2c_master->base->hal;
  498. portBASE_TYPE HPTaskAwoken = pdFALSE;
  499. uint32_t int_mask;
  500. BaseType_t ret = pdTRUE;
  501. i2c_master->trans_done = false;
  502. i2c_ll_get_intr_mask(hal->dev, &int_mask);
  503. i2c_ll_clear_intr_mask(hal->dev, int_mask);
  504. if (int_mask == 0) {
  505. return;
  506. }
  507. if (int_mask == I2C_LL_INTR_NACK) {
  508. atomic_store(&i2c_master->status, I2C_STATUS_ACK_ERROR);
  509. i2c_master->event = I2C_EVENT_NACK;
  510. } else if (int_mask == I2C_LL_INTR_TIMEOUT || int_mask == I2C_LL_INTR_ARBITRATION) {
  511. atomic_store(&i2c_master->status, I2C_STATUS_TIMEOUT);
  512. } else if (int_mask == I2C_LL_INTR_MST_COMPLETE) {
  513. i2c_master->trans_done = true;
  514. i2c_master->event = I2C_EVENT_DONE;
  515. }
  516. if (i2c_master->contains_read == true) {
  517. i2c_isr_receive_handler(i2c_master);
  518. }
  519. if (i2c_master->asnyc_trans) {
  520. i2c_master_dev_handle_t i2c_dev = NULL;
  521. i2c_master_device_list_t *device_item;
  522. xSemaphoreTakeFromISR(i2c_master->bus_lock_mux, &HPTaskAwoken);
  523. SLIST_FOREACH(device_item, &i2c_master->device_list, next) {
  524. if (device_item->device->device_address == i2c_master->i2c_trans.device_address) {
  525. i2c_dev = device_item->device;
  526. break;
  527. }
  528. }
  529. xSemaphoreGiveFromISR(i2c_master->bus_lock_mux, &HPTaskAwoken);
  530. if (i2c_dev == NULL) {
  531. return;
  532. }
  533. i2c_master_event_data_t evt = {
  534. .event = i2c_master->event,
  535. };
  536. s_i2c_send_command_async(i2c_master, &HPTaskAwoken);
  537. if (i2c_master->trans_done) {
  538. if (i2c_dev->on_trans_done) {
  539. i2c_dev->on_trans_done(i2c_dev, &evt, i2c_dev->user_ctx);
  540. }
  541. if (i2c_master->new_queue && i2c_master->num_trans_inqueue > 0 && i2c_master->in_progress == false) {
  542. i2c_transaction_t t = {};
  543. i2c_master->num_trans_inqueue--;
  544. i2c_master->new_queue = false;
  545. t.cmd_count = 0;
  546. t.device_address = 0;
  547. t.ops = NULL;
  548. ret = xQueueReceiveFromISR(i2c_master->trans_queues[I2C_TRANS_QUEUE_PROGRESS], &t, &HPTaskAwoken);
  549. if (ret == pdTRUE) {
  550. i2c_master->queue_trans = true;
  551. atomic_init(&i2c_master->trans_idx, 0);
  552. atomic_store(&i2c_master->status, I2C_STATUS_IDLE);
  553. i2c_master->cmd_idx = 0;
  554. i2c_master->rx_cnt = 0;
  555. i2c_master->read_len_static = 0;
  556. i2c_ll_txfifo_rst(hal->dev);
  557. i2c_ll_rxfifo_rst(hal->dev);
  558. i2c_ll_enable_intr_mask(hal->dev, I2C_LL_MASTER_EVENT_INTR);
  559. i2c_master->i2c_trans = t;
  560. memcpy(i2c_master->i2c_ops, t.ops, t.cmd_count * sizeof(i2c_operation_t));
  561. s_i2c_send_command_async(i2c_master, &HPTaskAwoken);
  562. }
  563. }
  564. }
  565. } else {
  566. xSemaphoreGiveFromISR(i2c_master->cmd_semphr, &HPTaskAwoken);
  567. }
  568. if (HPTaskAwoken == pdTRUE) {
  569. portYIELD_FROM_ISR();
  570. }
  571. }
  572. static esp_err_t i2c_param_master_config(i2c_bus_handle_t handle, const i2c_master_bus_config_t *i2c_conf)
  573. {
  574. i2c_hal_context_t *hal = &handle->hal;
  575. ESP_RETURN_ON_ERROR(i2c_common_set_pins(handle), TAG, "i2c master set pin failed");
  576. ESP_RETURN_ON_ERROR(i2c_select_periph_clock(handle, i2c_conf->clk_source), TAG, "i2c select clock failed");
  577. handle->clk_src = i2c_conf->clk_source;
  578. portENTER_CRITICAL(&handle->spinlock);
  579. i2c_hal_master_init(hal);
  580. i2c_ll_update(hal->dev);
  581. portEXIT_CRITICAL(&handle->spinlock);
  582. return ESP_OK;
  583. }
  584. static esp_err_t i2c_master_bus_destroy(i2c_master_bus_handle_t bus_handle)
  585. {
  586. ESP_RETURN_ON_FALSE(bus_handle, ESP_ERR_INVALID_ARG, TAG, "no memory for i2c master bus");
  587. i2c_master_bus_handle_t i2c_master = bus_handle;
  588. if(i2c_release_bus_handle(i2c_master->base) == 0) {
  589. if (i2c_master) {
  590. if (i2c_master->base->intr_handle) {
  591. ESP_RETURN_ON_ERROR(esp_intr_free(i2c_master->base->intr_handle), TAG, "delete interrupt service failed");
  592. }
  593. if (i2c_master->base->pm_lock) {
  594. ESP_RETURN_ON_ERROR(esp_pm_lock_delete(i2c_master->base->pm_lock), TAG, "delete pm_lock failed");
  595. }
  596. if (i2c_master->bus_lock_mux) {
  597. vSemaphoreDeleteWithCaps(i2c_master->bus_lock_mux);
  598. i2c_master->bus_lock_mux = NULL;
  599. }
  600. if (i2c_master->cmd_semphr) {
  601. vSemaphoreDeleteWithCaps(i2c_master->cmd_semphr);
  602. i2c_master->cmd_semphr = NULL;
  603. }
  604. if (i2c_master->queues_storage) {
  605. free(i2c_master->queues_storage);
  606. }
  607. if (i2c_master->i2c_anyc_ops) {
  608. for (int i = 0; i < i2c_master->index; i++) {
  609. if (i2c_master->i2c_anyc_ops[i]) {
  610. free(i2c_master->i2c_anyc_ops[i]);
  611. }
  612. }
  613. free(i2c_master->i2c_anyc_ops);
  614. }
  615. if (i2c_master->anyc_write_buffer) {
  616. for (int i = 0; i < i2c_master->index; i++) {
  617. if (i2c_master->anyc_write_buffer[i]) {
  618. free(i2c_master->anyc_write_buffer[i]);
  619. }
  620. }
  621. free(i2c_master->anyc_write_buffer);
  622. }
  623. for (int i = 0; i < I2C_TRANS_QUEUE_MAX; i++) {
  624. if (i2c_master->trans_queues[i]) {
  625. vQueueDelete(i2c_master->trans_queues[i]);
  626. }
  627. }
  628. bus_handle = NULL;
  629. }
  630. free(i2c_master);
  631. } else {
  632. free(i2c_master);
  633. }
  634. return ESP_OK;
  635. }
  636. static esp_err_t s_i2c_asynchronous_transaction(i2c_master_dev_handle_t i2c_dev, i2c_operation_t *i2c_ops, size_t ops_dim, int timeout_ms)
  637. {
  638. if (i2c_dev->master_bus->sent_all == true && i2c_dev->master_bus->num_trans_inqueue == 0) {
  639. memcpy(i2c_dev->master_bus->i2c_ops, i2c_ops, sizeof(i2c_operation_t) * ops_dim);
  640. i2c_dev->master_bus->addr_10bits_bus = i2c_dev->addr_10bits;
  641. i2c_dev->master_bus->i2c_trans = (i2c_transaction_t) {
  642. .device_address = i2c_dev->device_address,
  643. .ops = i2c_dev->master_bus->i2c_ops,
  644. .cmd_count = ops_dim,
  645. };
  646. i2c_dev->master_bus->sent_all = false;
  647. i2c_dev->master_bus->trans_finish = false;
  648. i2c_dev->master_bus->queue_trans = false;
  649. ESP_RETURN_ON_ERROR(s_i2c_transaction_start(i2c_dev, timeout_ms), TAG, "I2C transaction failed");
  650. } else {
  651. i2c_dev->master_bus->i2c_anyc_ops[i2c_dev->master_bus->index]=(i2c_operation_t(*))heap_caps_calloc(1, sizeof(i2c_operation_t) * 6, I2C_MEM_ALLOC_CAPS);
  652. memcpy(i2c_dev->master_bus->i2c_anyc_ops[i2c_dev->master_bus->index], i2c_ops, sizeof(i2c_operation_t) * ops_dim);
  653. i2c_transaction_t i2c_queue_pre;
  654. if (i2c_dev->master_bus->num_trans_inflight < i2c_dev->master_bus->queue_size) {
  655. ESP_RETURN_ON_FALSE(xQueueReceive(i2c_dev->master_bus->trans_queues[I2C_TRANS_QUEUE_READY], &i2c_queue_pre, portMAX_DELAY) == pdTRUE, ESP_FAIL, TAG, "no transaction in the ready queue");
  656. } else {
  657. ESP_RETURN_ON_FALSE(xQueueReceive(i2c_dev->master_bus->trans_queues[I2C_TRANS_QUEUE_COMPLETE], &i2c_queue_pre, portMAX_DELAY) == pdTRUE, ESP_FAIL, TAG, "recycle transaction from done queue failed");
  658. i2c_dev->master_bus->num_trans_inflight--;
  659. }
  660. i2c_queue_pre = (i2c_transaction_t) {
  661. .device_address = i2c_dev->device_address,
  662. .ops = i2c_dev->master_bus->i2c_anyc_ops[i2c_dev->master_bus->index],
  663. .cmd_count = ops_dim,
  664. };
  665. i2c_dev->master_bus->index++;
  666. if (xQueueSend(i2c_dev->master_bus->trans_queues[I2C_TRANS_QUEUE_PROGRESS], &i2c_queue_pre, portMAX_DELAY) == pdTRUE) {
  667. i2c_dev->master_bus->num_trans_inflight++;
  668. i2c_dev->master_bus->num_trans_inqueue++;
  669. if (i2c_dev->master_bus->sent_all == true) {
  670. // Oh no, you cannot get the queue from ISR, so you get queue here.
  671. xQueueReceive(i2c_dev->master_bus->trans_queues[I2C_TRANS_QUEUE_PROGRESS], &i2c_queue_pre, portMAX_DELAY);
  672. i2c_dev->master_bus->num_trans_inflight--;
  673. i2c_dev->master_bus->num_trans_inqueue--;
  674. i2c_dev->master_bus->sent_all = false;
  675. i2c_dev->master_bus->trans_finish = false;
  676. i2c_dev->master_bus->queue_trans = false;
  677. ESP_RETURN_ON_ERROR(s_i2c_transaction_start(i2c_dev, timeout_ms), TAG, "I2C transaction failed");
  678. }
  679. } else {
  680. ESP_RETURN_ON_FALSE(xQueueSend(i2c_dev->master_bus->trans_queues[I2C_TRANS_QUEUE_READY], &i2c_queue_pre, 0) == pdTRUE, ESP_ERR_INVALID_STATE, TAG, "ready queue full");
  681. }
  682. }
  683. return ESP_OK;
  684. }
  685. static esp_err_t s_i2c_synchronous_transaction(i2c_master_dev_handle_t i2c_dev, i2c_operation_t *i2c_ops, size_t ops_dim, int timeout_ms)
  686. {
  687. i2c_dev->master_bus->trans_done = false;
  688. TickType_t ticks_to_wait = (timeout_ms == -1) ? portMAX_DELAY : pdMS_TO_TICKS(timeout_ms);
  689. if (xSemaphoreTake(i2c_dev->master_bus->bus_lock_mux, ticks_to_wait) != pdTRUE) {
  690. return ESP_ERR_TIMEOUT;
  691. }
  692. memcpy(i2c_dev->master_bus->i2c_ops, i2c_ops, sizeof(i2c_operation_t) * ops_dim);
  693. i2c_dev->master_bus->addr_10bits_bus = i2c_dev->addr_10bits;
  694. i2c_dev->master_bus->i2c_trans = (i2c_transaction_t) {
  695. .device_address = i2c_dev->device_address,
  696. .ops = i2c_dev->master_bus->i2c_ops,
  697. .cmd_count = ops_dim,
  698. };
  699. i2c_dev->master_bus->sent_all = false;
  700. i2c_dev->master_bus->trans_finish = false;
  701. i2c_dev->master_bus->queue_trans = false;
  702. ESP_RETURN_ON_ERROR(s_i2c_transaction_start(i2c_dev, timeout_ms), TAG, "I2C transaction failed");
  703. xSemaphoreGive(i2c_dev->master_bus->bus_lock_mux);
  704. return ESP_OK;
  705. }
  706. esp_err_t i2c_new_master_bus(const i2c_master_bus_config_t *bus_config, i2c_master_bus_handle_t *ret_bus_handle)
  707. {
  708. #if CONFIG_I2C_ENABLE_DEBUG_LOG
  709. esp_log_level_set(TAG, ESP_LOG_DEBUG);
  710. #endif
  711. esp_err_t ret = ESP_OK;
  712. i2c_master_bus_t *i2c_master = NULL;
  713. i2c_port_num_t i2c_port_num = bus_config->i2c_port;
  714. ESP_RETURN_ON_FALSE(bus_config, ESP_ERR_INVALID_ARG, TAG, "invalid argument");
  715. ESP_RETURN_ON_FALSE((bus_config->i2c_port < SOC_I2C_NUM || bus_config->i2c_port == -1), ESP_ERR_INVALID_ARG, TAG, "invalid i2c port number");
  716. ESP_RETURN_ON_FALSE(GPIO_IS_VALID_GPIO(bus_config->sda_io_num) && GPIO_IS_VALID_GPIO(bus_config->scl_io_num), ESP_ERR_INVALID_ARG, TAG, "invalid SDA/SCL pin number");
  717. bool bus_occupied = false;
  718. bool bus_found = false;
  719. i2c_master = heap_caps_calloc(1, sizeof(i2c_master_bus_t) + 20 * sizeof(i2c_transaction_t), I2C_MEM_ALLOC_CAPS);
  720. ESP_RETURN_ON_FALSE(i2c_master, ESP_ERR_NO_MEM, TAG, "no memory for i2c master bus");
  721. _lock_acquire(&s_i2c_bus_acquire);
  722. if (i2c_port_num == -1) {
  723. for (int i = 0; i < SOC_I2C_NUM; i++) {
  724. bus_occupied = i2c_bus_occupied(i);
  725. if (bus_occupied == false) {
  726. ret = i2c_acquire_bus_handle(i, &i2c_master->base, I2C_BUS_MODE_MASTER);
  727. if (ret != ESP_OK) {
  728. ESP_LOGE(TAG, "acquire bus failed");
  729. _lock_release(&s_i2c_bus_acquire);
  730. goto err;
  731. }
  732. bus_found = true;
  733. i2c_port_num = i;
  734. break;
  735. }
  736. }
  737. ESP_GOTO_ON_FALSE((bus_found == true), ESP_ERR_NOT_FOUND, err, TAG, "acquire bus failed, no free bus");
  738. } else {
  739. ret = i2c_acquire_bus_handle(i2c_port_num, &i2c_master->base, I2C_BUS_MODE_MASTER);
  740. if (ret != ESP_OK) {
  741. ESP_LOGE(TAG, "acquire bus failed");
  742. _lock_release(&s_i2c_bus_acquire);
  743. goto err;
  744. }
  745. }
  746. _lock_release(&s_i2c_bus_acquire);
  747. i2c_hal_context_t *hal = &i2c_master->base->hal;
  748. i2c_master->base->scl_num = bus_config->scl_io_num;
  749. i2c_master->base->sda_num = bus_config->sda_io_num;
  750. i2c_master->base->pull_up_enable = bus_config->flags.enable_internal_pullup;
  751. ESP_GOTO_ON_ERROR(i2c_param_master_config(i2c_master->base, bus_config), err, TAG, "i2c configure parameter failed");
  752. i2c_master->bus_lock_mux = xSemaphoreCreateBinaryWithCaps(I2C_MEM_ALLOC_CAPS);
  753. ESP_GOTO_ON_FALSE(i2c_master->bus_lock_mux, ESP_ERR_NO_MEM, err, TAG, "No memory for binary semaphore");
  754. xSemaphoreGive(i2c_master->bus_lock_mux);
  755. i2c_master->cmd_semphr = xSemaphoreCreateBinaryWithCaps(I2C_MEM_ALLOC_CAPS);
  756. ESP_GOTO_ON_FALSE(i2c_master->cmd_semphr, ESP_ERR_NO_MEM, err, TAG, "no memory for i2c semaphore struct");
  757. portENTER_CRITICAL(&i2c_master->base->spinlock);
  758. i2c_ll_clear_intr_mask(hal->dev, I2C_LL_MASTER_EVENT_INTR);
  759. portEXIT_CRITICAL(&i2c_master->base->spinlock);
  760. if (bus_config->intr_priority) {
  761. ESP_RETURN_ON_FALSE(1 << (bus_config->intr_priority) & I2C_ALLOW_INTR_PRIORITY_MASK, ESP_ERR_INVALID_ARG, TAG, "invalid interrupt priority:%d", bus_config->intr_priority);
  762. }
  763. xSemaphoreTake(i2c_master->bus_lock_mux, portMAX_DELAY);
  764. SLIST_INIT(&i2c_master->device_list);
  765. xSemaphoreGive(i2c_master->bus_lock_mux);
  766. // Initialize the queue
  767. if (bus_config->trans_queue_depth) {
  768. i2c_master->asnyc_trans = true;
  769. i2c_master->sent_all = true;
  770. i2c_master->trans_finish = true;
  771. i2c_master->new_queue = true;
  772. i2c_master->queue_size = bus_config->trans_queue_depth;
  773. i2c_master->queues_storage = (uint8_t*)heap_caps_calloc(bus_config->trans_queue_depth * I2C_TRANS_QUEUE_MAX, sizeof(i2c_transaction_t), I2C_MEM_ALLOC_CAPS);
  774. ESP_RETURN_ON_FALSE(i2c_master->queues_storage, ESP_ERR_NO_MEM, TAG, "no mem for queue storage");
  775. i2c_transaction_t **pp_trans_desc = (i2c_transaction_t **)i2c_master->queues_storage;
  776. for (int i = 0; i < I2C_TRANS_QUEUE_MAX; i++) {
  777. i2c_master->trans_queues[i] = xQueueCreate(bus_config->trans_queue_depth, sizeof(i2c_transaction_t));
  778. pp_trans_desc += bus_config->trans_queue_depth;
  779. // sanity check
  780. assert(i2c_master->trans_queues[i]);
  781. }
  782. i2c_transaction_t trans_pre = {};
  783. for (int i = 0; i < bus_config->trans_queue_depth ; i++) {
  784. trans_pre = i2c_master->i2c_trans_pool[i];
  785. ESP_RETURN_ON_FALSE(xQueueSend(i2c_master->trans_queues[I2C_TRANS_QUEUE_READY], &trans_pre, 0) == pdTRUE,
  786. ESP_ERR_INVALID_STATE, TAG, "ready queue full");
  787. }
  788. i2c_master->i2c_anyc_ops = (i2c_operation_t(**))heap_caps_calloc(bus_config->trans_queue_depth, sizeof(i2c_operation_t*), I2C_MEM_ALLOC_CAPS);
  789. i2c_master->anyc_write_buffer = (uint8_t**)heap_caps_calloc(bus_config->trans_queue_depth, sizeof(uint8_t*), I2C_MEM_ALLOC_CAPS);
  790. }
  791. int isr_flags = I2C_INTR_ALLOC_FLAG;
  792. if (bus_config->intr_priority) {
  793. isr_flags |= 1 << (bus_config->intr_priority);
  794. }
  795. ret = esp_intr_alloc_intrstatus(i2c_periph_signal[i2c_port_num].irq, isr_flags, (uint32_t)i2c_ll_get_interrupt_status_reg(hal->dev), I2C_LL_MASTER_EVENT_INTR, i2c_master_isr_handler_default, i2c_master, &i2c_master->base->intr_handle);
  796. ESP_GOTO_ON_ERROR(ret, err, TAG, "install i2c master interrupt failed");
  797. atomic_init(&i2c_master->status, I2C_STATUS_IDLE);
  798. i2c_ll_enable_intr_mask(hal->dev, I2C_LL_MASTER_EVENT_INTR);
  799. i2c_ll_master_set_filter(hal->dev, bus_config->glitch_ignore_cnt);
  800. xSemaphoreGive(i2c_master->cmd_semphr);
  801. *ret_bus_handle = i2c_master;
  802. return ESP_OK;
  803. err:
  804. if (i2c_master) {
  805. i2c_master_bus_destroy(i2c_master);
  806. }
  807. return ret;
  808. }
  809. esp_err_t i2c_master_bus_add_device(i2c_master_bus_handle_t bus_handle, const i2c_device_config_t *dev_config, i2c_master_dev_handle_t *ret_handle)
  810. {
  811. esp_err_t ret = ESP_OK;
  812. ESP_RETURN_ON_FALSE((bus_handle != NULL), ESP_ERR_INVALID_ARG, TAG, "this bus is not initialized, please call `i2c_new_master_bus`");
  813. if(bus_handle->base->bus_mode != I2C_BUS_MODE_MASTER) {
  814. ESP_LOGE(TAG, "This is not master bus!");
  815. return ESP_ERR_INVALID_ARG;
  816. }
  817. i2c_master_bus_t *i2c_master = bus_handle;
  818. i2c_master_dev_t *i2c_dev = heap_caps_calloc(1, sizeof(i2c_master_dev_t), I2C_MEM_ALLOC_CAPS);
  819. ESP_GOTO_ON_FALSE(i2c_dev, ESP_ERR_NO_MEM, err, TAG, "no memory for i2c master device");
  820. i2c_dev->device_address = dev_config->device_address;
  821. i2c_dev->scl_speed_hz = dev_config->scl_speed_hz;
  822. i2c_dev->addr_10bits = dev_config->dev_addr_length;
  823. i2c_dev->master_bus = i2c_master;
  824. i2c_master_device_list_t *device_item = (i2c_master_device_list_t *)calloc(1, sizeof(i2c_master_device_list_t));
  825. ESP_RETURN_ON_FALSE((device_item != NULL), ESP_ERR_NO_MEM, TAG, "no memory for i2c device item`");
  826. device_item->device = i2c_dev;
  827. xSemaphoreTake(bus_handle->bus_lock_mux, portMAX_DELAY);
  828. SLIST_INSERT_HEAD(&bus_handle->device_list, device_item, next);
  829. xSemaphoreGive(bus_handle->bus_lock_mux);
  830. *ret_handle = i2c_dev;
  831. return ret;
  832. err:
  833. if (i2c_dev) {
  834. i2c_master_bus_rm_device(i2c_dev);
  835. }
  836. return ret;
  837. }
  838. esp_err_t i2c_master_bus_rm_device(i2c_master_dev_handle_t handle)
  839. {
  840. ESP_RETURN_ON_FALSE((handle != NULL), ESP_ERR_INVALID_ARG, TAG, "this device is not initialized");
  841. ESP_RETURN_ON_FALSE((((int)atomic_load(&handle->master_bus->status) > (int)I2C_STATUS_START)), ESP_ERR_INVALID_STATE, TAG, "Wrong I2C status, cannot delete device");
  842. i2c_master_bus_handle_t i2c_master = handle->master_bus;
  843. i2c_master_device_list_t *device_item;
  844. xSemaphoreTake(handle->master_bus->bus_lock_mux, portMAX_DELAY);
  845. SLIST_FOREACH(device_item, &i2c_master->device_list, next) {
  846. if (handle == device_item->device) {
  847. SLIST_REMOVE(&i2c_master->device_list, device_item, i2c_master_device_list, next);
  848. free(device_item);
  849. break;
  850. }
  851. }
  852. xSemaphoreGive(handle->master_bus->bus_lock_mux);
  853. if (handle) {
  854. free(handle);
  855. handle = NULL;
  856. }
  857. return ESP_OK;
  858. }
  859. esp_err_t i2c_del_master_bus(i2c_master_bus_handle_t bus_handle)
  860. {
  861. ESP_LOGD(TAG, "del i2c bus(%d)", bus_handle->base->port_num);
  862. ESP_RETURN_ON_ERROR(i2c_master_bus_destroy(bus_handle), TAG, "destroy i2c bus failed");
  863. return ESP_OK;
  864. }
  865. esp_err_t i2c_master_bus_reset(i2c_master_bus_handle_t handle)
  866. {
  867. ESP_RETURN_ON_FALSE((handle != NULL), ESP_ERR_INVALID_ARG, TAG, "This bus is not initialized");
  868. // Reset I2C master bus
  869. ESP_RETURN_ON_ERROR(s_i2c_hw_fsm_reset(handle), TAG, "I2C master bus reset failed");
  870. // Reset I2C status state
  871. atomic_store(&handle->status, I2C_STATUS_IDLE);
  872. return ESP_OK;
  873. }
  874. esp_err_t i2c_master_transmit(i2c_master_dev_handle_t i2c_dev, const uint8_t *write_buffer, size_t write_size, int xfer_timeout_ms)
  875. {
  876. ESP_RETURN_ON_FALSE(i2c_dev != NULL, ESP_ERR_INVALID_ARG, TAG, "i2c handle not initialized");
  877. ESP_RETURN_ON_FALSE((write_buffer != NULL) && (write_size > 0), ESP_ERR_INVALID_ARG, TAG, "i2c transmit buffer or size invalid");
  878. if (i2c_dev->master_bus->asnyc_trans == false) {
  879. i2c_operation_t i2c_ops[] = {
  880. {.hw_cmd = I2C_TRANS_START_COMMAND},
  881. {.hw_cmd = I2C_TRANS_WRITE_COMMAND(false), .data = (uint8_t *)write_buffer, .total_bytes = write_size},
  882. {.hw_cmd = I2C_TRANS_STOP_COMMAND},
  883. };
  884. ESP_RETURN_ON_ERROR(s_i2c_synchronous_transaction(i2c_dev, i2c_ops, DIM(i2c_ops), xfer_timeout_ms), TAG, "I2C transaction failed");
  885. } else {
  886. i2c_dev->master_bus->anyc_write_buffer[i2c_dev->master_bus->index] = (uint8_t*)heap_caps_calloc(1, sizeof(uint8_t)*write_size, I2C_MEM_ALLOC_CAPS);
  887. memcpy(i2c_dev->master_bus->anyc_write_buffer[i2c_dev->master_bus->index], write_buffer, write_size);
  888. i2c_operation_t i2c_ops[] = {
  889. {.hw_cmd = I2C_TRANS_START_COMMAND},
  890. {.hw_cmd = I2C_TRANS_WRITE_COMMAND(false), .data = (uint8_t *)i2c_dev->master_bus->anyc_write_buffer[i2c_dev->master_bus->index], .total_bytes = write_size},
  891. {.hw_cmd = I2C_TRANS_STOP_COMMAND},
  892. };
  893. ESP_RETURN_ON_ERROR(s_i2c_asynchronous_transaction(i2c_dev, i2c_ops, DIM(i2c_ops), xfer_timeout_ms), TAG, "I2C transaction failed");
  894. }
  895. return ESP_OK;
  896. }
  897. esp_err_t i2c_master_transmit_receive(i2c_master_dev_handle_t i2c_dev, const uint8_t *write_buffer, size_t write_size, uint8_t *read_buffer, size_t read_size, int xfer_timeout_ms)
  898. {
  899. ESP_RETURN_ON_FALSE(i2c_dev != NULL, ESP_ERR_INVALID_ARG, TAG, "i2c handle not initialized");
  900. ESP_RETURN_ON_FALSE((write_buffer != NULL) && (write_size > 0), ESP_ERR_INVALID_ARG, TAG, "i2c transmit buffer or size invalid");
  901. ESP_RETURN_ON_FALSE((read_buffer != NULL) && (read_size > 0), ESP_ERR_INVALID_ARG, TAG, "i2c receive buffer or size invalid");
  902. if (i2c_dev->master_bus->asnyc_trans == false) {
  903. i2c_operation_t i2c_ops[] = {
  904. {.hw_cmd = I2C_TRANS_START_COMMAND},
  905. {.hw_cmd = I2C_TRANS_WRITE_COMMAND(false), .data = (uint8_t *)write_buffer, .total_bytes = write_size},
  906. {.hw_cmd = I2C_TRANS_START_COMMAND},
  907. {.hw_cmd = I2C_TRANS_READ_COMMAND(ACK_VAL), .data = read_buffer, .total_bytes = read_size - 1},
  908. {.hw_cmd = I2C_TRANS_READ_COMMAND(NACK_VAL), .data = (read_buffer + read_size - 1), .total_bytes = 1},
  909. {.hw_cmd = I2C_TRANS_STOP_COMMAND},
  910. };
  911. ESP_RETURN_ON_ERROR(s_i2c_synchronous_transaction(i2c_dev, i2c_ops, DIM(i2c_ops), xfer_timeout_ms), TAG, "I2C transaction failed");
  912. } else {
  913. i2c_dev->master_bus->anyc_write_buffer[i2c_dev->master_bus->index] = (uint8_t*)heap_caps_calloc(1, sizeof(uint8_t)*write_size, I2C_MEM_ALLOC_CAPS);
  914. memcpy(i2c_dev->master_bus->anyc_write_buffer[i2c_dev->master_bus->index], write_buffer, write_size);
  915. i2c_operation_t i2c_ops[] = {
  916. {.hw_cmd = I2C_TRANS_START_COMMAND},
  917. {.hw_cmd = I2C_TRANS_WRITE_COMMAND(false), .data = (uint8_t *)i2c_dev->master_bus->anyc_write_buffer[i2c_dev->master_bus->index], .total_bytes = write_size},
  918. {.hw_cmd = I2C_TRANS_START_COMMAND},
  919. {.hw_cmd = I2C_TRANS_READ_COMMAND(ACK_VAL), .data = read_buffer, .total_bytes = read_size - 1},
  920. {.hw_cmd = I2C_TRANS_READ_COMMAND(NACK_VAL), .data = (read_buffer + read_size - 1), .total_bytes = 1},
  921. {.hw_cmd = I2C_TRANS_STOP_COMMAND},
  922. };
  923. ESP_RETURN_ON_ERROR(s_i2c_asynchronous_transaction(i2c_dev, i2c_ops, DIM(i2c_ops), xfer_timeout_ms), TAG, "I2C transaction failed");
  924. }
  925. return ESP_OK;
  926. }
  927. esp_err_t i2c_master_receive(i2c_master_dev_handle_t i2c_dev, uint8_t *read_buffer, size_t read_size, int xfer_timeout_ms)
  928. {
  929. ESP_RETURN_ON_FALSE(i2c_dev != NULL, ESP_ERR_INVALID_ARG, TAG, "i2c handle not initialized");
  930. ESP_RETURN_ON_FALSE((read_buffer != NULL) && (read_size > 0), ESP_ERR_INVALID_ARG, TAG, "i2c receive buffer or size invalid");
  931. i2c_operation_t i2c_ops[] = {
  932. {.hw_cmd = I2C_TRANS_START_COMMAND},
  933. {.hw_cmd = I2C_TRANS_READ_COMMAND(ACK_VAL), .data = read_buffer, .total_bytes = read_size - 1},
  934. {.hw_cmd = I2C_TRANS_READ_COMMAND(NACK_VAL), .data = (read_buffer + read_size - 1), .total_bytes = 1},
  935. {.hw_cmd = I2C_TRANS_STOP_COMMAND},
  936. };
  937. if (i2c_dev->master_bus->asnyc_trans == false) {
  938. ESP_RETURN_ON_ERROR(s_i2c_synchronous_transaction(i2c_dev, i2c_ops, DIM(i2c_ops), xfer_timeout_ms), TAG, "I2C transaction failed");
  939. } else {
  940. ESP_RETURN_ON_ERROR(s_i2c_asynchronous_transaction(i2c_dev, i2c_ops, DIM(i2c_ops), xfer_timeout_ms), TAG, "I2C transaction failed");
  941. }
  942. return ESP_OK;
  943. }
  944. esp_err_t i2c_master_probe(i2c_master_bus_handle_t i2c_master, uint16_t address, int xfer_timeout_ms)
  945. {
  946. ESP_RETURN_ON_FALSE(i2c_master != NULL, ESP_ERR_INVALID_ARG, TAG, "i2c handle not initialized");
  947. i2c_operation_t i2c_ops[] = {
  948. {.hw_cmd = I2C_TRANS_START_COMMAND},
  949. {.hw_cmd = I2C_TRANS_STOP_COMMAND},
  950. };
  951. TickType_t ticks_to_wait = (xfer_timeout_ms == -1) ? portMAX_DELAY : pdMS_TO_TICKS(xfer_timeout_ms);
  952. i2c_master->i2c_trans = (i2c_transaction_t) {
  953. .device_address = address,
  954. .ops = i2c_ops,
  955. .cmd_count = DIM(i2c_ops),
  956. };
  957. s_i2c_send_commands(i2c_master, ticks_to_wait);
  958. if (i2c_master->status == I2C_STATUS_ACK_ERROR) {
  959. return ESP_ERR_NOT_FOUND;
  960. }
  961. return ESP_OK;
  962. }
  963. esp_err_t i2c_master_register_event_callbacks(i2c_master_dev_handle_t i2c_dev, const i2c_master_event_callbacks_t *cbs, void *user_data)
  964. {
  965. ESP_RETURN_ON_FALSE(i2c_dev != NULL, ESP_ERR_INVALID_ARG, TAG, "i2c handle not initialized");
  966. if (i2c_dev->master_bus->asnyc_trans == false) {
  967. ESP_LOGE(TAG, "I2C transaction queue is not initialized, so you can't use callback here, please resister the bus again with trans_queue_depth != 0");
  968. return ESP_ERR_INVALID_STATE;
  969. }
  970. #if CONFIG_I2C_ISR_IRAM_SAFE
  971. if (cbs->on_trans_done) {
  972. ESP_RETURN_ON_FALSE(esp_ptr_in_iram(cbs->on_trans_done), ESP_ERR_INVALID_ARG, TAG, "i2c trans done callback not in IRAM");
  973. }
  974. if (user_data) {
  975. ESP_RETURN_ON_FALSE(esp_ptr_internal(user_data), ESP_ERR_INVALID_ARG, TAG, "user context not in internal RAM");
  976. }
  977. #endif // CONFIG_I2C_ISR_IRAM_SAFE
  978. i2c_dev->on_trans_done = cbs->on_trans_done;
  979. i2c_dev->user_ctx = user_data;
  980. return ESP_OK;
  981. }
  982. esp_err_t i2c_master_wait_all_done(i2c_master_bus_handle_t i2c_master, int timeout_ms)
  983. {
  984. ESP_RETURN_ON_FALSE(i2c_master, ESP_ERR_INVALID_ARG, TAG, "invalid argument");
  985. TickType_t wait_ticks = timeout_ms < 0 ? portMAX_DELAY : pdMS_TO_TICKS(timeout_ms);
  986. i2c_transaction_t t;
  987. size_t cnt = i2c_master->num_trans_inflight;
  988. for (size_t i = 0; i < cnt; i++) {
  989. ESP_RETURN_ON_FALSE(xQueueReceive(i2c_master->trans_queues[I2C_TRANS_QUEUE_COMPLETE], &t, wait_ticks) == pdTRUE,
  990. ESP_ERR_TIMEOUT, TAG, "flush timeout");
  991. ESP_RETURN_ON_FALSE(xQueueSend(i2c_master->trans_queues[I2C_TRANS_QUEUE_READY], &t, 0) == pdTRUE,
  992. ESP_ERR_INVALID_STATE, TAG, "ready queue full");
  993. i2c_master->num_trans_inflight--;
  994. }
  995. return ESP_OK;
  996. }