ESP32_UART串口通讯

冇雨
2024-11-22 / 0 评论 / 45 阅读 / 正在检测是否收录...

#include <stdio.h>
#include <inttypes.h>
#include "sdkconfig.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "driver/ledc.h"
#include "driver/uart.h"
#include "driver/gpio.h"
#include "string.h"

//UART1
#define RX1_BUF_SIZE 1024
#define TX1_BUF_SIZE 512
#define RXD1_PIN     16
#define TXD1_PIN     17

//串口配置函数
void uart_init()
{
    //UART1结构体配置
    uart_config_t uart1_config = 
    {
        .baud_rate = 115200 ,//波特率
        .data_bits =UART_DATA_8_BITS,//数据位
        .parity    =UART_PARITY_DISABLE,//校验位
        .stop_bits =UART_STOP_BITS_1,//停止位
        .flow_ctrl =UART_HW_FLOWCTRL_DISABLE,//硬件流控
    };
    //绑定串口
    uart_param_config(UART_NUM_0,&uart1_config);
    //映射IO口
    uart_set_pin(UART_NUM_0,UART_PIN_NO_CHANGE,UART_PIN_NO_CHANGE,UART_PIN_NO_CHANGE,UART_PIN_NO_CHANGE);
    //注册串口服务即使能+设置缓存区大小
    uart_driver_install(UART_NUM_0, RX1_BUF_SIZE * 2, TX1_BUF_SIZE * 2, 0, NULL, 0);
}
/*
 * 串口1接收任务
*/
 void uart1_rx_task()
 {
    uint8_t* data = (uint8_t*) malloc(RX1_BUF_SIZE+1);//分配内存,用于串口接收
    while (1) 
    {
        //获取串口1接收的数据
        const int rxBytes = uart_read_bytes(UART_NUM_0, data, RX1_BUF_SIZE, 10 / portTICK_PERIOD_MS);
        if (rxBytes > 0) 
        {
            data[rxBytes] = 0;//在串口接收的数据增加结束符
            //将接收到的数据发出去
            uart_write_bytes(UART_NUM_0, (char *)data, rxBytes);
        }
    }
    free(data);//释放申请的内存
}

void app_main(void)
{
   uart_init();
    //创建串口1接收任务
    xTaskCreate(uart1_rx_task, "uart1_rx_task", 1024*2, NULL, 1, NULL);
    //串口1数据发送测试
    uart_write_bytes(UART_NUM_0, "uart1 test OK ", strlen("uart1 test OK "));
}
0

评论

博主关闭了所有页面的评论