[应用相关] 基于STM32F4的FreeRTOS_笔记2_打印输出字符串

[复制链接]
1911|10
 楼主| goodluck09876 发表于 2018-9-11 10:55 | 显示全部楼层 |阅读模式
基于STM32F4的FreeRTOS_笔记2_打印输出字符串

关于printf()
在此用printf()函数代替示例中的vPrintString()函数,以实现通过串口将相应的字符串打印至串口助手上。对此,ST的库函数中有相应的例程,需要将以下代码添加到程序中:



 楼主| goodluck09876 发表于 2018-9-11 10:56 | 显示全部楼层
#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__ */
 楼主| goodluck09876 发表于 2018-9-11 10:56 | 显示全部楼层
需要勾选Use MicroLIB和添加stdio.h头文件;

/**
  * @brief  Retargets the C library printf function to the USART.
  * @param  None
  * @retval None
  */
PUTCHAR_PROTOTYPE
{
  /* Place your implementation of fputc here */
  /* e.g. write a character to the USART */
  USART_SendData(USART1, (uint8_t) ch);

  /* Loop until the end of transmission */
  while (USART_GetFlagStatus(USART1, USART_FLAG_TC) == RESET)
  {}

  return ch;
}
 楼主| goodluck09876 发表于 2018-9-11 10:57 | 显示全部楼层
通过同一个任务代码创建两个任务实例,以此实现两个任务分别打印输出Task 1 is running和Task 2 is running。

void vTaskFunction(void *pvParameters)
{
    /* 需要打印输出的字符串从入口参数传入,强制转换为字符串指针。 */
    const char *pcTaskName = (char *)pvParameters;
    volatile unsigned long ul;

    while(1)
    {
        /* 打印输出任务名 */
        printf(pcTaskName);

        /* 用以产生一个周期延时 */
        for(ul = 0; ul < mainDELAY_LOOP_COUNT; ul++)
        {
        }
    }
}
 楼主| goodluck09876 发表于 2018-9-11 10:57 | 显示全部楼层
static const char *pcTextForTask1 = "Task 1 is running\r\n";
static const char *pcTextForTask2 = "Task 2 is running\r\n";

int main(void)
{
    /* Perform any hardware setup necessary. */
    prvSetupHardware();

    /* --- APPLICATION TASKS CAN BE CREATED HERE --- */
    /* 由相同的任务代码创建多个任务,仅是传入的参数不同。 */
    xTaskCreate(vTaskFunction, "Task 1", 1000, (void *)pcTextForTask1, 1, NULL);
    xTaskCreate(vTaskFunction, "Task 2", 1000, (void *)pcTextForTask2, 1, NULL);

    /* Start the created tasks running. */
    vTaskStartScheduler();

    /* Execution will only reach here if there was insufficient heap to
    start the scheduler. */
    while(1);
}

702625b972f10212e1.png
 楼主| goodluck09876 发表于 2018-9-11 10:57 | 显示全部楼层
不难看出输出结果未达到预期,这是因为时间片长度太短,以致在一个时间片长度内未能输出全部字符串便被另一个任务所打断,参考《FreeRTOS实时内核使用指南》第17页的相关内容,不妨将configTICK_RATE_HZ设为100(HZ),效果如下图所示:

257935b972f29add5e.png
磨砂 发表于 2018-9-11 13:10 | 显示全部楼层
非常感谢楼主分享
晓伍 发表于 2018-9-11 13:13 | 显示全部楼层
楼主的讲解很详细
木木guainv 发表于 2018-9-12 19:38 | 显示全部楼层
非常感谢楼主分享
 楼主| goodluck09876 发表于 2018-9-12 21:01 | 显示全部楼层
不用客气,一起探讨吧!
dingbo95 发表于 2018-9-12 22:42 | 显示全部楼层
其实跟裸机也没什么区别
您需要登录后才可以回帖 登录 | 注册

本版积分规则

220

主题

5843

帖子

25

粉丝
快速回复 在线客服 返回列表 返回顶部