写一个串口三,连接esp8266使能串口发送和接收中断
时间: 2023-08-05 17:06:38 浏览: 95
好的,下面是一个使用USART3连接ESP8266,使能串口发送和接收中断的示例代码:
```c
#include "stm32f4xx.h"
#include <stdio.h>
#include <string.h>
#define ESP8266_BUFFER_SIZE 64
volatile uint8_t esp8266_rx_buffer[ESP8266_BUFFER_SIZE];
volatile uint8_t esp8266_rx_index = 0;
void USART3_Init(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
USART_InitTypeDef USART_InitStructure;
NVIC_InitTypeDef NVIC_InitStructure;
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOB, ENABLE);
RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART3, ENABLE);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10 | GPIO_Pin_11;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;
GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP;
GPIO_Init(GPIOB, &GPIO_InitStructure);
GPIO_PinAFConfig(GPIOB, GPIO_PinSource10, GPIO_AF_USART3);
GPIO_PinAFConfig(GPIOB, GPIO_PinSource11, GPIO_AF_USART3);
USART_InitStructure.USART_BaudRate = 115200;
USART_InitStructure.USART_WordLength = USART_WordLength_8b;
USART_InitStructure.USART_StopBits = USART_StopBits_1;
USART_InitStructure.USART_Parity = USART_Parity_No;
USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
USART_InitStructure.USART_Mode = USART_Mode_Rx | USART_Mode_Tx;
USART_Init(USART3, &USART_InitStructure);
USART_Cmd(USART3, ENABLE);
USART_ITConfig(USART3, USART_IT_RXNE, ENABLE);
NVIC_InitStructure.NVIC_IRQChannel = USART3_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
}
void ESP8266_SendString(char* str)
{
while(*str)
{
while(USART_GetFlagStatus(USART3, USART_FLAG_TXE) == RESET);
USART_SendData(USART3, *str++);
}
}
void USART3_IRQHandler(void)
{
if(USART_GetITStatus(USART3, USART_IT_RXNE) != RESET)
{
uint8_t ch = USART_ReceiveData(USART3);
if(esp8266_rx_index < ESP8266_BUFFER_SIZE)
{
esp8266_rx_buffer[esp8266_rx_index++] = ch;
}
}
}
int main(void)
{
USART3_Init();
while(1)
{
// 发送AT指令
ESP8266_SendString("AT\r\n");
// 等待接收到ESP8266的回复
while(esp8266_rx_index == 0);
esp8266_rx_buffer[esp8266_rx_index] = '\0';
// 处理接收到的数据
printf("%s\n", esp8266_rx_buffer);
// 清空接收缓存
esp8266_rx_index = 0;
memset(esp8266_rx_buffer, 0, sizeof(esp8266_rx_buffer));
}
}
```
在该示例中,使用USART3连接ESP8266,初始化USART3模块,并使能USART3的接收中断。在USART3接收到数据后,将数据存储到esp8266_rx_buffer数组中,并递增esp8266_rx_index变量。在主循环中,发送AT指令给ESP8266,并等待接收到ESP8266的回复。当接收到数据后,使用printf函数输出到串口。然后清空接收缓存,以便下一次接收数据。
阅读全文