uart_echo_example_main.c 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. /* UART Echo Example
  2. This example code is in the Public Domain (or CC0 licensed, at your option.)
  3. Unless required by applicable law or agreed to in writing, this
  4. software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
  5. CONDITIONS OF ANY KIND, either express or implied.
  6. */
  7. #include <stdio.h>
  8. #include "freertos/FreeRTOS.h"
  9. #include "freertos/task.h"
  10. #include "driver/uart.h"
  11. #include "driver/gpio.h"
  12. /**
  13. * This is an example which echos any data it receives on UART1 back to the sender,
  14. * with hardware flow control turned off. It does not use UART driver event queue.
  15. *
  16. * - Port: UART1
  17. * - Receive (Rx) buffer: on
  18. * - Transmit (Tx) buffer: off
  19. * - Flow control: off
  20. * - Event queue: off
  21. * - Pin assignment: see defines below
  22. */
  23. #define ECHO_TEST_TXD (GPIO_NUM_4)
  24. #define ECHO_TEST_RXD (GPIO_NUM_5)
  25. #define ECHO_TEST_RTS (UART_PIN_NO_CHANGE)
  26. #define ECHO_TEST_CTS (UART_PIN_NO_CHANGE)
  27. #define BUF_SIZE (1024)
  28. static void echo_task(void *arg)
  29. {
  30. /* Configure parameters of an UART driver,
  31. * communication pins and install the driver */
  32. uart_config_t uart_config = {
  33. .baud_rate = 115200,
  34. .data_bits = UART_DATA_8_BITS,
  35. .parity = UART_PARITY_DISABLE,
  36. .stop_bits = UART_STOP_BITS_1,
  37. .flow_ctrl = UART_HW_FLOWCTRL_DISABLE,
  38. .source_clk = UART_SCLK_APB,
  39. };
  40. uart_driver_install(UART_NUM_1, BUF_SIZE * 2, 0, 0, NULL, 0);
  41. uart_param_config(UART_NUM_1, &uart_config);
  42. uart_set_pin(UART_NUM_1, ECHO_TEST_TXD, ECHO_TEST_RXD, ECHO_TEST_RTS, ECHO_TEST_CTS);
  43. // Configure a temporary buffer for the incoming data
  44. uint8_t *data = (uint8_t *) malloc(BUF_SIZE);
  45. while (1) {
  46. // Read data from the UART
  47. int len = uart_read_bytes(UART_NUM_1, data, BUF_SIZE, 20 / portTICK_RATE_MS);
  48. // Write data back to the UART
  49. uart_write_bytes(UART_NUM_1, (const char *) data, len);
  50. }
  51. }
  52. void app_main(void)
  53. {
  54. xTaskCreate(echo_task, "uart_echo_task", 1024, NULL, 10, NULL);
  55. }