解决STM32+FreeRTOS的printf重定向打印凌乱的问题

本内容基于正点原子STM32F103系列开发板开发调试。

由于引入了FreeRTOS后,出现了任务调度,就出现了打印之间互相穿插,杂乱无章的情况。
打印如下所示:

LED Running!
Task test tTask test wo!
Task tethree!
st one!
Task test tTask test wo!
Task tethree!
st one!
LED Running!
Task test tTask test wo!
Task tethree!
st one!
Task test tTask test wo!
Task tethree!
st one!
Task test tTask test wo!
Task tethree!
st one!
LED Running!

代码如下:

#pragma import(__use_no_semihosting)             
//标准库需要的支持函数                 
struct __FILE 
{ 
	int handle; 

}; 

FILE __stdout;       
//定义_sys_exit()以避免使用半主机模式    
_sys_exit(int x) 
{ 
	x = x; 
} 
//重定义fputc函数 
int fputc(int ch, FILE *f)
{      
	while((USART1->SR&0X40)==0);//循环发送,直到发送完毕  
    USART1->DR = (u8) ch;     
	return ch;
}
#endif 

为了解决这个问题,在printf重定向时并不直接打印,而是存入一个u8队列里,然后开一个优先级为1的打印任务来打印这个队列里的数据。
代码如下:


//重定义fputc函数 
int fputc(int ch, FILE *f)
{      
    // 在这里存入到一个数据缓冲区内
    // 然后在其他地方循环打印
    PrintQueue_InQueue((u8) ch);
	return ch;
}
// 打印任务,从消息队列里取数据然后来打印
void Print_Task(void* pvParameters)
{   
    // 局部变量
    u8 ch = 0xFF;
    //
    while(1)
    {
        if(PrintQueue_OutQueue(&ch) == PrintQueue_OK)
        {    
            USART1_SendByte(ch);
        }
    }
}

增加这个处理后的打印就恢复正常了,打印如下所示:

LED Running!
Task test two!
Task test three!
Task test one!
Task test two!
Task test three!
Task test one!
Task test two!
Task test three!
Task test one!
LED Running!
Task test two!
Task test three!
Task test one!
Task test two!
Task test three!
Task test one!
LED Running!
Task test two!
Task test three!
Task test one!
Task test two!
Task test three!

至此打印混乱问题基本算是解决了。

评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值