STM32多串口共用printf打印串口数据

(1)问题描述:
多串口共用printf函数,百度到的资料大部分是建议重新写一个xx_printf(format, …)。但是使用起来还是不方便,就此问题而言加上一个判断语句便可解决。
(2)解决方法:
printf函数最后调用的是int fputc(int ch, FILE *f),那么重新改写此函数便可。
(3)代码:

//标志量定义
int USART_PRINTF_FLAG = 2;//默认串口2

//改写fputc
int fputc(int ch, FILE *f)
{
    if (USART_PRINTF_FLAG == 2)
    {
        while(USART_GetFlagStatus(USART2,USART_FLAG_TC)==RESET);
        USART_SendData(USART2,(uint8_t)ch);
    }
    else
    {
        while(USART_GetFlagStatus(USART1,USART_FLAG_TC)==RESET);
        USART_SendData(USART1,(uint8_t)ch);
    }

    return ch;
}

//中断处理
void USART1_IRQHandler(void)
{
    USART_PRINTF_FLAG = 1;
    //your coding here...
}

void USART2_IRQHandler(void)
{
    USART_PRINTF_FLAG = 2;
    //your coding here...
}

猜你喜欢

转载自blog.csdn.net/huazhen1234/article/details/78512412