/*
名稱:STM32之串口
說明:對於STM32的串口通信來說,從外部看,和C51差不多。從內部看,啊。。我還不瞭解。
從使用上說,也是需要先配置USART,然後通過終端或者輪詢的方式接受或者輸出數據。由於有了固件庫函數的幫助,STM32的串口配置起來比C51還要方便不少。
本實驗完成的是輸入輸出重定向,主要是重寫了fput()和fget()函數。
*/
實驗主要代碼如下:
//USART1配置信息
void USART1_Config(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
USART_InitTypeDef USART_InitStructure;
/* config USART1 clock */
RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1 | RCC_APB2Periph_GPIOA, ENABLE);
//GPIO初始化
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP; //默認的複用功能
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOA, &GPIO_InitStructure);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
GPIO_Init(GPIOA, &GPIO_InitStructure);
/* USART1 mode config */
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);
}
//fput用作重定向,爲了使用庫函數printf()函數
int fputc(int ch, FILE *f)
{
/* 將 Printf 內容發往串口 */
USART_SendData(USART1, (unsigned char) ch);
//while (!(USART1->SR & USART_FLAG_TXE));
while( USART_GetFlagStatus(USART1,USART_FLAG_TC)!= SET);
return (ch);
}
//fgetc用作重定向,爲了使用庫函數scanf()函數
int fgetc(FILE *f)
{
while(USART_GetFlagStatus(USART1,USART_FLAG_RXNE) != SET) ; //等待不空
return (int)USART_ReceiveData(USART1);
}