1、原理图
2、源码程序
app_main.c
#include <stdio.h>
#include "esp_system.h"
#include "esp_spi_flash.h"
#include "esp_wifi.h"
#include "esp_event_loop.h"
#include "esp_log.h"
#include "esp_err.h"
#include "nvs_flash.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "driver/ledc.h"
#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "driver/uart.h"
#include "driver/gpio.h"
#include "string.h"
#include "uart0.h"
// 串口0接收任务
void uart0_rx_task()
{
uint8_t* data = (uint8_t*) malloc(RX0_BUF_SIZE+1);
while (1) {
//获取串口1接收的数据
const int rxBytes = uart_read_bytes(UART_NUM_0, data, RX0_BUF_SIZE, 10 / portTICK_RATE_MS);
if (rxBytes > 0) {
data[rxBytes] = 0;
uart_write_bytes(UART_NUM_0, "uart0 cb\r\n", strlen("uart0 cb\r\n"));
//将接收到的数据发出去
uart_write_bytes(UART_NUM_0, (char *)data, rxBytes);
}
}
free(data);
}
//用户函数入口,相当于main函数
void app_main()
{
//串口初始化
uart_config();
//创建串口0接收任务
xTaskCreate(uart0_rx_task, "uart0_rx_task", 1024*2, NULL, configMAX_PRIORITIES, NULL);
//串口0数据发送测试
uart_write_bytes(UART_NUM_0, "uart0 test OK ", strlen("uart0 test OK "));
}
uart0.c
#include "driver/uart.h"
#include "driver/gpio.h"
#include "uart0.h"
void uart_config(void)
{
//串口配置结构体
uart_config_t uart0_config, uart1_config,uart2_config;
//串口参数配置->uart0
uart0_config.baud_rate = 115200; //波特率
uart0_config.data_bits = UART_DATA_8_BITS; //数据位
uart0_config.parity = UART_PARITY_DISABLE; //校验位
uart0_config.stop_bits = UART_STOP_BITS_1; //停止位
uart0_config.flow_ctrl = UART_HW_FLOWCTRL_DISABLE; //硬件流控
uart_param_config(UART_NUM_0, &uart0_config); //设置串口
//IO映射-> T:IO1 R:IO3
uart_set_pin(UART_NUM_0, TXD0_PIN, RXD0_PIN, UART_PIN_NO_CHANGE, UART_PIN_NO_CHANGE);
//注册串口服务即使能+设置缓存区大小
uart_driver_install(UART_NUM_0, RX0_BUF_SIZE * 2, TX0_BUF_SIZE * 2, 0, NULL, 0);
}
uart0.h
#ifndef __UART0_H
#define __UART0_H
//TX-----IO1
//RX-----IO3
#define RX0_BUF_SIZE (1024)
#define TX0_BUF_SIZE (512)
#define TXD0_PIN (GPIO_NUM_1)
#define RXD0_PIN (GPIO_NUM_3)
void uart_config(void);
#endif