要想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在串口助手中输入数据时,有必要以空格完毕,然后点击发送,不然无法完结发送。