实现功能:回显串口助手发送的数据,数据结束符为‘a’。
参考例程:官网串口的printf例程。
用到的串口函数接口:
HAL_UART_Init-串口初始化函数
HAL_UART_Transmit-串口发送函数
HAL_UART_Receive_IT-使能串口中断接收函数(需每次调用才能持续中断接收)
HAL_UART_IRQHandler-串口中断处理函数
HAL_UART_RxCpltCallback-串口接收回调函数
HAL_UART_ErrorCallback-串口故障回调函数
实现过程:
1.初始化函数和串口中断处理函数用STM32CUBEMX搞定,printf函数如下重定义
- #ifdef __GNUC__
- /* With GCC/RAISONANCE, small printf (option LD Linker->Libraries->Small printf
- set to 'Yes') calls __io_putchar() */
- #define PUTCHAR_PROTOTYPE int __io_putchar(int ch)
- #else
- #define PUTCHAR_PROTOTYPE int fputc(int ch, FILE *f)
- #endif /* __GNUC__ */
- PUTCHAR_PROTOTYPE
- {
- /* Place your implementation of fputc here */
- /* e.g. write a character to the EVAL_COM1 and Loop until the end of transmission */
- HAL_UART_Transmit(&usart1, (uint8_t *)&ch, 1, 0xFFFF);
-
- return ch;
2.全局变量声明
- uint16_t i;
- uint16_t Rx_Len = 0;
- uint8_t Rx_Flag = 0;
- uint8_t Rx_Buffer[20];
- uint8_t Dat_Buffer[1024];
3.在主循环前,使能串口接收
- HAL_UART_Receive_IT(&usart1, (uint8_t *)Rx_Buffer, 1);
4.主循环
- while(1)
- {
- if(Rx_Flag == 1)
- {
- for(i = 0; i < Rx_Len; i++)
- {
- printf("%c",Dat_Buffer[i]);
- }
- printf("\r\n");
- Rx_Flag = 0;
- Rx_Len = 0;
- memset(&Dat_Buffrt,0,sizeof(Dat_Buffrt));
- }
- }
|