要想printf()和scanf() 函數(shù)工作,我們需要把printf()和scanf() 重新定向到串口中。重定向是指用戶可以自己重寫C 的庫(kù)函數(shù),當(dāng)連接器檢查到用戶編寫了與C 庫(kù)函數(shù)相同名字的函數(shù)時(shí),優(yōu)先采用用戶編寫的函數(shù),這樣用戶就可以實(shí)現(xiàn)對(duì)庫(kù)的修改了。為了實(shí)現(xiàn)重定向printf()和scanf() 函數(shù),我們需要分別重寫fputc()和fgetc() 這兩個(gè)C 標(biāo)準(zhǔn)庫(kù)函數(shù)。
一、移植printf()函數(shù),重定向C庫(kù)函數(shù)printf到USART1
int fputc(int ch, FILE *f)
{
HAL_UART_Transmit(&huart1, (uint8_t *)&ch,1, 0xFFFF);
return ch;
}
注釋:
調(diào)用了函數(shù)?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()函數(shù),重定向C庫(kù)函數(shù)scanf到USART1
int fgetc(FILE *f)
{
uint8_t ?ch;
HAL_UART_Receive(&huart1,(uint8_t *)&ch, 1, 0xFFFF);
return ?ch;
}
注釋:
調(diào)用了函數(shù)?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都是用輪詢方式,沒有使用中斷。調(diào)用scanf在串口助手中輸入數(shù)據(jù)時(shí),必須以空格結(jié)束,然后點(diǎn)擊發(fā)送,否則無法完成發(fā)送。
評(píng)論
查看更多