• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2015-2020 Espressif Systems (Shanghai) PTE LTD
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 
7 //     http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 #include <string.h>
15 #include <stdio.h>
16 #include "esp_types.h"
17 #include "esp_attr.h"
18 #include "esp_intr_alloc.h"
19 #include "esp_log.h"
20 #include "malloc.h"
21 #include "esp_osal/esp_osal.h"
22 #include "esp_osal/semphr.h"
23 #include "esp_osal/task.h"
24 #include "ringbuf.h"
25 #include "soc/soc_memory_layout.h"
26 #include "hal/i2c_hal.h"
27 #include "hal/gpio_hal.h"
28 #include "soc/i2c_periph.h"
29 #include "driver/i2c.h"
30 #include "driver/periph_ctrl.h"
31 #include "esp_rom_gpio.h"
32 #include "esp_rom_sys.h"
33 
34 static const char *I2C_TAG = "i2c";
35 #define I2C_CHECK(a, str, ret)  if(!(a)) {                                             \
36         ESP_LOGE(I2C_TAG,"%s(%d): %s", __FUNCTION__, __LINE__, str);                   \
37         return (ret);                                                                  \
38         }
39 
40 /* DRAM_ATTR is required to avoid I2C array placed in flash, due to accessed from ISR */
41 
42 #define I2C_ENTER_CRITICAL_ISR(mux)    portENTER_CRITICAL_ISR(mux)
43 #define I2C_EXIT_CRITICAL_ISR(mux)     portEXIT_CRITICAL_ISR(mux)
44 #define I2C_ENTER_CRITICAL(mux)        portENTER_CRITICAL(mux)
45 #define I2C_EXIT_CRITICAL(mux)         portEXIT_CRITICAL(mux)
46 
47 #define I2C_DRIVER_ERR_STR             "i2c driver install error"
48 #define I2C_DRIVER_MALLOC_ERR_STR      "i2c driver malloc error"
49 #define I2C_NUM_ERROR_STR              "i2c number error"
50 #define I2C_TIMEING_VAL_ERR_STR        "i2c timing value error"
51 #define I2C_ADDR_ERROR_STR             "i2c null address error"
52 #define I2C_DRIVER_NOT_INSTALL_ERR_STR "i2c driver not installed"
53 #define I2C_SLAVE_BUFFER_LEN_ERR_STR   "i2c buffer size too small for slave mode"
54 #define I2C_EVT_QUEUE_ERR_STR          "i2c evt queue error"
55 #define I2C_SEM_ERR_STR                "i2c semaphore error"
56 #define I2C_BUF_ERR_STR                "i2c ringbuffer error"
57 #define I2C_MASTER_MODE_ERR_STR        "Only allowed in master mode"
58 #define I2C_MODE_SLAVE_ERR_STR         "Only allowed in slave mode"
59 #define I2C_CMD_MALLOC_ERR_STR         "i2c command link malloc error"
60 #define I2C_TRANS_MODE_ERR_STR         "i2c trans mode error"
61 #define I2C_MODE_ERR_STR               "i2c mode error"
62 #define I2C_SDA_IO_ERR_STR             "sda gpio number error"
63 #define I2C_SCL_IO_ERR_STR             "scl gpio number error"
64 #define I2C_SCL_SDA_EQUAL_ERR_STR      "scl and sda gpio numbers are the same"
65 #define I2C_CMD_LINK_INIT_ERR_STR      "i2c command link error"
66 #define I2C_GPIO_PULLUP_ERR_STR        "this i2c pin does not support internal pull-up"
67 #define I2C_ACK_TYPE_ERR_STR           "i2c ack type error"
68 #define I2C_DATA_LEN_ERR_STR           "i2c data read length error"
69 #define I2C_PSRAM_BUFFER_WARN_STR      "Using buffer allocated from psram"
70 #define I2C_LOCK_ERR_STR               "Power lock creation error"
71 #define I2C_CLK_FLAG_ERR_STR           "i2c clock choice is invalid, please check flag and frequency"
72 #define I2C_FIFO_FULL_THRESH_VAL       (28)
73 #define I2C_FIFO_EMPTY_THRESH_VAL      (5)
74 #define I2C_IO_INIT_LEVEL              (1)
75 #define I2C_CMD_ALIVE_INTERVAL_TICK    (1000 / portTICK_PERIOD_MS)
76 #define I2C_CMD_EVT_ALIVE              (0)
77 #define I2C_CMD_EVT_DONE               (1)
78 #define I2C_EVT_QUEUE_LEN              (1)
79 #define I2C_SLAVE_TIMEOUT_DEFAULT      (32000)     /* I2C slave timeout value, APB clock cycle number */
80 #define I2C_SLAVE_SDA_SAMPLE_DEFAULT   (10)        /* I2C slave sample time after scl positive edge default value */
81 #define I2C_SLAVE_SDA_HOLD_DEFAULT     (10)        /* I2C slave hold time after scl negative edge default value */
82 #define I2C_MASTER_TOUT_CNUM_DEFAULT   (8)         /* I2C master timeout cycle number of I2C clock, after which the timeout interrupt will be triggered */
83 #define I2C_ACKERR_CNT_MAX             (10)
84 #define I2C_FILTER_CYC_NUM_DEF         (7)         /* The number of apb cycles filtered by default*/
85 #define I2C_CLR_BUS_SCL_NUM            (9)
86 #define I2C_CLR_BUS_HALF_PERIOD_US     (5)
87 
88 #define I2C_CONTEX_INIT_DEF(uart_num) {\
89     .hal.dev = I2C_LL_GET_HW(uart_num),\
90     .spinlock = portMUX_INITIALIZER_UNLOCKED,\
91     .hw_enabled = false,\
92 }
93 
94 // Freq limitation when using different clock sources
95 #define I2C_CLK_LIMIT_REF_TICK            (1 * 1000 * 1000 / 20)    /*!< Limited by REF_TICK, no more than REF_TICK/20*/
96 #define I2C_CLK_LIMIT_APB                 (80 * 1000 * 1000 / 20)   /*!< Limited by APB, no more than APB/20*/
97 #define I2C_CLK_LIMIT_RTC                 (20 * 1000 * 1000 / 20)   /*!< Limited by RTC, no more than RTC/20*/
98 #define I2C_CLK_LIMIT_XTAL                (40 * 1000 * 1000 / 20)   /*!< Limited by RTC, no more than XTAL/20*/
99 
100 typedef struct {
101     i2c_hw_cmd_t hw_cmd;
102     uint8_t *data;     /*!< data address */
103     uint8_t byte_cmd;  /*!< to save cmd for one byte command mode */
104 } i2c_cmd_t;
105 
106 typedef struct i2c_cmd_link {
107     i2c_cmd_t cmd;              /*!< command in current cmd link */
108     struct i2c_cmd_link *next;  /*!< next cmd link */
109 } i2c_cmd_link_t;
110 
111 typedef struct {
112     i2c_cmd_link_t *head;     /*!< head of the command link */
113     i2c_cmd_link_t *cur;      /*!< last node of the command link */
114     i2c_cmd_link_t *free;     /*!< the first node to free of the command link */
115 } i2c_cmd_desc_t;
116 
117 typedef enum {
118     I2C_STATUS_READ,      /*!< read status for current master command */
119     I2C_STATUS_WRITE,     /*!< write status for current master command */
120     I2C_STATUS_IDLE,      /*!< idle status for current master command */
121     I2C_STATUS_ACK_ERROR, /*!< ack error status for current master command */
122     I2C_STATUS_DONE,      /*!< I2C command done */
123     I2C_STATUS_TIMEOUT,   /*!< I2C bus status error, and operation timeout */
124 } i2c_status_t;
125 
126 typedef struct {
127     int type;
128 } i2c_cmd_evt_t;
129 
130 typedef struct {
131     int i2c_num;                     /*!< I2C port number */
132     int mode;                        /*!< I2C mode, master or slave */
133     intr_handle_t intr_handle;       /*!< I2C interrupt handle*/
134     int cmd_idx;                     /*!< record current command index, for master mode */
135     int status;                      /*!< record current command status, for master mode */
136     int rx_cnt;                      /*!< record current read index, for master mode */
137     uint8_t data_buf[SOC_I2C_FIFO_LEN ];  /*!< a buffer to store i2c fifo data */
138 
139     i2c_cmd_desc_t cmd_link;         /*!< I2C command link */
140     QueueHandle_t cmd_evt_queue;     /*!< I2C command event queue */
141 #if CONFIG_SPIRAM_USE_MALLOC
142     uint8_t *evt_queue_storage;      /*!< The buffer that will hold the items in the queue */
143     int intr_alloc_flags;            /*!< Used to allocate the interrupt */
144     StaticQueue_t evt_queue_buffer;  /*!< The buffer that will hold the queue structure*/
145 #endif
146     xSemaphoreHandle cmd_mux;        /*!< semaphore to lock command process */
147 #ifdef CONFIG_PM_ENABLE
148     esp_pm_lock_handle_t pm_lock;
149 #endif
150 
151     xSemaphoreHandle slv_rx_mux;     /*!< slave rx buffer mux */
152     xSemaphoreHandle slv_tx_mux;     /*!< slave tx buffer mux */
153     size_t rx_buf_length;            /*!< rx buffer length */
154     RingbufHandle_t rx_ring_buf;     /*!< rx ringbuffer handler of slave mode */
155     size_t tx_buf_length;            /*!< tx buffer length */
156     RingbufHandle_t tx_ring_buf;     /*!< tx ringbuffer handler of slave mode */
157 } i2c_obj_t;
158 
159 typedef struct {
160     i2c_hal_context_t hal;      /*!< I2C hal context */
161     portMUX_TYPE spinlock;
162     bool hw_enabled;
163 #if !SOC_I2C_SUPPORT_HW_CLR_BUS
164     int scl_io_num;
165     int sda_io_num;
166 #endif
167 } i2c_context_t;
168 
169 typedef struct
170 {
171     uint8_t character;          /*!< I2C source clock characteristic */
172     uint32_t clk_freq;          /*!< I2C source clock frequency */
173 } i2c_clk_alloc_t;
174 
175 static i2c_context_t i2c_context[I2C_NUM_MAX] = {
176     I2C_CONTEX_INIT_DEF(I2C_NUM_0),
177 #if I2C_NUM_MAX > 1
178     I2C_CONTEX_INIT_DEF(I2C_NUM_1),
179 #endif
180 };
181 
182 // i2c clock characteristic, The order is the same as i2c_sclk_t.
183 static i2c_clk_alloc_t i2c_clk_alloc[I2C_SCLK_MAX] = {
184     {0, 0},
185 #if SOC_I2C_SUPPORT_APB
186     {0, I2C_CLK_LIMIT_APB},                                                                /*!< I2C APB clock characteristic*/
187 #endif
188 #if SOC_I2C_SUPPORT_XTAL
189     {0, I2C_CLK_LIMIT_XTAL},                                                               /*!< I2C XTAL characteristic*/
190 #endif
191 #if SOC_I2C_SUPPORT_RTC
192     {I2C_SCLK_SRC_FLAG_LIGHT_SLEEP | I2C_SCLK_SRC_FLAG_AWARE_DFS, I2C_CLK_LIMIT_RTC},      /*!< I2C 20M RTC characteristic*/
193 #endif
194 #if SOC_I2C_SUPPORT_REF_TICK
195     {I2C_SCLK_SRC_FLAG_AWARE_DFS, I2C_CLK_LIMIT_REF_TICK},                                 /*!< I2C REF_TICK characteristic*/
196 #endif
197 };
198 
199 static i2c_obj_t *p_i2c_obj[I2C_NUM_MAX] = {0};
200 static void i2c_isr_handler_default(void *arg);
201 static void IRAM_ATTR i2c_master_cmd_begin_static(i2c_port_t i2c_num);
202 static esp_err_t IRAM_ATTR i2c_hw_fsm_reset(i2c_port_t i2c_num);
203 
i2c_hw_disable(i2c_port_t i2c_num)204 static void i2c_hw_disable(i2c_port_t i2c_num)
205 {
206     I2C_ENTER_CRITICAL(&(i2c_context[i2c_num].spinlock));
207     if (i2c_context[i2c_num].hw_enabled != false) {
208         periph_module_disable(i2c_periph_signal[i2c_num].module);
209         i2c_context[i2c_num].hw_enabled = false;
210     }
211     I2C_EXIT_CRITICAL(&(i2c_context[i2c_num].spinlock));
212 }
213 
i2c_hw_enable(i2c_port_t i2c_num)214 static void i2c_hw_enable(i2c_port_t i2c_num)
215 {
216     I2C_ENTER_CRITICAL(&(i2c_context[i2c_num].spinlock));
217     if (i2c_context[i2c_num].hw_enabled != true) {
218         periph_module_enable(i2c_periph_signal[i2c_num].module);
219         i2c_context[i2c_num].hw_enabled = true;
220     }
221     I2C_EXIT_CRITICAL(&(i2c_context[i2c_num].spinlock));
222 }
223 
224 /*
225     For i2c master mode, we don't need to use a buffer for the data, the APIs will execute the master commands
226 and return after all of the commands have been sent out or when error occurs. So when we send master commands,
227 we should free or modify the source data only after the i2c_master_cmd_begin function returns.
228     For i2c slave mode, we need a data buffer to stash the sending and receiving data, because the hardware fifo
229 has only 32 bytes.
230 */
i2c_driver_install(i2c_port_t i2c_num,i2c_mode_t mode,size_t slv_rx_buf_len,size_t slv_tx_buf_len,int intr_alloc_flags)231 esp_err_t i2c_driver_install(i2c_port_t i2c_num, i2c_mode_t mode, size_t slv_rx_buf_len, size_t slv_tx_buf_len,
232                              int intr_alloc_flags)
233 {
234     I2C_CHECK(i2c_num < I2C_NUM_MAX, I2C_NUM_ERROR_STR, ESP_ERR_INVALID_ARG);
235     I2C_CHECK(mode == I2C_MODE_MASTER || ( slv_rx_buf_len > 100 || slv_tx_buf_len > 100 ), I2C_SLAVE_BUFFER_LEN_ERR_STR,
236               ESP_ERR_INVALID_ARG);
237     if (p_i2c_obj[i2c_num] == NULL) {
238 
239 #if !CONFIG_SPIRAM_USE_MALLOC
240         p_i2c_obj[i2c_num] = (i2c_obj_t *) calloc(1, sizeof(i2c_obj_t));
241 #else
242         if ( !(intr_alloc_flags & ESP_INTR_FLAG_IRAM) ) {
243             p_i2c_obj[i2c_num] = (i2c_obj_t *) calloc(1, sizeof(i2c_obj_t));
244         } else {
245             p_i2c_obj[i2c_num] = (i2c_obj_t *) heap_caps_calloc(1, sizeof(i2c_obj_t), MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT);
246         }
247 #endif
248         if (p_i2c_obj[i2c_num] == NULL) {
249             ESP_LOGE(I2C_TAG, I2C_DRIVER_MALLOC_ERR_STR);
250             return ESP_FAIL;
251         }
252         i2c_obj_t *p_i2c = p_i2c_obj[i2c_num];
253         p_i2c->i2c_num = i2c_num;
254         p_i2c->mode = mode;
255         p_i2c->cmd_idx = 0;
256         p_i2c->rx_cnt = 0;
257         p_i2c->status = I2C_STATUS_IDLE;
258 
259 #if CONFIG_SPIRAM_USE_MALLOC
260         p_i2c->intr_alloc_flags = intr_alloc_flags;
261 #endif
262 
263         if (mode == I2C_MODE_SLAVE) {
264             //we only use ringbuffer for slave mode.
265             if (slv_rx_buf_len > 0) {
266                 p_i2c->rx_ring_buf = xRingbufferCreate(slv_rx_buf_len, RINGBUF_TYPE_BYTEBUF);
267                 if (p_i2c->rx_ring_buf == NULL) {
268                     ESP_LOGE(I2C_TAG, I2C_BUF_ERR_STR);
269                     goto err;
270                 }
271                 p_i2c->rx_buf_length = slv_rx_buf_len;
272             } else {
273                 p_i2c->rx_ring_buf = NULL;
274                 p_i2c->rx_buf_length = 0;
275             }
276             if (slv_tx_buf_len > 0) {
277                 p_i2c->tx_ring_buf = xRingbufferCreate(slv_tx_buf_len, RINGBUF_TYPE_BYTEBUF);
278                 if (p_i2c->tx_ring_buf == NULL) {
279                     ESP_LOGE(I2C_TAG, I2C_BUF_ERR_STR);
280                     goto err;
281                 }
282                 p_i2c->tx_buf_length = slv_tx_buf_len;
283             } else {
284                 p_i2c->tx_ring_buf = NULL;
285                 p_i2c->tx_buf_length = 0;
286             }
287             p_i2c->slv_rx_mux = xSemaphoreCreateMutex();
288             p_i2c->slv_tx_mux = xSemaphoreCreateMutex();
289             if (p_i2c->slv_rx_mux == NULL || p_i2c->slv_tx_mux == NULL) {
290                 ESP_LOGE(I2C_TAG, I2C_SEM_ERR_STR);
291                 goto err;
292             }
293         } else {
294             //semaphore to sync sending process, because we only have 32 bytes for hardware fifo.
295             p_i2c->cmd_mux = xSemaphoreCreateMutex();
296 #ifdef CONFIG_PM_ENABLE
297             if (esp_pm_lock_create(ESP_PM_APB_FREQ_MAX, 0, "i2c_driver", &p_i2c->pm_lock) != ESP_OK) {
298                 ESP_LOGE(I2C_TAG, I2C_LOCK_ERR_STR);
299                 goto err;
300             }
301 #endif
302 #if !CONFIG_SPIRAM_USE_MALLOC
303             p_i2c->cmd_evt_queue = xQueueCreate(I2C_EVT_QUEUE_LEN, sizeof(i2c_cmd_evt_t));
304 #else
305             if ( !(intr_alloc_flags & ESP_INTR_FLAG_IRAM) ) {
306                 p_i2c->cmd_evt_queue = xQueueCreate(I2C_EVT_QUEUE_LEN, sizeof(i2c_cmd_evt_t));
307             } else {
308                 p_i2c->evt_queue_storage = (uint8_t *)heap_caps_calloc(I2C_EVT_QUEUE_LEN, sizeof(i2c_cmd_evt_t), MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT);
309                 if ( p_i2c->evt_queue_storage == NULL ) {
310                     ESP_LOGE(I2C_TAG, I2C_DRIVER_MALLOC_ERR_STR);
311                     goto err;
312                 }
313                 memset(&p_i2c->evt_queue_buffer, 0, sizeof(StaticQueue_t));
314                 p_i2c->cmd_evt_queue =  xQueueCreateStatic(I2C_EVT_QUEUE_LEN, sizeof(i2c_cmd_evt_t), p_i2c->evt_queue_storage, &p_i2c->evt_queue_buffer);
315             }
316 #endif
317             if (p_i2c->cmd_mux == NULL || p_i2c->cmd_evt_queue == NULL) {
318                 ESP_LOGE(I2C_TAG, I2C_SEM_ERR_STR);
319                 goto err;
320             }
321             //command link
322             p_i2c->cmd_link.cur = NULL;
323             p_i2c->cmd_link.head = NULL;
324             p_i2c->cmd_link.free = NULL;
325 
326             p_i2c->tx_ring_buf = NULL;
327             p_i2c->rx_buf_length = 0;
328             p_i2c->tx_ring_buf = NULL;
329             p_i2c->tx_buf_length = 0;
330         }
331     } else {
332         ESP_LOGE(I2C_TAG, I2C_DRIVER_ERR_STR);
333         return ESP_FAIL;
334     }
335     i2c_hw_enable(i2c_num);
336     //Disable I2C interrupt.
337     i2c_hal_disable_intr_mask(&(i2c_context[i2c_num].hal), I2C_LL_INTR_MASK);
338     i2c_hal_clr_intsts_mask(&(i2c_context[i2c_num].hal), I2C_LL_INTR_MASK);
339     //hook isr handler
340     i2c_isr_register(i2c_num, i2c_isr_handler_default, p_i2c_obj[i2c_num], intr_alloc_flags, &p_i2c_obj[i2c_num]->intr_handle);
341     //Enable I2C slave rx interrupt
342     if (mode == I2C_MODE_SLAVE) {
343         i2c_hal_enable_slave_rx_it(&(i2c_context[i2c_num].hal));
344     }
345     return ESP_OK;
346 
347 err:
348     //Some error has happened. Free/destroy all allocated things and return ESP_FAIL.
349     if (p_i2c_obj[i2c_num]) {
350         if (p_i2c_obj[i2c_num]->rx_ring_buf) {
351             vRingbufferDelete(p_i2c_obj[i2c_num]->rx_ring_buf);
352             p_i2c_obj[i2c_num]->rx_ring_buf = NULL;
353             p_i2c_obj[i2c_num]->rx_buf_length = 0;
354         }
355         if (p_i2c_obj[i2c_num]->tx_ring_buf) {
356             vRingbufferDelete(p_i2c_obj[i2c_num]->tx_ring_buf);
357             p_i2c_obj[i2c_num]->tx_ring_buf = NULL;
358             p_i2c_obj[i2c_num]->tx_buf_length = 0;
359         }
360         if (p_i2c_obj[i2c_num]->cmd_evt_queue) {
361             vQueueDelete(p_i2c_obj[i2c_num]->cmd_evt_queue);
362             p_i2c_obj[i2c_num]->cmd_evt_queue = NULL;
363         }
364         if (p_i2c_obj[i2c_num]->cmd_mux) {
365             vSemaphoreDelete(p_i2c_obj[i2c_num]->cmd_mux);
366         }
367         if (p_i2c_obj[i2c_num]->slv_rx_mux) {
368             vSemaphoreDelete(p_i2c_obj[i2c_num]->slv_rx_mux);
369         }
370         if (p_i2c_obj[i2c_num]->slv_tx_mux) {
371             vSemaphoreDelete(p_i2c_obj[i2c_num]->slv_tx_mux);
372         }
373 #ifdef CONFIG_PM_ENABLE
374         if (p_i2c_obj[i2c_num]->pm_lock) {
375             esp_pm_lock_delete(p_i2c_obj[i2c_num]->pm_lock);
376             p_i2c_obj[i2c_num]->pm_lock = NULL;
377         }
378 #endif
379 #if CONFIG_SPIRAM_USE_MALLOC
380         if (p_i2c_obj[i2c_num]->evt_queue_storage) {
381             free(p_i2c_obj[i2c_num]->evt_queue_storage);
382             p_i2c_obj[i2c_num]->evt_queue_storage = NULL;
383         }
384 #endif
385     }
386     free(p_i2c_obj[i2c_num]);
387     p_i2c_obj[i2c_num] = NULL;
388     return ESP_FAIL;
389 }
390 
i2c_driver_delete(i2c_port_t i2c_num)391 esp_err_t i2c_driver_delete(i2c_port_t i2c_num)
392 {
393     I2C_CHECK(i2c_num < I2C_NUM_MAX, I2C_NUM_ERROR_STR, ESP_ERR_INVALID_ARG);
394     I2C_CHECK(p_i2c_obj[i2c_num] != NULL, I2C_DRIVER_ERR_STR, ESP_FAIL);
395 
396     i2c_obj_t *p_i2c = p_i2c_obj[i2c_num];
397     i2c_hal_disable_intr_mask(&(i2c_context[i2c_num].hal), I2C_LL_INTR_MASK);
398     esp_intr_free(p_i2c->intr_handle);
399     p_i2c->intr_handle = NULL;
400 
401     if (p_i2c->cmd_mux) {
402         // Let any command in progress finish.
403         xSemaphoreTake(p_i2c->cmd_mux, portMAX_DELAY);
404         xSemaphoreGive(p_i2c->cmd_mux);
405         vSemaphoreDelete(p_i2c->cmd_mux);
406     }
407     if (p_i2c_obj[i2c_num]->cmd_evt_queue) {
408         vQueueDelete(p_i2c_obj[i2c_num]->cmd_evt_queue);
409         p_i2c_obj[i2c_num]->cmd_evt_queue = NULL;
410     }
411     if (p_i2c->slv_rx_mux) {
412         vSemaphoreDelete(p_i2c->slv_rx_mux);
413     }
414     if (p_i2c->slv_tx_mux) {
415         vSemaphoreDelete(p_i2c->slv_tx_mux);
416     }
417 
418     if (p_i2c->rx_ring_buf) {
419         vRingbufferDelete(p_i2c->rx_ring_buf);
420         p_i2c->rx_ring_buf = NULL;
421         p_i2c->rx_buf_length = 0;
422     }
423     if (p_i2c->tx_ring_buf) {
424         vRingbufferDelete(p_i2c->tx_ring_buf);
425         p_i2c->tx_ring_buf = NULL;
426         p_i2c->tx_buf_length = 0;
427     }
428 #ifdef CONFIG_PM_ENABLE
429     if (p_i2c->pm_lock) {
430         esp_pm_lock_delete(p_i2c->pm_lock);
431         p_i2c->pm_lock = NULL;
432     }
433 #endif
434 #if CONFIG_SPIRAM_USE_MALLOC
435     if (p_i2c_obj[i2c_num]->evt_queue_storage) {
436         free(p_i2c_obj[i2c_num]->evt_queue_storage);
437         p_i2c_obj[i2c_num]->evt_queue_storage = NULL;
438     }
439 #endif
440 
441     free(p_i2c_obj[i2c_num]);
442     p_i2c_obj[i2c_num] = NULL;
443 
444     i2c_hw_disable(i2c_num);
445     return ESP_OK;
446 }
447 
i2c_reset_tx_fifo(i2c_port_t i2c_num)448 esp_err_t i2c_reset_tx_fifo(i2c_port_t i2c_num)
449 {
450     I2C_CHECK(i2c_num < I2C_NUM_MAX, I2C_NUM_ERROR_STR, ESP_ERR_INVALID_ARG);
451     I2C_ENTER_CRITICAL(&(i2c_context[i2c_num].spinlock));
452     i2c_hal_txfifo_rst(&(i2c_context[i2c_num].hal));
453     I2C_EXIT_CRITICAL(&(i2c_context[i2c_num].spinlock));
454     return ESP_OK;
455 }
456 
i2c_reset_rx_fifo(i2c_port_t i2c_num)457 esp_err_t i2c_reset_rx_fifo(i2c_port_t i2c_num)
458 {
459     I2C_CHECK(i2c_num < I2C_NUM_MAX, I2C_NUM_ERROR_STR, ESP_ERR_INVALID_ARG);
460     I2C_ENTER_CRITICAL(&(i2c_context[i2c_num].spinlock));
461     i2c_hal_rxfifo_rst(&(i2c_context[i2c_num].hal));
462     I2C_EXIT_CRITICAL(&(i2c_context[i2c_num].spinlock));
463     return ESP_OK;
464 }
465 
i2c_isr_handler_default(void * arg)466 static void IRAM_ATTR i2c_isr_handler_default(void *arg)
467 {
468     i2c_obj_t *p_i2c = (i2c_obj_t *) arg;
469     int i2c_num = p_i2c->i2c_num;
470     i2c_intr_event_t evt_type = I2C_INTR_EVENT_ERR;
471     portBASE_TYPE HPTaskAwoken = pdFALSE;
472     if (p_i2c->mode == I2C_MODE_MASTER) {
473         if (p_i2c->status == I2C_STATUS_WRITE) {
474             i2c_hal_master_handle_tx_event(&(i2c_context[i2c_num].hal), &evt_type);
475         } else if (p_i2c->status == I2C_STATUS_READ) {
476             i2c_hal_master_handle_rx_event(&(i2c_context[i2c_num].hal), &evt_type);
477         }
478         if (evt_type == I2C_INTR_EVENT_NACK) {
479             p_i2c_obj[i2c_num]->status = I2C_STATUS_ACK_ERROR;
480             i2c_master_cmd_begin_static(i2c_num);
481         } else if (evt_type == I2C_INTR_EVENT_TOUT) {
482             p_i2c_obj[i2c_num]->status = I2C_STATUS_TIMEOUT;
483             i2c_master_cmd_begin_static(i2c_num);
484         } else if (evt_type == I2C_INTR_EVENT_ARBIT_LOST) {
485             p_i2c_obj[i2c_num]->status = I2C_STATUS_TIMEOUT;
486             i2c_master_cmd_begin_static(i2c_num);
487         } else if (evt_type == I2C_INTR_EVENT_END_DET) {
488             i2c_master_cmd_begin_static(i2c_num);
489         } else if (evt_type == I2C_INTR_EVENT_TRANS_DONE) {
490             if (p_i2c->status != I2C_STATUS_ACK_ERROR && p_i2c->status != I2C_STATUS_IDLE) {
491                 i2c_master_cmd_begin_static(i2c_num);
492             }
493         }
494         i2c_cmd_evt_t evt = {
495             .type = I2C_CMD_EVT_ALIVE
496         };
497         xQueueSendFromISR(p_i2c->cmd_evt_queue, &evt, &HPTaskAwoken);
498     } else {
499         i2c_hal_slave_handle_event(&(i2c_context[i2c_num].hal), &evt_type);
500         if (evt_type == I2C_INTR_EVENT_TRANS_DONE || evt_type == I2C_INTR_EVENT_RXFIFO_FULL) {
501             uint32_t rx_fifo_cnt;
502             i2c_hal_get_rxfifo_cnt(&(i2c_context[i2c_num].hal), &rx_fifo_cnt);
503             i2c_hal_read_rxfifo(&(i2c_context[i2c_num].hal), p_i2c->data_buf, rx_fifo_cnt);
504             xRingbufferSendFromISR(p_i2c->rx_ring_buf, p_i2c->data_buf, rx_fifo_cnt, &HPTaskAwoken);
505             i2c_hal_slave_clr_rx_it(&(i2c_context[i2c_num].hal));
506         } else if (evt_type == I2C_INTR_EVENT_TXFIFO_EMPTY) {
507             uint32_t tx_fifo_rem;
508             i2c_hal_get_txfifo_cnt(&(i2c_context[i2c_num].hal), &tx_fifo_rem);
509             size_t size = 0;
510             uint8_t *data = (uint8_t *) xRingbufferReceiveUpToFromISR(p_i2c->tx_ring_buf, &size, tx_fifo_rem);
511             if (data) {
512                 i2c_hal_write_txfifo(&(i2c_context[i2c_num].hal), data, size);
513                 vRingbufferReturnItemFromISR(p_i2c->tx_ring_buf, data, &HPTaskAwoken);
514             } else {
515                 i2c_hal_disable_slave_tx_it(&(i2c_context[i2c_num].hal));
516             }
517             i2c_hal_slave_clr_tx_it(&(i2c_context[i2c_num].hal));
518         }
519     }
520     //We only need to check here if there is a high-priority task needs to be switched.
521     if (HPTaskAwoken == pdTRUE) {
522         portYIELD_FROM_ISR();
523     }
524 }
525 
i2c_set_data_mode(i2c_port_t i2c_num,i2c_trans_mode_t tx_trans_mode,i2c_trans_mode_t rx_trans_mode)526 esp_err_t i2c_set_data_mode(i2c_port_t i2c_num, i2c_trans_mode_t tx_trans_mode, i2c_trans_mode_t rx_trans_mode)
527 {
528     I2C_CHECK(i2c_num < I2C_NUM_MAX, I2C_NUM_ERROR_STR, ESP_ERR_INVALID_ARG);
529     I2C_CHECK(tx_trans_mode < I2C_DATA_MODE_MAX, I2C_TRANS_MODE_ERR_STR, ESP_ERR_INVALID_ARG);
530     I2C_CHECK(rx_trans_mode < I2C_DATA_MODE_MAX, I2C_TRANS_MODE_ERR_STR, ESP_ERR_INVALID_ARG);
531     I2C_ENTER_CRITICAL(&(i2c_context[i2c_num].spinlock));
532     i2c_hal_set_data_mode(&(i2c_context[i2c_num].hal), tx_trans_mode, rx_trans_mode);
533     I2C_EXIT_CRITICAL(&(i2c_context[i2c_num].spinlock));
534     return ESP_OK;
535 }
536 
i2c_get_data_mode(i2c_port_t i2c_num,i2c_trans_mode_t * tx_trans_mode,i2c_trans_mode_t * rx_trans_mode)537 esp_err_t i2c_get_data_mode(i2c_port_t i2c_num, i2c_trans_mode_t *tx_trans_mode, i2c_trans_mode_t *rx_trans_mode)
538 {
539     I2C_CHECK(i2c_num < I2C_NUM_MAX, I2C_NUM_ERROR_STR, ESP_ERR_INVALID_ARG);
540     i2c_hal_get_data_mode(&(i2c_context[i2c_num].hal), tx_trans_mode, rx_trans_mode);
541     return ESP_OK;
542 }
543 
544 /* Some slave device will die by accident and keep the SDA in low level,
545  * in this case, master should send several clock to make the slave release the bus.
546  * Slave mode of ESP32 might also get in wrong state that held the SDA low,
547  * in this case, master device could send a stop signal to make esp32 slave release the bus.
548  **/
i2c_master_clear_bus(i2c_port_t i2c_num)549 static esp_err_t i2c_master_clear_bus(i2c_port_t i2c_num)
550 {
551 #if !SOC_I2C_SUPPORT_HW_CLR_BUS
552     const int scl_half_period = I2C_CLR_BUS_HALF_PERIOD_US; // use standard 100kHz data rate
553     int i = 0;
554     int scl_io = i2c_context[i2c_num].scl_io_num;
555     int sda_io = i2c_context[i2c_num].sda_io_num;
556     gpio_set_direction(scl_io, GPIO_MODE_OUTPUT_OD);
557     gpio_set_direction(sda_io, GPIO_MODE_INPUT_OUTPUT_OD);
558     // If a SLAVE device was in a read operation when the bus was interrupted, the SLAVE device is controlling SDA.
559     // The only bit during the 9 clock cycles of a READ byte the MASTER(ESP32) is guaranteed control over is during the ACK bit
560     // period. If the slave is sending a stream of ZERO bytes, it will only release SDA during the ACK bit period.
561     // So, this reset code needs to synchronize the bit stream with, Either, the ACK bit, Or a 1 bit to correctly generate
562     // a STOP condition.
563     gpio_set_level(scl_io, 0);
564     gpio_set_level(sda_io, 1);
565     esp_rom_delay_us(scl_half_period);
566     while (!gpio_get_level(sda_io) && (i++ < I2C_CLR_BUS_SCL_NUM)) {
567         gpio_set_level(scl_io, 1);
568         esp_rom_delay_us(scl_half_period);
569         gpio_set_level(scl_io, 0);
570         esp_rom_delay_us(scl_half_period);
571     }
572     gpio_set_level(sda_io, 0); // setup for STOP
573     gpio_set_level(scl_io, 1);
574     esp_rom_delay_us(scl_half_period);
575     gpio_set_level(sda_io, 1); // STOP, SDA low -> high while SCL is HIGH
576     i2c_set_pin(i2c_num, sda_io, scl_io, 1, 1, I2C_MODE_MASTER);
577 #else
578     i2c_hal_master_clr_bus(&(i2c_context[i2c_num].hal));
579 #endif
580     return ESP_OK;
581 }
582 
583 /**if the power and SDA/SCL wires are in proper condition, everything works find with reading the slave.
584  * If we remove the power supply for the slave during I2C is reading, or directly connect SDA or SCL to ground,
585  * this would cause the I2C FSM get stuck in wrong state, all we can do is to reset the I2C hardware in this case.
586  **/
i2c_hw_fsm_reset(i2c_port_t i2c_num)587 static esp_err_t i2c_hw_fsm_reset(i2c_port_t i2c_num)
588 {
589 #if !SOC_I2C_SUPPORT_HW_FSM_RST
590     int scl_low_period, scl_high_period;
591     int scl_start_hold, scl_rstart_setup;
592     int scl_stop_hold, scl_stop_setup;
593     int sda_hold, sda_sample;
594     int timeout;
595     uint8_t filter_cfg;
596 
597     i2c_hal_get_scl_timing(&(i2c_context[i2c_num].hal), &scl_high_period, &scl_low_period);
598     i2c_hal_get_start_timing(&(i2c_context[i2c_num].hal), &scl_rstart_setup, &scl_start_hold);
599     i2c_hal_get_stop_timing(&(i2c_context[i2c_num].hal), &scl_stop_setup, &scl_stop_hold);
600     i2c_hal_get_sda_timing(&(i2c_context[i2c_num].hal), &sda_sample, &sda_hold);
601     i2c_hal_get_tout(&(i2c_context[i2c_num].hal), &timeout);
602     i2c_hal_get_filter(&(i2c_context[i2c_num].hal), &filter_cfg);
603 
604     //to reset the I2C hw module, we need re-enable the hw
605     i2c_hw_disable(i2c_num);
606     i2c_master_clear_bus(i2c_num);
607     i2c_hw_enable(i2c_num);
608 
609     i2c_hal_master_init(&(i2c_context[i2c_num].hal), i2c_num);
610     i2c_hal_disable_intr_mask(&(i2c_context[i2c_num].hal), I2C_LL_INTR_MASK);
611     i2c_hal_clr_intsts_mask(&(i2c_context[i2c_num].hal), I2C_LL_INTR_MASK);
612     i2c_hal_set_scl_timing(&(i2c_context[i2c_num].hal), scl_high_period, scl_low_period);
613     i2c_hal_set_start_timing(&(i2c_context[i2c_num].hal), scl_rstart_setup, scl_start_hold);
614     i2c_hal_set_stop_timing(&(i2c_context[i2c_num].hal), scl_stop_setup, scl_stop_hold);
615     i2c_hal_set_sda_timing(&(i2c_context[i2c_num].hal), sda_sample, sda_hold);
616     i2c_hal_set_tout(&(i2c_context[i2c_num].hal), timeout);
617     i2c_hal_set_filter(&(i2c_context[i2c_num].hal), filter_cfg);
618 #else
619     i2c_hal_master_fsm_rst(&(i2c_context[i2c_num].hal));
620     i2c_master_clear_bus(i2c_num);
621 #endif
622     return ESP_OK;
623 }
624 
i2c_get_clk_src(const i2c_config_t * i2c_conf)625 static i2c_sclk_t i2c_get_clk_src(const i2c_config_t *i2c_conf)
626 {
627     for (i2c_sclk_t clk = I2C_SCLK_DEFAULT + 1; clk < I2C_SCLK_MAX; clk++) {
628 #if CONFIG_IDF_TARGET_ESP32S3
629         if (clk == I2C_SCLK_RTC) { // RTC clock for s3 is unaccessable now.
630             continue;
631         }
632 #endif
633         if (((i2c_conf->clk_flags & i2c_clk_alloc[clk].character) == i2c_conf->clk_flags) && (i2c_conf->master.clk_speed <= i2c_clk_alloc[clk].clk_freq)) {
634             return clk;
635         }
636     }
637     return I2C_SCLK_MAX;     // flag invalid;
638 }
639 
i2c_param_config(i2c_port_t i2c_num,const i2c_config_t * i2c_conf)640 esp_err_t i2c_param_config(i2c_port_t i2c_num, const i2c_config_t *i2c_conf)
641 {
642     I2C_CHECK(i2c_num < I2C_NUM_MAX, I2C_NUM_ERROR_STR, ESP_ERR_INVALID_ARG);
643     I2C_CHECK(i2c_conf != NULL, I2C_ADDR_ERROR_STR, ESP_ERR_INVALID_ARG);
644     I2C_CHECK(i2c_conf->mode < I2C_MODE_MAX, I2C_MODE_ERR_STR, ESP_ERR_INVALID_ARG);
645     if (i2c_conf->mode == I2C_MODE_MASTER) {
646         I2C_CHECK(i2c_get_clk_src(i2c_conf) != I2C_SCLK_MAX, I2C_CLK_FLAG_ERR_STR, ESP_ERR_INVALID_ARG);
647     }
648 
649     esp_err_t ret = i2c_set_pin(i2c_num, i2c_conf->sda_io_num, i2c_conf->scl_io_num,
650                                 i2c_conf->sda_pullup_en, i2c_conf->scl_pullup_en, i2c_conf->mode);
651     if (ret != ESP_OK) {
652         return ret;
653     }
654     i2c_hw_enable(i2c_num);
655     I2C_ENTER_CRITICAL(&(i2c_context[i2c_num].spinlock));
656     i2c_hal_disable_intr_mask(&(i2c_context[i2c_num].hal), I2C_LL_INTR_MASK);
657     i2c_hal_clr_intsts_mask(&(i2c_context[i2c_num].hal), I2C_LL_INTR_MASK);
658     if (i2c_conf->mode == I2C_MODE_SLAVE) {  //slave mode
659         i2c_hal_slave_init(&(i2c_context[i2c_num].hal), i2c_num);
660         i2c_hal_set_slave_addr(&(i2c_context[i2c_num].hal), i2c_conf->slave.slave_addr, i2c_conf->slave.addr_10bit_en);
661         i2c_hal_set_rxfifo_full_thr(&(i2c_context[i2c_num].hal), I2C_FIFO_FULL_THRESH_VAL);
662         i2c_hal_set_txfifo_empty_thr(&(i2c_context[i2c_num].hal), I2C_FIFO_EMPTY_THRESH_VAL);
663         //set timing for data
664         i2c_hal_set_sda_timing(&(i2c_context[i2c_num].hal), I2C_SLAVE_SDA_SAMPLE_DEFAULT, I2C_SLAVE_SDA_HOLD_DEFAULT);
665         i2c_hal_set_tout(&(i2c_context[i2c_num].hal), I2C_SLAVE_TIMEOUT_DEFAULT);
666         i2c_hal_enable_slave_rx_it(&(i2c_context[i2c_num].hal));
667         i2c_hal_update_config(&(i2c_context[i2c_num].hal));
668     } else {
669         i2c_hal_master_init(&(i2c_context[i2c_num].hal), i2c_num);
670         //Default, we enable hardware filter
671         i2c_hal_set_filter(&(i2c_context[i2c_num].hal), I2C_FILTER_CYC_NUM_DEF);
672         i2c_hal_set_bus_timing(&(i2c_context[i2c_num].hal), i2c_conf->master.clk_speed, i2c_get_clk_src(i2c_conf));
673     }
674     I2C_EXIT_CRITICAL(&(i2c_context[i2c_num].spinlock));
675     return ESP_OK;
676 }
677 
i2c_set_period(i2c_port_t i2c_num,int high_period,int low_period)678 esp_err_t i2c_set_period(i2c_port_t i2c_num, int high_period, int low_period)
679 {
680     I2C_CHECK(i2c_num < I2C_NUM_MAX, I2C_NUM_ERROR_STR, ESP_ERR_INVALID_ARG);
681     I2C_CHECK((high_period <= I2C_SCL_HIGH_PERIOD_V) && (high_period > 0), I2C_TIMEING_VAL_ERR_STR, ESP_ERR_INVALID_ARG);
682     I2C_CHECK((low_period <= I2C_SCL_LOW_PERIOD_V) && (low_period > 0), I2C_TIMEING_VAL_ERR_STR, ESP_ERR_INVALID_ARG);
683 
684     I2C_ENTER_CRITICAL(&(i2c_context[i2c_num].spinlock));
685     i2c_hal_set_scl_timing(&(i2c_context[i2c_num].hal), high_period, low_period);
686     I2C_EXIT_CRITICAL(&(i2c_context[i2c_num].spinlock));
687     return ESP_OK;
688 }
689 
i2c_get_period(i2c_port_t i2c_num,int * high_period,int * low_period)690 esp_err_t i2c_get_period(i2c_port_t i2c_num, int *high_period, int *low_period)
691 {
692     I2C_CHECK(i2c_num < I2C_NUM_MAX && high_period != NULL && low_period != NULL, I2C_NUM_ERROR_STR, ESP_ERR_INVALID_ARG);
693     I2C_ENTER_CRITICAL(&(i2c_context[i2c_num].spinlock));
694     i2c_hal_get_scl_timing(&(i2c_context[i2c_num].hal), high_period, low_period);
695     I2C_EXIT_CRITICAL(&(i2c_context[i2c_num].spinlock));
696     return ESP_OK;
697 }
698 
i2c_filter_enable(i2c_port_t i2c_num,uint8_t cyc_num)699 esp_err_t i2c_filter_enable(i2c_port_t i2c_num, uint8_t cyc_num)
700 {
701     I2C_CHECK(i2c_num < I2C_NUM_MAX, I2C_NUM_ERROR_STR, ESP_ERR_INVALID_ARG);
702     I2C_CHECK(p_i2c_obj[i2c_num] != NULL, I2C_DRIVER_ERR_STR, ESP_FAIL);
703     I2C_ENTER_CRITICAL(&(i2c_context[i2c_num].spinlock));
704     i2c_hal_set_filter(&(i2c_context[i2c_num].hal), cyc_num);
705     I2C_EXIT_CRITICAL(&(i2c_context[i2c_num].spinlock));
706     return ESP_OK;
707 }
708 
i2c_filter_disable(i2c_port_t i2c_num)709 esp_err_t i2c_filter_disable(i2c_port_t i2c_num)
710 {
711     I2C_CHECK(i2c_num < I2C_NUM_MAX, I2C_NUM_ERROR_STR, ESP_ERR_INVALID_ARG);
712     I2C_ENTER_CRITICAL(&(i2c_context[i2c_num].spinlock));
713     i2c_hal_set_filter(&(i2c_context[i2c_num].hal), 0);
714     I2C_EXIT_CRITICAL(&(i2c_context[i2c_num].spinlock));
715     return ESP_OK;
716 }
717 
i2c_set_start_timing(i2c_port_t i2c_num,int setup_time,int hold_time)718 esp_err_t i2c_set_start_timing(i2c_port_t i2c_num, int setup_time, int hold_time)
719 {
720     I2C_CHECK(i2c_num < I2C_NUM_MAX, I2C_NUM_ERROR_STR, ESP_ERR_INVALID_ARG);
721     I2C_CHECK((hold_time <= I2C_SCL_START_HOLD_TIME_V) && (hold_time > 0), I2C_TIMEING_VAL_ERR_STR, ESP_ERR_INVALID_ARG);
722     I2C_CHECK((setup_time <= I2C_SCL_RSTART_SETUP_TIME_V) && (setup_time > 0), I2C_TIMEING_VAL_ERR_STR, ESP_ERR_INVALID_ARG);
723 
724     I2C_ENTER_CRITICAL(&(i2c_context[i2c_num].spinlock));
725     i2c_hal_set_start_timing(&(i2c_context[i2c_num].hal), setup_time, hold_time);
726     I2C_EXIT_CRITICAL(&(i2c_context[i2c_num].spinlock));
727     return ESP_OK;
728 }
729 
i2c_get_start_timing(i2c_port_t i2c_num,int * setup_time,int * hold_time)730 esp_err_t i2c_get_start_timing(i2c_port_t i2c_num, int *setup_time, int *hold_time)
731 {
732     I2C_CHECK(i2c_num < I2C_NUM_MAX && setup_time != NULL && hold_time != NULL, I2C_NUM_ERROR_STR, ESP_ERR_INVALID_ARG);
733     I2C_ENTER_CRITICAL(&(i2c_context[i2c_num].spinlock));
734     i2c_hal_get_start_timing(&(i2c_context[i2c_num].hal), setup_time, hold_time);
735     I2C_EXIT_CRITICAL(&(i2c_context[i2c_num].spinlock));
736     return ESP_OK;
737 }
738 
i2c_set_stop_timing(i2c_port_t i2c_num,int setup_time,int hold_time)739 esp_err_t i2c_set_stop_timing(i2c_port_t i2c_num, int setup_time, int hold_time)
740 {
741     I2C_CHECK(i2c_num < I2C_NUM_MAX, I2C_NUM_ERROR_STR, ESP_ERR_INVALID_ARG);
742     I2C_CHECK((setup_time <= I2C_SCL_STOP_SETUP_TIME_V) && (setup_time > 0), I2C_TIMEING_VAL_ERR_STR, ESP_ERR_INVALID_ARG);
743     I2C_CHECK((hold_time <= I2C_SCL_STOP_HOLD_TIME_V) && (hold_time > 0), I2C_TIMEING_VAL_ERR_STR, ESP_ERR_INVALID_ARG);
744 
745     I2C_ENTER_CRITICAL(&(i2c_context[i2c_num].spinlock));
746     i2c_hal_set_stop_timing(&(i2c_context[i2c_num].hal), setup_time, hold_time);
747     I2C_EXIT_CRITICAL(&(i2c_context[i2c_num].spinlock));
748     return ESP_OK;
749 }
750 
i2c_get_stop_timing(i2c_port_t i2c_num,int * setup_time,int * hold_time)751 esp_err_t i2c_get_stop_timing(i2c_port_t i2c_num, int *setup_time, int *hold_time)
752 {
753     I2C_CHECK(i2c_num < I2C_NUM_MAX && setup_time != NULL && hold_time != NULL, I2C_NUM_ERROR_STR, ESP_ERR_INVALID_ARG);
754     I2C_ENTER_CRITICAL(&(i2c_context[i2c_num].spinlock));
755     i2c_hal_get_stop_timing(&(i2c_context[i2c_num].hal), setup_time, hold_time);
756     I2C_EXIT_CRITICAL(&(i2c_context[i2c_num].spinlock));
757     return ESP_OK;
758 }
759 
i2c_set_data_timing(i2c_port_t i2c_num,int sample_time,int hold_time)760 esp_err_t i2c_set_data_timing(i2c_port_t i2c_num, int sample_time, int hold_time)
761 {
762     I2C_CHECK(i2c_num < I2C_NUM_MAX, I2C_NUM_ERROR_STR, ESP_ERR_INVALID_ARG);
763     I2C_CHECK((sample_time <= I2C_SDA_SAMPLE_TIME_V) && (sample_time > 0), I2C_TIMEING_VAL_ERR_STR, ESP_ERR_INVALID_ARG);
764     I2C_CHECK((hold_time <= I2C_SDA_HOLD_TIME_V) && (hold_time > 0), I2C_TIMEING_VAL_ERR_STR, ESP_ERR_INVALID_ARG);
765 
766     I2C_ENTER_CRITICAL(&(i2c_context[i2c_num].spinlock));
767     i2c_hal_set_sda_timing(&(i2c_context[i2c_num].hal), sample_time, hold_time);
768     I2C_EXIT_CRITICAL(&(i2c_context[i2c_num].spinlock));
769     return ESP_OK;
770 }
771 
i2c_get_data_timing(i2c_port_t i2c_num,int * sample_time,int * hold_time)772 esp_err_t i2c_get_data_timing(i2c_port_t i2c_num, int *sample_time, int *hold_time)
773 {
774     I2C_CHECK(i2c_num < I2C_NUM_MAX && sample_time != NULL && hold_time != NULL, I2C_NUM_ERROR_STR, ESP_ERR_INVALID_ARG);
775     I2C_ENTER_CRITICAL(&(i2c_context[i2c_num].spinlock));
776     i2c_hal_get_sda_timing(&(i2c_context[i2c_num].hal), sample_time, hold_time);
777     I2C_EXIT_CRITICAL(&(i2c_context[i2c_num].spinlock));
778     return ESP_OK;
779 }
780 
i2c_set_timeout(i2c_port_t i2c_num,int timeout)781 esp_err_t i2c_set_timeout(i2c_port_t i2c_num, int timeout)
782 {
783     I2C_CHECK(i2c_num < I2C_NUM_MAX, I2C_NUM_ERROR_STR, ESP_ERR_INVALID_ARG);
784     I2C_CHECK((timeout <= I2C_TIME_OUT_REG_V) && (timeout > 0), I2C_TIMEING_VAL_ERR_STR, ESP_ERR_INVALID_ARG);
785 
786     I2C_ENTER_CRITICAL(&(i2c_context[i2c_num].spinlock));
787     i2c_hal_set_tout(&(i2c_context[i2c_num].hal), timeout);
788     I2C_EXIT_CRITICAL(&(i2c_context[i2c_num].spinlock));
789     return ESP_OK;
790 }
791 
i2c_get_timeout(i2c_port_t i2c_num,int * timeout)792 esp_err_t i2c_get_timeout(i2c_port_t i2c_num, int *timeout)
793 {
794     I2C_CHECK(i2c_num < I2C_NUM_MAX && timeout != NULL, I2C_NUM_ERROR_STR, ESP_ERR_INVALID_ARG);
795     i2c_hal_get_tout(&(i2c_context[i2c_num].hal), timeout);
796     return ESP_OK;
797 }
798 
i2c_isr_register(i2c_port_t i2c_num,void (* fn)(void *),void * arg,int intr_alloc_flags,intr_handle_t * handle)799 esp_err_t i2c_isr_register(i2c_port_t i2c_num, void (*fn)(void *), void *arg, int intr_alloc_flags, intr_handle_t *handle)
800 {
801     I2C_CHECK(i2c_num < I2C_NUM_MAX, I2C_NUM_ERROR_STR, ESP_ERR_INVALID_ARG);
802     I2C_CHECK(fn != NULL, I2C_ADDR_ERROR_STR, ESP_ERR_INVALID_ARG);
803     esp_err_t ret = esp_intr_alloc(i2c_periph_signal[i2c_num].irq, intr_alloc_flags, fn, arg, handle);
804     return ret;
805 }
806 
i2c_isr_free(intr_handle_t handle)807 esp_err_t i2c_isr_free(intr_handle_t handle)
808 {
809     return esp_intr_free(handle);
810 }
811 
i2c_set_pin(i2c_port_t i2c_num,int sda_io_num,int scl_io_num,bool sda_pullup_en,bool scl_pullup_en,i2c_mode_t mode)812 esp_err_t i2c_set_pin(i2c_port_t i2c_num, int sda_io_num, int scl_io_num, bool sda_pullup_en, bool scl_pullup_en, i2c_mode_t mode)
813 {
814     I2C_CHECK(( i2c_num < I2C_NUM_MAX ), I2C_NUM_ERROR_STR, ESP_ERR_INVALID_ARG);
815     I2C_CHECK(((sda_io_num < 0) || ((GPIO_IS_VALID_OUTPUT_GPIO(sda_io_num)))), I2C_SDA_IO_ERR_STR, ESP_ERR_INVALID_ARG);
816     I2C_CHECK(scl_io_num < 0 ||
817               (GPIO_IS_VALID_OUTPUT_GPIO(scl_io_num)) ||
818               (GPIO_IS_VALID_GPIO(scl_io_num) && mode == I2C_MODE_SLAVE),
819               I2C_SCL_IO_ERR_STR,
820               ESP_ERR_INVALID_ARG);
821     I2C_CHECK(sda_io_num < 0 ||
822               (sda_pullup_en == GPIO_PULLUP_ENABLE && GPIO_IS_VALID_OUTPUT_GPIO(sda_io_num)) ||
823               sda_pullup_en == GPIO_PULLUP_DISABLE, I2C_GPIO_PULLUP_ERR_STR, ESP_ERR_INVALID_ARG);
824     I2C_CHECK(scl_io_num < 0 ||
825               (scl_pullup_en == GPIO_PULLUP_ENABLE && GPIO_IS_VALID_OUTPUT_GPIO(scl_io_num)) ||
826               scl_pullup_en == GPIO_PULLUP_DISABLE, I2C_GPIO_PULLUP_ERR_STR, ESP_ERR_INVALID_ARG);
827     I2C_CHECK((sda_io_num != scl_io_num), I2C_SCL_SDA_EQUAL_ERR_STR, ESP_ERR_INVALID_ARG);
828 
829     int sda_in_sig, sda_out_sig, scl_in_sig, scl_out_sig;
830     sda_out_sig = i2c_periph_signal[i2c_num].sda_out_sig;
831     sda_in_sig = i2c_periph_signal[i2c_num].sda_in_sig;
832     scl_out_sig = i2c_periph_signal[i2c_num].scl_out_sig;
833     scl_in_sig = i2c_periph_signal[i2c_num].scl_in_sig;
834     if (sda_io_num >= 0) {
835         gpio_set_level(sda_io_num, I2C_IO_INIT_LEVEL);
836         gpio_hal_iomux_func_sel(GPIO_PIN_MUX_REG[sda_io_num], PIN_FUNC_GPIO);
837         gpio_set_direction(sda_io_num, GPIO_MODE_INPUT_OUTPUT_OD);
838 
839         if (sda_pullup_en == GPIO_PULLUP_ENABLE) {
840             gpio_set_pull_mode(sda_io_num, GPIO_PULLUP_ONLY);
841         } else {
842             gpio_set_pull_mode(sda_io_num, GPIO_FLOATING);
843         }
844         esp_rom_gpio_connect_out_signal(sda_io_num, sda_out_sig, 0, 0);
845         esp_rom_gpio_connect_in_signal(sda_io_num, sda_in_sig, 0);
846     }
847     if (scl_io_num >= 0) {
848         gpio_set_level(scl_io_num, I2C_IO_INIT_LEVEL);
849         gpio_hal_iomux_func_sel(GPIO_PIN_MUX_REG[scl_io_num], PIN_FUNC_GPIO);
850         gpio_set_direction(scl_io_num, GPIO_MODE_INPUT_OUTPUT_OD);
851         esp_rom_gpio_connect_out_signal(scl_io_num, scl_out_sig, 0, 0);
852         esp_rom_gpio_connect_in_signal(scl_io_num, scl_in_sig, 0);
853         if (scl_pullup_en == GPIO_PULLUP_ENABLE) {
854             gpio_set_pull_mode(scl_io_num, GPIO_PULLUP_ONLY);
855         } else {
856             gpio_set_pull_mode(scl_io_num, GPIO_FLOATING);
857         }
858     }
859 #if !SOC_I2C_SUPPORT_HW_CLR_BUS
860     i2c_context[i2c_num].scl_io_num = scl_io_num;
861     i2c_context[i2c_num].sda_io_num = sda_io_num;
862 #endif
863     return ESP_OK;
864 }
865 
i2c_cmd_link_create(void)866 i2c_cmd_handle_t i2c_cmd_link_create(void)
867 {
868 #if !CONFIG_SPIRAM_USE_MALLOC
869     i2c_cmd_desc_t *cmd_desc = (i2c_cmd_desc_t *) calloc(1, sizeof(i2c_cmd_desc_t));
870 #else
871     i2c_cmd_desc_t *cmd_desc = (i2c_cmd_desc_t *) heap_caps_calloc(1, sizeof(i2c_cmd_desc_t), MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT);
872 #endif
873     return (i2c_cmd_handle_t) cmd_desc;
874 }
875 
i2c_cmd_link_delete(i2c_cmd_handle_t cmd_handle)876 void i2c_cmd_link_delete(i2c_cmd_handle_t cmd_handle)
877 {
878     if (cmd_handle == NULL) {
879         return;
880     }
881     i2c_cmd_desc_t *cmd = (i2c_cmd_desc_t *) cmd_handle;
882     while (cmd->free) {
883         i2c_cmd_link_t *ptmp = cmd->free;
884         cmd->free = cmd->free->next;
885         free(ptmp);
886     }
887     cmd->cur = NULL;
888     cmd->free = NULL;
889     cmd->head = NULL;
890     free(cmd_handle);
891     return;
892 }
893 
i2c_cmd_link_append(i2c_cmd_handle_t cmd_handle,i2c_cmd_t * cmd)894 static esp_err_t i2c_cmd_link_append(i2c_cmd_handle_t cmd_handle, i2c_cmd_t *cmd)
895 {
896     i2c_cmd_desc_t *cmd_desc = (i2c_cmd_desc_t *) cmd_handle;
897     if (cmd_desc->head == NULL) {
898 #if !CONFIG_SPIRAM_USE_MALLOC
899         cmd_desc->head = (i2c_cmd_link_t *) calloc(1, sizeof(i2c_cmd_link_t));
900 #else
901         cmd_desc->head = (i2c_cmd_link_t *) heap_caps_calloc(1, sizeof(i2c_cmd_link_t), MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT);
902 #endif
903         if (cmd_desc->head == NULL) {
904             ESP_LOGE(I2C_TAG, I2C_CMD_MALLOC_ERR_STR);
905             goto err;
906         }
907         cmd_desc->cur = cmd_desc->head;
908         cmd_desc->free = cmd_desc->head;
909     } else {
910 #if !CONFIG_SPIRAM_USE_MALLOC
911         cmd_desc->cur->next = (i2c_cmd_link_t *) calloc(1, sizeof(i2c_cmd_link_t));
912 #else
913         cmd_desc->cur->next = (i2c_cmd_link_t *) heap_caps_calloc(1, sizeof(i2c_cmd_link_t), MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT);
914 #endif
915         if (cmd_desc->cur->next == NULL) {
916             ESP_LOGE(I2C_TAG, I2C_CMD_MALLOC_ERR_STR);
917             goto err;
918         }
919         cmd_desc->cur = cmd_desc->cur->next;
920     }
921     memcpy((uint8_t *) &cmd_desc->cur->cmd, (uint8_t *) cmd, sizeof(i2c_cmd_t));
922     cmd_desc->cur->next = NULL;
923     return ESP_OK;
924 
925 err:
926     return ESP_FAIL;
927 }
928 
i2c_master_start(i2c_cmd_handle_t cmd_handle)929 esp_err_t i2c_master_start(i2c_cmd_handle_t cmd_handle)
930 {
931     I2C_CHECK(cmd_handle != NULL, I2C_CMD_LINK_INIT_ERR_STR, ESP_ERR_INVALID_ARG);
932     i2c_cmd_t cmd;
933     cmd.hw_cmd.ack_en = 0;
934     cmd.hw_cmd.ack_exp = 0;
935     cmd.hw_cmd.ack_val = 0;
936     cmd.hw_cmd.op_code = I2C_LL_CMD_RESTART;
937     cmd.hw_cmd.byte_num = 0;
938     cmd.data = NULL;
939     return i2c_cmd_link_append(cmd_handle, &cmd);
940 }
941 
i2c_master_stop(i2c_cmd_handle_t cmd_handle)942 esp_err_t i2c_master_stop(i2c_cmd_handle_t cmd_handle)
943 {
944     I2C_CHECK(cmd_handle != NULL, I2C_CMD_LINK_INIT_ERR_STR, ESP_ERR_INVALID_ARG);
945     i2c_cmd_t cmd;
946     cmd.hw_cmd.ack_en = 0;
947     cmd.hw_cmd.ack_exp = 0;
948     cmd.hw_cmd.ack_val = 0;
949     cmd.hw_cmd.op_code = I2C_LL_CMD_STOP;
950     cmd.hw_cmd.byte_num = 0;
951     cmd.data = NULL;
952     return i2c_cmd_link_append(cmd_handle, &cmd);
953 }
954 
i2c_master_write(i2c_cmd_handle_t cmd_handle,const uint8_t * data,size_t data_len,bool ack_en)955 esp_err_t i2c_master_write(i2c_cmd_handle_t cmd_handle, const uint8_t *data, size_t data_len, bool ack_en)
956 {
957     I2C_CHECK((data != NULL), I2C_ADDR_ERROR_STR, ESP_ERR_INVALID_ARG);
958     I2C_CHECK(cmd_handle != NULL, I2C_CMD_LINK_INIT_ERR_STR, ESP_ERR_INVALID_ARG);
959 
960     uint8_t len_tmp;
961     int data_offset = 0;
962     esp_err_t ret;
963     while (data_len > 0) {
964         len_tmp = data_len > 0xff ? 0xff : data_len;
965         data_len -= len_tmp;
966         i2c_cmd_t cmd;
967         cmd.hw_cmd.ack_en = ack_en;
968         cmd.hw_cmd.ack_exp = 0;
969         cmd.hw_cmd.ack_val = 0;
970         cmd.hw_cmd.op_code = I2C_LL_CMD_WRITE;
971         cmd.hw_cmd.byte_num = len_tmp;
972         cmd.data = (uint8_t*) data + data_offset;
973         ret = i2c_cmd_link_append(cmd_handle, &cmd);
974         data_offset += len_tmp;
975         if (ret != ESP_OK) {
976             return ret;
977         }
978     }
979     return ESP_OK;
980 }
981 
i2c_master_write_byte(i2c_cmd_handle_t cmd_handle,uint8_t data,bool ack_en)982 esp_err_t i2c_master_write_byte(i2c_cmd_handle_t cmd_handle, uint8_t data, bool ack_en)
983 {
984     I2C_CHECK(cmd_handle != NULL, I2C_CMD_LINK_INIT_ERR_STR, ESP_ERR_INVALID_ARG);
985     i2c_cmd_t cmd;
986     cmd.hw_cmd.ack_en = ack_en;
987     cmd.hw_cmd.ack_exp = 0;
988     cmd.hw_cmd.ack_val = 0;
989     cmd.hw_cmd.op_code = I2C_LL_CMD_WRITE;
990     cmd.hw_cmd.byte_num = 1;
991     cmd.data = NULL;
992     cmd.byte_cmd = data;
993     return i2c_cmd_link_append(cmd_handle, &cmd);
994 }
995 
i2c_master_read_static(i2c_cmd_handle_t cmd_handle,uint8_t * data,size_t data_len,i2c_ack_type_t ack)996 static esp_err_t i2c_master_read_static(i2c_cmd_handle_t cmd_handle, uint8_t *data, size_t data_len, i2c_ack_type_t ack)
997 {
998     int len_tmp;
999     int data_offset = 0;
1000     esp_err_t ret;
1001     while (data_len > 0) {
1002         len_tmp = data_len > 0xff ? 0xff : data_len;
1003         data_len -= len_tmp;
1004         i2c_cmd_t cmd;
1005         cmd.hw_cmd.ack_en = 0;
1006         cmd.hw_cmd.ack_exp = 0;
1007         cmd.hw_cmd.ack_val = ack & 0x1;
1008         cmd.hw_cmd.byte_num = len_tmp;
1009         cmd.hw_cmd.op_code = I2C_LL_CMD_READ;
1010         cmd.data = data + data_offset;
1011         ret = i2c_cmd_link_append(cmd_handle, &cmd);
1012         data_offset += len_tmp;
1013         if (ret != ESP_OK) {
1014             return ret;
1015         }
1016     }
1017     return ESP_OK;
1018 }
1019 
i2c_master_read_byte(i2c_cmd_handle_t cmd_handle,uint8_t * data,i2c_ack_type_t ack)1020 esp_err_t i2c_master_read_byte(i2c_cmd_handle_t cmd_handle, uint8_t *data, i2c_ack_type_t ack)
1021 {
1022     I2C_CHECK((data != NULL), I2C_ADDR_ERROR_STR, ESP_ERR_INVALID_ARG);
1023     I2C_CHECK(cmd_handle != NULL, I2C_CMD_LINK_INIT_ERR_STR, ESP_ERR_INVALID_ARG);
1024     I2C_CHECK(ack < I2C_MASTER_ACK_MAX, I2C_ACK_TYPE_ERR_STR, ESP_ERR_INVALID_ARG);
1025 
1026     i2c_cmd_t cmd;
1027     cmd.hw_cmd.ack_en = 0;
1028     cmd.hw_cmd.ack_exp = 0;
1029     cmd.hw_cmd.ack_val = ((ack == I2C_MASTER_LAST_NACK) ? I2C_MASTER_NACK : (ack & 0x1));
1030     cmd.hw_cmd.byte_num = 1;
1031     cmd.hw_cmd.op_code = I2C_LL_CMD_READ;
1032     cmd.data = data;
1033     return i2c_cmd_link_append(cmd_handle, &cmd);
1034 }
1035 
i2c_master_read(i2c_cmd_handle_t cmd_handle,uint8_t * data,size_t data_len,i2c_ack_type_t ack)1036 esp_err_t i2c_master_read(i2c_cmd_handle_t cmd_handle, uint8_t *data, size_t data_len, i2c_ack_type_t ack)
1037 {
1038     I2C_CHECK((data != NULL), I2C_ADDR_ERROR_STR, ESP_ERR_INVALID_ARG);
1039     I2C_CHECK(cmd_handle != NULL, I2C_CMD_LINK_INIT_ERR_STR, ESP_ERR_INVALID_ARG);
1040     I2C_CHECK(ack < I2C_MASTER_ACK_MAX, I2C_ACK_TYPE_ERR_STR, ESP_ERR_INVALID_ARG);
1041     I2C_CHECK(data_len > 0, I2C_DATA_LEN_ERR_STR, ESP_ERR_INVALID_ARG);
1042 
1043     if (ack != I2C_MASTER_LAST_NACK) {
1044         return i2c_master_read_static(cmd_handle, data, data_len, ack);
1045     } else {
1046         if (data_len == 1) {
1047             return i2c_master_read_byte(cmd_handle, data, I2C_MASTER_NACK);
1048         } else {
1049             esp_err_t ret;
1050             if ((ret =  i2c_master_read_static(cmd_handle, data, data_len - 1, I2C_MASTER_ACK)) != ESP_OK) {
1051                 return ret;
1052             }
1053             return i2c_master_read_byte(cmd_handle, data + data_len - 1, I2C_MASTER_NACK);
1054         }
1055     }
1056 }
1057 
i2c_master_cmd_begin_static(i2c_port_t i2c_num)1058 static void IRAM_ATTR i2c_master_cmd_begin_static(i2c_port_t i2c_num)
1059 {
1060     i2c_obj_t *p_i2c = p_i2c_obj[i2c_num];
1061     portBASE_TYPE HPTaskAwoken = pdFALSE;
1062     i2c_cmd_evt_t evt;
1063     if (p_i2c->cmd_link.head != NULL && p_i2c->status == I2C_STATUS_READ) {
1064         i2c_cmd_t *cmd = &p_i2c->cmd_link.head->cmd;
1065         i2c_hal_read_rxfifo(&(i2c_context[i2c_num].hal), cmd->data, p_i2c->rx_cnt);
1066         cmd->data += p_i2c->rx_cnt;
1067         if (cmd->hw_cmd.byte_num > 0) {
1068             p_i2c->cmd_idx = 0;
1069         } else {
1070             p_i2c->cmd_link.head = p_i2c->cmd_link.head->next;
1071         }
1072     } else if ((p_i2c->status == I2C_STATUS_ACK_ERROR)
1073                || (p_i2c->status == I2C_STATUS_TIMEOUT)) {
1074         evt.type = I2C_CMD_EVT_DONE;
1075         xQueueOverwriteFromISR(p_i2c->cmd_evt_queue, &evt, &HPTaskAwoken);
1076         return;
1077     } else if (p_i2c->status == I2C_STATUS_DONE) {
1078         return;
1079     }
1080 
1081     if (p_i2c->cmd_link.head == NULL) {
1082         p_i2c->cmd_link.cur = NULL;
1083         evt.type = I2C_CMD_EVT_DONE;
1084         xQueueOverwriteFromISR(p_i2c->cmd_evt_queue, &evt, &HPTaskAwoken);
1085         // Return to the IDLE status after cmd_eve_done signal were send out.
1086         p_i2c->status = I2C_STATUS_IDLE;
1087         return;
1088     }
1089     const i2c_hw_cmd_t hw_end_cmd = {
1090         .op_code = I2C_LL_CMD_END
1091     };
1092     while (p_i2c->cmd_link.head) {
1093         i2c_cmd_t *cmd = &p_i2c->cmd_link.head->cmd;
1094         i2c_hw_cmd_t hw_cmd = cmd->hw_cmd;
1095         if (cmd->hw_cmd.op_code == I2C_LL_CMD_WRITE) {
1096             uint8_t wr_filled = 0;
1097             uint8_t *write_pr = NULL;
1098             //TODO: to reduce interrupt number
1099             if (cmd->data) {
1100                 wr_filled = (cmd->hw_cmd.byte_num > SOC_I2C_FIFO_LEN) ? SOC_I2C_FIFO_LEN : cmd->hw_cmd.byte_num;
1101                 write_pr = cmd->data;
1102                 cmd->data += wr_filled;
1103                 cmd->hw_cmd.byte_num -= wr_filled;
1104             } else {
1105                 wr_filled = 1;
1106                 write_pr = &(cmd->byte_cmd);
1107                 cmd->hw_cmd.byte_num--;
1108             }
1109             hw_cmd.byte_num = wr_filled;
1110             i2c_hal_write_txfifo(&(i2c_context[i2c_num].hal), write_pr, wr_filled);
1111             i2c_hal_write_cmd_reg(&(i2c_context[i2c_num].hal), hw_cmd, p_i2c->cmd_idx);
1112             i2c_hal_write_cmd_reg(&(i2c_context[i2c_num].hal), hw_end_cmd, p_i2c->cmd_idx + 1);
1113             i2c_hal_enable_master_tx_it(&(i2c_context[i2c_num].hal));
1114             p_i2c->cmd_idx = 0;
1115             if (cmd->hw_cmd.byte_num == 0) {
1116                 p_i2c->cmd_link.head = p_i2c->cmd_link.head->next;
1117             }
1118             p_i2c->status = I2C_STATUS_WRITE;
1119             break;
1120         } else if (cmd->hw_cmd.op_code == I2C_LL_CMD_READ) {
1121             //TODO: to reduce interrupt number
1122             p_i2c->rx_cnt = cmd->hw_cmd.byte_num > SOC_I2C_FIFO_LEN ? SOC_I2C_FIFO_LEN : cmd->hw_cmd.byte_num;
1123             cmd->hw_cmd.byte_num -= p_i2c->rx_cnt;
1124             hw_cmd.byte_num = p_i2c->rx_cnt;
1125             i2c_hal_write_cmd_reg(&(i2c_context[i2c_num].hal), hw_cmd, p_i2c->cmd_idx);
1126             i2c_hal_write_cmd_reg(&(i2c_context[i2c_num].hal), hw_end_cmd, p_i2c->cmd_idx + 1);
1127             i2c_hal_enable_master_rx_it(&(i2c_context[i2c_num].hal));
1128             p_i2c->status = I2C_STATUS_READ;
1129             break;
1130         } else {
1131             i2c_hal_write_cmd_reg(&(i2c_context[i2c_num].hal), hw_cmd, p_i2c->cmd_idx);
1132         }
1133         p_i2c->cmd_idx++;
1134         p_i2c->cmd_link.head = p_i2c->cmd_link.head->next;
1135         if (p_i2c->cmd_link.head == NULL || p_i2c->cmd_idx >= 15) {
1136             p_i2c->cmd_idx = 0;
1137             break;
1138         }
1139     }
1140     i2c_hal_update_config(&(i2c_context[i2c_num].hal));
1141     i2c_hal_trans_start(&(i2c_context[i2c_num].hal));
1142     return;
1143 }
1144 
1145 #if CONFIG_SPIRAM_USE_MALLOC
1146 //Check whether read or write buffer in cmd_link is internal.
is_cmd_link_buffer_internal(const i2c_cmd_link_t * link)1147 static bool is_cmd_link_buffer_internal(const i2c_cmd_link_t *link)
1148 {
1149     const i2c_cmd_link_t *cmd_link = link;
1150     while (cmd_link != NULL)  {
1151         if (cmd_link->cmd.hw_cmd.op_code == I2C_LL_CMD_WRITE || cmd_link->cmd.hw_cmd.op_code == I2C_LL_CMD_READ) {
1152             if (cmd_link->cmd.data != NULL && !esp_ptr_internal(cmd_link->cmd.data)) {
1153                 return false;
1154             }
1155         }
1156         cmd_link = cmd_link->next;
1157     }
1158     return true;
1159 }
1160 #endif
1161 
i2c_master_cmd_begin(i2c_port_t i2c_num,i2c_cmd_handle_t cmd_handle,TickType_t ticks_to_wait)1162 esp_err_t i2c_master_cmd_begin(i2c_port_t i2c_num, i2c_cmd_handle_t cmd_handle, TickType_t ticks_to_wait)
1163 {
1164     I2C_CHECK(( i2c_num < I2C_NUM_MAX ), I2C_NUM_ERROR_STR, ESP_ERR_INVALID_ARG);
1165     I2C_CHECK(p_i2c_obj[i2c_num] != NULL, I2C_DRIVER_NOT_INSTALL_ERR_STR, ESP_ERR_INVALID_STATE);
1166     I2C_CHECK(p_i2c_obj[i2c_num]->mode == I2C_MODE_MASTER, I2C_MASTER_MODE_ERR_STR, ESP_ERR_INVALID_STATE);
1167     I2C_CHECK(cmd_handle != NULL, I2C_CMD_LINK_INIT_ERR_STR, ESP_ERR_INVALID_ARG);
1168 
1169 #if CONFIG_SPIRAM_USE_MALLOC
1170     //If the i2c read or write buffer is not in internal RAM, we will return ESP_FAIL
1171     //to avoid the ISR handler function crashing when the cache is disabled.
1172     if ((p_i2c_obj[i2c_num]->intr_alloc_flags & ESP_INTR_FLAG_IRAM)) {
1173         if (!is_cmd_link_buffer_internal(((const i2c_cmd_desc_t *)cmd_handle)->head) ) {
1174             ESP_LOGE(I2C_TAG, I2C_PSRAM_BUFFER_WARN_STR);
1175             return ESP_ERR_INVALID_ARG;
1176         }
1177     }
1178 #endif
1179     // Sometimes when the FSM get stuck, the ACK_ERR interrupt will occur endlessly until we reset the FSM and clear bus.
1180     static uint8_t clear_bus_cnt = 0;
1181     esp_err_t ret = ESP_FAIL;
1182     i2c_obj_t *p_i2c = p_i2c_obj[i2c_num];
1183     portTickType ticks_start = xTaskGetTickCount();
1184     portBASE_TYPE res = xSemaphoreTake(p_i2c->cmd_mux, ticks_to_wait);
1185     if (res == pdFALSE) {
1186         return ESP_ERR_TIMEOUT;
1187     }
1188 #ifdef CONFIG_PM_ENABLE
1189     esp_pm_lock_acquire(p_i2c->pm_lock);
1190 #endif
1191     xQueueReset(p_i2c->cmd_evt_queue);
1192     if (p_i2c->status == I2C_STATUS_TIMEOUT
1193             || i2c_hal_is_bus_busy(&(i2c_context[i2c_num].hal))) {
1194         i2c_hw_fsm_reset(i2c_num);
1195         clear_bus_cnt = 0;
1196     }
1197     i2c_reset_tx_fifo(i2c_num);
1198     i2c_reset_rx_fifo(i2c_num);
1199     const i2c_cmd_desc_t *cmd = (const i2c_cmd_desc_t *) cmd_handle;
1200     p_i2c->cmd_link.free = cmd->free;
1201     p_i2c->cmd_link.cur = cmd->cur;
1202     p_i2c->cmd_link.head = cmd->head;
1203     p_i2c->status = I2C_STATUS_IDLE;
1204     p_i2c->cmd_idx = 0;
1205     p_i2c->rx_cnt = 0;
1206     i2c_reset_tx_fifo(i2c_num);
1207     i2c_reset_rx_fifo(i2c_num);
1208     // These two interrupts some times can not be cleared when the FSM gets stuck.
1209     // so we disable them when these two interrupt occurs and re-enable them here.
1210     i2c_hal_disable_intr_mask(&(i2c_context[i2c_num].hal), I2C_LL_INTR_MASK);
1211     i2c_hal_clr_intsts_mask(&(i2c_context[i2c_num].hal), I2C_LL_INTR_MASK);
1212     //start send commands, at most 32 bytes one time, isr handler will process the remaining commands.
1213     i2c_master_cmd_begin_static(i2c_num);
1214 
1215     // Wait event bits
1216     i2c_cmd_evt_t evt;
1217     while (1) {
1218         TickType_t wait_time = xTaskGetTickCount();
1219         if (wait_time - ticks_start > ticks_to_wait) { // out of time
1220             wait_time = I2C_CMD_ALIVE_INTERVAL_TICK;
1221         } else {
1222             wait_time = ticks_to_wait - (wait_time - ticks_start);
1223             if (wait_time < I2C_CMD_ALIVE_INTERVAL_TICK) {
1224                 wait_time = I2C_CMD_ALIVE_INTERVAL_TICK;
1225             }
1226         }
1227         // In master mode, since we don't have an interrupt to detective bus error or FSM state, what we do here is to make
1228         // sure the interrupt mechanism for master mode is still working.
1229         // If the command sending is not finished and there is no interrupt any more, the bus is probably dead caused by external noise.
1230         portBASE_TYPE evt_res = xQueueReceive(p_i2c->cmd_evt_queue, &evt, wait_time);
1231         if (evt_res == pdTRUE) {
1232             if (evt.type == I2C_CMD_EVT_DONE) {
1233                 if (p_i2c->status == I2C_STATUS_TIMEOUT) {
1234                     // If the I2C slave are powered off or the SDA/SCL are connected to ground, for example,
1235                     // I2C hw FSM would get stuck in wrong state, we have to reset the I2C module in this case.
1236                     i2c_hw_fsm_reset(i2c_num);
1237                     clear_bus_cnt = 0;
1238                     ret = ESP_ERR_TIMEOUT;
1239                 } else if (p_i2c->status == I2C_STATUS_ACK_ERROR) {
1240                     clear_bus_cnt++;
1241                     if (clear_bus_cnt >= I2C_ACKERR_CNT_MAX) {
1242                         clear_bus_cnt = 0;
1243                     }
1244                     ret = ESP_FAIL;
1245                 } else {
1246                     ret = ESP_OK;
1247                 }
1248                 break;
1249             }
1250             if (evt.type == I2C_CMD_EVT_ALIVE) {
1251             }
1252         } else {
1253             ret = ESP_ERR_TIMEOUT;
1254             // If the I2C slave are powered off or the SDA/SCL are connected to ground, for example,
1255             // I2C hw FSM would get stuck in wrong state, we have to reset the I2C module in this case.
1256             i2c_hw_fsm_reset(i2c_num);
1257             clear_bus_cnt = 0;
1258             break;
1259         }
1260     }
1261     p_i2c->status = I2C_STATUS_DONE;
1262 #ifdef CONFIG_PM_ENABLE
1263     esp_pm_lock_release(p_i2c->pm_lock);
1264 #endif
1265     xSemaphoreGive(p_i2c->cmd_mux);
1266     return ret;
1267 }
1268 
i2c_slave_write_buffer(i2c_port_t i2c_num,const uint8_t * data,int size,TickType_t ticks_to_wait)1269 int i2c_slave_write_buffer(i2c_port_t i2c_num, const uint8_t *data, int size, TickType_t ticks_to_wait)
1270 {
1271     I2C_CHECK(( i2c_num < I2C_NUM_MAX ), I2C_NUM_ERROR_STR, ESP_FAIL);
1272     I2C_CHECK(p_i2c_obj[i2c_num] != NULL, I2C_DRIVER_ERR_STR, ESP_FAIL);
1273     I2C_CHECK((data != NULL), I2C_ADDR_ERROR_STR, ESP_FAIL);
1274     I2C_CHECK(p_i2c_obj[i2c_num]->mode == I2C_MODE_SLAVE, I2C_MODE_SLAVE_ERR_STR, ESP_FAIL);
1275     i2c_obj_t *p_i2c = p_i2c_obj[i2c_num];
1276 
1277     portBASE_TYPE res;
1278     int cnt = 0;
1279     portTickType ticks_end = xTaskGetTickCount() + ticks_to_wait;
1280 
1281     res = xSemaphoreTake(p_i2c->slv_tx_mux, ticks_to_wait);
1282     if (res == pdFALSE) {
1283         return 0;
1284     }
1285     ticks_to_wait = ticks_end - xTaskGetTickCount();
1286     res = xRingbufferSend(p_i2c->tx_ring_buf, data, size, ticks_to_wait);
1287     if (res == pdFALSE) {
1288         cnt = 0;
1289     } else {
1290         I2C_ENTER_CRITICAL(&(i2c_context[i2c_num].spinlock));
1291         i2c_hal_enable_slave_tx_it(&(i2c_context[i2c_num].hal));
1292         I2C_EXIT_CRITICAL(&(i2c_context[i2c_num].spinlock));
1293         cnt = size;
1294     }
1295     xSemaphoreGive(p_i2c->slv_tx_mux);
1296     return cnt;
1297 }
1298 
i2c_slave_read_buffer(i2c_port_t i2c_num,uint8_t * data,size_t max_size,TickType_t ticks_to_wait)1299 int i2c_slave_read_buffer(i2c_port_t i2c_num, uint8_t *data, size_t max_size, TickType_t ticks_to_wait)
1300 {
1301     I2C_CHECK(( i2c_num < I2C_NUM_MAX ), I2C_NUM_ERROR_STR, ESP_FAIL);
1302     I2C_CHECK(p_i2c_obj[i2c_num] != NULL, I2C_DRIVER_ERR_STR, ESP_FAIL);
1303     I2C_CHECK((data != NULL), I2C_ADDR_ERROR_STR, ESP_FAIL);
1304     I2C_CHECK(p_i2c_obj[i2c_num]->mode == I2C_MODE_SLAVE, I2C_MODE_SLAVE_ERR_STR, ESP_FAIL);
1305 
1306     size_t size = 0;
1307     size_t size_rem = max_size;
1308     i2c_obj_t *p_i2c = p_i2c_obj[i2c_num];
1309     if (xSemaphoreTake(p_i2c->slv_rx_mux, ticks_to_wait) == pdFALSE) {
1310         return 0;
1311     }
1312     portTickType ticks_rem = ticks_to_wait;
1313     portTickType ticks_end = xTaskGetTickCount() + ticks_to_wait;
1314     I2C_ENTER_CRITICAL(&(i2c_context[i2c_num].spinlock));
1315     i2c_hal_enable_slave_rx_it(&(i2c_context[i2c_num].hal));
1316     I2C_EXIT_CRITICAL(&(i2c_context[i2c_num].spinlock));
1317     while (size_rem && ticks_rem <= ticks_to_wait) {
1318         uint8_t *pdata = (uint8_t *) xRingbufferReceiveUpTo(p_i2c->rx_ring_buf, &size, ticks_to_wait, size_rem);
1319         if (pdata && size > 0) {
1320             memcpy(data, pdata, size);
1321             vRingbufferReturnItem(p_i2c->rx_ring_buf, pdata);
1322             data += size;
1323             size_rem -= size;
1324         }
1325         if (ticks_to_wait != portMAX_DELAY) {
1326             ticks_rem = ticks_end - xTaskGetTickCount();
1327         }
1328     }
1329     xSemaphoreGive(p_i2c->slv_rx_mux);
1330     return max_size - size_rem;
1331 }
1332