STM32F103 HAL库开发的程序 - 使用 stm32f10x.h 完成并添加注释
#include 'stm32f10x.h' #include 'stm32f10x_usart.h'
USART_InitTypeDef USART_InitStructure; GPIO_InitTypeDef GPIO_InitStructure;
/**
@brief DEBUG_USART GPIO 配置,工作模式配置。115200 8-N-1 @param 无 @retval 无 */ void DEBUG_USART_Config(void) { RCC_APB2PeriphClockCmd(DEBUG_USART_CLK | DEBUG_USART_RX_GPIO_CLK | DEBUG_USART_TX_GPIO_CLK, 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(DEBUG_USART, &USART_InitStructure);
GPIO_InitStructure.GPIO_Pin = DEBUG_USART_TX_PIN; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; GPIO_Init(DEBUG_USART_TX_GPIO_PORT, &GPIO_InitStructure);
GPIO_InitStructure.GPIO_Pin = DEBUG_USART_RX_PIN; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING; GPIO_Init(DEBUG_USART_RX_GPIO_PORT, &GPIO_InitStructure);
USART_ITConfig(DEBUG_USART, USART_IT_RXNE, ENABLE); USART_Cmd(DEBUG_USART, ENABLE); }
/**
@brief USART2 中断处理函数 @param 无 @retval 无 */ void USART2_IRQHandler(void) { if (USART_GetITStatus(DEBUG_USART, USART_IT_RXNE) != RESET) { uint8_t data = USART_ReceiveData(DEBUG_USART); // 处理接收到的数据 // ... } }
/**
@brief 发送字符串 @param str: 字符串指针 @retval 无 */ void Usart_SendString(uint8_t *str) { while (*str) { USART_SendData(DEBUG_USART, *str++); while (USART_GetFlagStatus(DEBUG_USART, USART_FLAG_TXE) == RESET) { } } }
/**
@brief 清空接收缓冲区 @param 无 @retval 无 */ void uart_FlushRxBuffer(void) { // 清空接收缓冲 UART_RxPtr = 0; memset(UART_RxBuffer, 0, sizeof(UART_RxBuffer)); }
/**
@brief 重定向 c 库函数 printf 到串口 DEBUG_USART @param ch: 字符 @param f: 文件指针 @retval 返回字符 */ int fputc(int ch, FILE *f) { USART_SendData(DEBUG_USART, (uint8_t)ch); while (USART_GetFlagStatus(DEBUG_USART, USART_FLAG_TXE) == RESET) { } return ch; }
/**
@brief 重定向 c 库函数 scanf 到串口 DEBUG_USART @param f: 文件指针 @retval 返回接收到的字符 */ int fgetc(FILE *f) { while (USART_GetFlagStatus(DEBUG_USART, USART_FLAG_RXNE) == RESET) { } return (int)USART_ReceiveData(DEBUG_USART); }
原文地址: https://www.cveoy.top/t/topic/o4ux 著作权归作者所有。请勿转载和采集!