Note: In general I need to respond to the incoming uart data in less or equal time of 11/baud_rate (which is the duration of sending a uart frame)
Code: Select all
/*
UART Interrupt Example
*/
#include <stdio.h>
#include <string.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/queue.h"
#include "freertos/portmacro.h"
#include "driver/uart.h"
#include "esp_log.h"
#include "driver/gpio.h"
#include "sdkconfig.h"
#include "esp_intr_alloc.h"
#define EX_UART_NUM UART_NUM_1
#define BUF_SIZE (66)
uint8_t rxbuf[BUF_SIZE]; //Buffer for incoming data from UART
const int tx_GPIO = 22;
const int rx_GPIO = 21;
// Both definition are same and valid
//static uart_isr_handle_t *handle_console;
static intr_handle_t handle_console;
static void IRAM_ATTR uart_intr_handle(void *arg)
{
uint16_t rx_fifo_len, status;
status = UART1.int_st.val; // read UART interrupt Status
rx_fifo_len = UART1.status.rxfifo_cnt; // read number of bytes in UART buffer
for (int i = 0; i < rx_fifo_len; i++)
rxbuf[i] = UART1.fifo.rw_byte; // read all bytes
// after reading bytes from buffer clear UART interrupt status
uart_clear_intr_status(EX_UART_NUM, UART_RXFIFO_FULL_INT_CLR | UART_RXFIFO_TOUT_INT_CLR);
//Echo recieved buffer
uart_write_bytes(EX_UART_NUM, (const char*) rxbuf, rx_fifo_len);
}
void app_main(void)
{
uart_config_t uart_config = {
.baud_rate = 38400,
.data_bits = UART_DATA_8_BITS,
.parity = UART_PARITY_EVEN,
.stop_bits = UART_STOP_BITS_1,
.flow_ctrl = UART_HW_FLOWCTRL_DISABLE
};
ESP_ERROR_CHECK(uart_param_config(EX_UART_NUM, &uart_config));
//Set UART pins (using UART0 default pins ie no changes.)
ESP_ERROR_CHECK(uart_set_pin(EX_UART_NUM, tx_GPIO, rx_GPIO, UART_PIN_NO_CHANGE, UART_PIN_NO_CHANGE));
//Install UART driver, and get the queue.
ESP_ERROR_CHECK(uart_driver_install(EX_UART_NUM, BUF_SIZE * 2, 0, 0, NULL, 0));
// release the pre registered UART handler/subroutine
ESP_ERROR_CHECK(uart_isr_free(EX_UART_NUM));
// register new UART subroutine
ESP_ERROR_CHECK(uart_isr_register(EX_UART_NUM, uart_intr_handle, NULL, ESP_INTR_FLAG_IRAM, &handle_console));
// enable RX interrupt
ESP_ERROR_CHECK(uart_enable_rx_intr(EX_UART_NUM));
while (1)
{
vTaskDelay(1000);
}
}