Usart1 的使用
1、usart1用作printf的打印使用。
根据芯片手册,PA9 PA10可用作uasrt1
复用功能
2、串口初始化代码
#define LOG_USARTx USART1
#define LOG_PERIPH RCC_APB2_PERIPH_USART1
#define LOG_GPIO GPIOA
#define LOG_PERIPH_GPIO RCC_AHB_PERIPH_GPIOA
#define LOG_TX_PIN GPIO_PIN_9
#define LOG_RX_PIN GPIO_PIN_10
void log_init(void)
{
GPIO_InitType GPIO_InitStructure;
USART_InitType USART_InitStructure;
// 使能RCC
RCC_AHB_Peripheral_Clock_Enable(LOG_PERIPH_GPIO);
RCC_APB2_Peripheral_Clock_Enable(RCC_APB2_PERIPH_AFIO | LOG_PERIPH);
// 初始化GPIO
GPIO_Structure_Initialize(&GPIO_InitStructure);
GPIO_InitStructure.Pin = LOG_TX_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_MODE_AF_PP;
GPIO_InitStructure.GPIO_Alternate = GPIO_AF5_USART1;
GPIO_Peripheral_Initialize(LOG_GPIO, &GPIO_InitStructure);
GPIO_InitStructure.Pin = LOG_RX_PIN;
GPIO_InitStructure.GPIO_Alternate = GPIO_AF5_USART1;
GPIO_Peripheral_Initialize(GPIOA, &GPIO_InitStructure);
//初始化串口
USART_InitStructure.BaudRate = 115200;
USART_InitStructure.WordLength = USART_WL_8B;
USART_InitStructure.StopBits = USART_STPB_1;
USART_InitStructure.Parity = USART_PE_NO;
USART_InitStructure.HardwareFlowControl = USART_HFCTRL_NONE;
USART_InitStructure.Mode = USART_MODE_TX;
// init uart
USART_Initializes(LOG_USARTx, &USART_InitStructure);
// enable uart
USART_Enable(LOG_USARTx);
}
3、main.c调用
4、printf重映射,因为gcc环境,重写_write函数
int _write (int fd, char *pBuffer, int size)
{
uint32_t i;
for (i = 0; i < size; i++)
{
USART_Data_Send(USART1, (uint8_t)pBuffer[i]);
while (USART_Flag_Status_Get(USART1, USART_FLAG_TXDE) == RESET);
}
return size;
}
5、使用printf就可以收到打印了。