STM32F407 串口通信程序示例 - 实现数据接收和发送
#include "stm32f4xx.h" #include <stdio.h>
#define BAUDRATE 9600 #define BUFFER_SIZE 128
char buffer[BUFFER_SIZE]; uint8_t bufferIndex = 0; uint8_t isBufferFull = 0;
void USART2_Init(void); void USART2_SendChar(char c); void USART2_SendString(char* s); void USART2_IRQHandler(void);
int main(void) { USART2_Init(); printf('Hello, world!\n'); while (1) { if (isBufferFull) { USART2_SendString(buffer); bufferIndex = 0; isBufferFull = 0; } } }
void USART2_Init(void) { GPIO_InitTypeDef GPIO_InitStruct; USART_InitTypeDef USART_InitStruct; NVIC_InitTypeDef NVIC_InitStruct;
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOA, ENABLE);
RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART2, ENABLE);
GPIO_InitStruct.GPIO_Pin = GPIO_Pin_2 | GPIO_Pin_3;
GPIO_InitStruct.GPIO_Mode = GPIO_Mode_AF;
GPIO_InitStruct.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStruct.GPIO_OType = GPIO_OType_PP;
GPIO_InitStruct.GPIO_PuPd = GPIO_PuPd_UP;
GPIO_Init(GPIOA, &GPIO_InitStruct);
GPIO_PinAFConfig(GPIOA, GPIO_PinSource2, GPIO_AF_USART2);
GPIO_PinAFConfig(GPIOA, GPIO_PinSource3, GPIO_AF_USART2);
USART_InitStruct.USART_BaudRate = BAUDRATE;
USART_InitStruct.USART_WordLength = USART_WordLength_8b;
USART_InitStruct.USART_StopBits = USART_StopBits_1;
USART_InitStruct.USART_Parity = USART_Parity_No;
USART_InitStruct.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
USART_InitStruct.USART_Mode = USART_Mode_Rx | USART_Mode_Tx;
USART_Init(USART2, &USART_InitStruct);
NVIC_InitStruct.NVIC_IRQChannel = USART2_IRQn;
NVIC_InitStruct.NVIC_IRQChannelPreemptionPriority = 0;
NVIC_InitStruct.NVIC_IRQChannelSubPriority = 0;
NVIC_InitStruct.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStruct);
USART_ITConfig(USART2, USART_IT_RXNE, ENABLE);
USART_Cmd(USART2, ENABLE);
}
void USART2_SendChar(char c) { while (!USART_GetFlagStatus(USART2, USART_FLAG_TXE)); USART_SendData(USART2, c); }
void USART2_SendString(char* s) { while (*s) { USART2_SendChar(*s++); } }
void USART2_IRQHandler(void) { if (USART_GetITStatus(USART2, USART_IT_RXNE)) { char c = USART_ReceiveData(USART2); if (c == '\n' || c == '\r' || bufferIndex == BUFFER_SIZE - 1) { buffer[bufferIndex++] = '\n'; isBufferFull = 1; } else { buffer[bufferIndex++] = c; } } }
原文地址: https://www.cveoy.top/t/topic/n3la 著作权归作者所有。请勿转载和采集!