本代码基于ESP-IDF 4.2 SDK编写,具体UART可参考官方例程
一、ESP32总共有3个串口,并且3个 串口管脚都是可以重映射的
1.串口收发代码编写
1.1加载串口相关的头文件、定义串口IO映射引脚、定义串口缓存等
/**
* This is an example which echos any data it receives on UART1 back to the sender,
* with hardware flow control turned off. It does not use UART driver event queue.
*
* - Port: UART1
* - Pin assignment: see defines below
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "driver/uart.h"
#include "driver/gpio.h"
#include "cJSON.h"
#include "esp_log.h"
#include "sdkconfig.h"
#include "esp_system.h"
#include "esp_spi_flash.h"
#define EX_UART_NUM UART_NUM_1
#define ECHO_TEST_TXD (GPIO_NUM_4)
#define ECHO_TEST_RXD (GPIO_NUM_5)
#define BUF_SIZE (1024)
static const char *TAG = "UART1";
1.2串口初始化配置函数
void uart_init(void)
{
//串口配置结构体
uart_config_t uart_config = {
.baud_rate = 9600, //波特率
.data_bits = UART_DATA_8_BITS, //数据位
.parity = UART_PARITY_DISABLE, //校验位
.stop_bits = UART_STOP_BITS_1, //停止位
.flow_ctrl = UART_HW_FLOWCTRL_DISABLE, //流控位
.source_clk = UART_SCLK_APB,
};
//设置串口
uart_param_config(EX_UART_NUM, &uart_config);
//IO映射->TX->GPIO_NUM_4,RX->GPIO_NUM_5
uart_set_pin(EX_UART_NUM, ECHO_TEST_TXD, ECHO_TEST_RXD, UART_PIN_NO_CHANGE, UART_PIN_NO_CHANGE);
//注册串口服务即使能+设置缓存区大小
uart_driver_install(EX_UART_NUM, BUF_SIZE * 2, 0, 0, NULL, 0);
}
1.3 建立串口任务
static void echo_task(void *arg)
{
//分配内存,用于串口接收
uint8_t *data = (uint8_t *)malloc(BUF_SIZE);
while (1)
{
// Read data from the UART
int len = uart_read_bytes(EX_UART_NUM, data, BUF_SIZE, 20 / portTICK_RATE_MS);
if (len > 0)
{
//在串口接收的数据增加结束符
data[len] = 0;
//将接收到的数据发出去
uart_write_bytes(EX_UART_NUM, (const char *)data, len);
}
//释放申请的内存
free(data);
//删除任务
vTaskDelete(NULL);
}
1.4 主函数:串口初始化、创建任务用于串口数据接收、测试串口发送数据
void app_main(void)
{
uart_init(); //串口初始化
//创建串口接收任务
xTaskCreate(echo_task, "uart_echo_task", 1024, NULL, 10, NULL);
}
本文档详细介绍了ESP32中UART1的使用,包括串口的重映射、收发代码编写步骤,如加载相关头文件、定义IO映射、初始化配置、建立串口任务以及主函数中的串口初始化和数据发送测试。

被折叠的 条评论
为什么被折叠?



