写一段stm32与esp8266串口通信的代码
时间: 2023-06-11 10:04:33 浏览: 112
STM32-ESP8266 基础网络通信之 UDP模式(必须接路由器)源代码
好的,以下是一段stm32与esp8266串口通信的代码:
```c
#include "stm32f10x.h"
void USART1_Init(void) {
USART_InitTypeDef USART_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1, ENABLE);
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(USART1, &USART_InitStructure);
USART_Cmd(USART1, ENABLE);
}
void USART1_SendByte(uint8_t byte) {
while (USART_GetFlagStatus(USART1, USART_FLAG_TXE) == RESET);
USART_SendData(USART1, byte);
}
void USART1_SendString(char* str) {
while (*str) {
USART1_SendByte(*str++);
}
}
void USART2_Init(void) {
USART_InitTypeDef USART_InitStructure;
RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART2, ENABLE);
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(USART2, &USART_InitStructure);
USART_Cmd(USART2, ENABLE);
}
int main(void) {
char recv;
USART1_Init();
USART2_Init();
while (1) {
if (USART_GetFlagStatus(USART2, USART_FLAG_RXNE) != RESET) {
recv = USART_ReceiveData(USART2);
USART1_SendByte(recv);
}
if (USART_GetFlagStatus(USART1, USART_FLAG_RXNE) != RESET) {
recv = USART_ReceiveData(USART1);
USART2_SendByte(recv);
}
}
}
```
这是一个简单的串口通信代码,利用stm32和esp8266之间的串口1和串口2实现数据的收发。其中,USART1接收到数据后会将数据发送到USART2,USART2接收到数据后会将数据发送回USART1。这样,两个串口之间就实现了数据的互发。
阅读全文