uart_async_rxtxtasks_main.c 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. /* UART asynchronous example, that uses separate RX and TX tasks
  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 "freertos/FreeRTOS.h"
  8. #include "freertos/task.h"
  9. #include "esp_system.h"
  10. #include "esp_log.h"
  11. #include "driver/uart.h"
  12. #include "soc/uart_struct.h"
  13. #include "string.h"
  14. static const int RX_BUF_SIZE = 1024;
  15. #define TXD_PIN (GPIO_NUM_4)
  16. #define RXD_PIN (GPIO_NUM_5)
  17. void init() {
  18. const uart_config_t uart_config = {
  19. .baud_rate = 115200,
  20. .data_bits = UART_DATA_8_BITS,
  21. .parity = UART_PARITY_DISABLE,
  22. .stop_bits = UART_STOP_BITS_1,
  23. .flow_ctrl = UART_HW_FLOWCTRL_DISABLE
  24. };
  25. uart_param_config(UART_NUM_1, &uart_config);
  26. uart_set_pin(UART_NUM_1, TXD_PIN, RXD_PIN, UART_PIN_NO_CHANGE, UART_PIN_NO_CHANGE);
  27. // We won't use a buffer for sending data.
  28. uart_driver_install(UART_NUM_1, RX_BUF_SIZE * 2, 0, 0, NULL, 0);
  29. }
  30. int sendData(const char* logName, const char* data)
  31. {
  32. const int len = strlen(data);
  33. const int txBytes = uart_write_bytes(UART_NUM_1, data, len);
  34. ESP_LOGI(logName, "Wrote %d bytes", txBytes);
  35. return txBytes;
  36. }
  37. static void tx_task()
  38. {
  39. static const char *TX_TASK_TAG = "TX_TASK";
  40. esp_log_level_set(TX_TASK_TAG, ESP_LOG_INFO);
  41. while (1) {
  42. sendData(TX_TASK_TAG, "Hello world");
  43. vTaskDelay(2000 / portTICK_PERIOD_MS);
  44. }
  45. }
  46. static void rx_task()
  47. {
  48. static const char *RX_TASK_TAG = "RX_TASK";
  49. esp_log_level_set(RX_TASK_TAG, ESP_LOG_INFO);
  50. uint8_t* data = (uint8_t*) malloc(RX_BUF_SIZE+1);
  51. while (1) {
  52. const int rxBytes = uart_read_bytes(UART_NUM_1, data, RX_BUF_SIZE, 1000 / portTICK_RATE_MS);
  53. if (rxBytes > 0) {
  54. data[rxBytes] = 0;
  55. ESP_LOGI(RX_TASK_TAG, "Read %d bytes: '%s'", rxBytes, data);
  56. ESP_LOG_BUFFER_HEXDUMP(RX_TASK_TAG, data, rxBytes, ESP_LOG_INFO);
  57. }
  58. }
  59. free(data);
  60. }
  61. void app_main()
  62. {
  63. init();
  64. xTaskCreate(rx_task, "uart_rx_task", 1024*2, NULL, configMAX_PRIORITIES, NULL);
  65. xTaskCreate(tx_task, "uart_tx_task", 1024*2, NULL, configMAX_PRIORITIES-1, NULL);
  66. }