要想printf()和scanf() 函數工作,我們需要把printf()和scanf() 重新定向到串口中。重定向是指用戶可以自己重寫C 的庫函數,當連接器檢查到用戶編寫了與C 庫函數相同名字的函數時,優先采用用戶編寫的函數,這樣用戶就可以實現對庫的修改了。為了實現重定向printf()和scanf() 函數,我們需要分別重寫fputc()和fgetc() 這兩個C 標準庫函數。
一、移植printf()函數,重定向C庫函數printf到USART1
int fputc(int ch, FILE *f)
{
HAL_UART_Transmit(&huart1, (uint8_t *)&ch,1, 0xFFFF);
return ch;
}
注釋:
調用了函數?HAL_UART_Transmit()
/**
* @brief? Sends an amount of data in blocking mode.
* @param? huart: Pointer to a UART_HandleTypeDefstructure that contains
*????? ??????????the configuration information for thespecified UART module.
* @param? pData: Pointer to data buffer
* @param? Size: Amount of data to be sent
* @param? Timeout: Timeout duration?
* @retval HAL status
*/
HAL_StatusTypeDef ? ?HAL_UART_Transmit(UART_HandleTypeDef *huart,uint8_t *pData, uint16_t Size, uint32_t Timeout)
二、移植scanf()函數,重定向C庫函數scanf到USART1
int fgetc(FILE *f)
{
uint8_t ?ch;
HAL_UART_Receive(&huart1,(uint8_t *)&ch, 1, 0xFFFF);
return ?ch;
}
注釋:
調用了函數?HAL_UART_Receive()
/**
* @brief? Receives an amount of data in blocking mode.
* @param? huart: Pointer to a UART_HandleTypeDefstructure that contains
*??????????????? the configuration informationfor the specified UART module.
* @param? pData: Pointer to data buffer
* @param? Size: Amount of data to be received
* @param? Timeout: Timeout duration
* @retval HAL status
*/
HAL_StatusTypeDef ? HAL_UART_Receive(UART_HandleTypeDef *huart,uint8_t *pData, uint16_t Size, uint32_t Timeout)
提示:printf和scanf都是用輪詢方式,沒有使用中斷。調用scanf在串口助手中輸入數據時,必須以空格結束,然后點擊發送,否則無法完成發送。
評論