i2c_master.c 49 KB

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