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