esp32 串口发送和接收

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

 

  • 1
    点赞
  • 33
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值