2.5 时间管理

概述

时间管理,提供了一族与时间相关的函数,可以获取/设置系统时钟滴答数(systick)、systick与毫秒单位之间互相转化、按毫秒、墙上时钟等单位进行任务睡眠的功能。

API讲解

编程实例

1、配置每秒钟的系统滴答数TOS_CFG_CPU_TICK_PER_SECOND:

#define TOS_CFG_CPU_TICK_PER_SECOND 1000u

2、编写main.c示例代码:

  1. #include "tos.h"
  2. #include "mcu_init.h"
  3.  
  4. #define STK_SIZE_TASK_DEMO 512
  5.  
  6. k_stack_t stack_task_demo[STK_SIZE_TASK_DEMO];
  7.  
  8. k_task_t task_demo;
  9.  
  10. extern void entry_task_demo(void *arg);
  11.  
  12. void entry_task_demo(void *arg)
  13. {
  14. k_time_t ms;
  15. k_tick_t systick, after_systick;
  16.  
  17. // 因为TOS_CFG_CPU_TICK_PER_SECOND为1000,也就是一秒钟会有1000个systick,因此1000个systick等于1000毫秒。
  18. systick = tos_millisec2tick(2000);
  19. printf("%d millisec equals to %lld ticks\n", 2000, systick);
  20.  
  21. ms = tos_tick2millisec(1000);
  22. printf("%lld ticks equals to %d millisec\n", (k_tick_t)1000, ms);
  23.  
  24. systick = tos_systick_get();
  25. printf("before sleep, systick is %lld\n", systick);
  26.  
  27. tos_msleep(2000);
  28.  
  29. after_systick = tos_systick_get();
  30. printf("after sleep %d ms, systick is %lld\n", 2000, after_systick);
  31.  
  32. printf("milliseconds sleep is about: %d\n", tos_ticks2millisec(after_systick - systick));
  33. }
  34.  
  35. int main(void)
  36. {
  37. board_init();
  38. tos_knl_init();
  39. (void)tos_task_create(&task_demo, "receiver_higher_prio", entry_task_demo, NULL,
  40. 4, stack_task_demo, STK_SIZE_TASK_DEMO, 0);
  41. tos_knl_start();
  42. }

运行效果

2000 millisec equals to 2000 ticks1000 ticks equals to 1000 millisecbefore sleep, systick is 7after sleep 2000 ms, systick is 2009milliseconds sleep is about: 2002

实例代码