timer_dynamic.c 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. /*
  2. * Copyright (c) 2006-2021, RT-Thread Development Team
  3. *
  4. * SPDX-License-Identifier: Apache-2.0
  5. *
  6. * Change Logs:
  7. *
  8. */
  9. /*
  10. * 程序清单:动态定时器例程
  11. *
  12. * 这个例程会创建两个动态定时器对象,一个是单次定时,一个是周期性的定时
  13. */
  14. #include <rtthread.h>
  15. #include "tc_comm.h"
  16. /* 定时器的控制块 */
  17. static rt_timer_t timer1;
  18. static rt_timer_t timer2;
  19. /* 定时器1超时函数 */
  20. static void timeout1(void* parameter)
  21. {
  22. rt_kprintf("periodic timer is timeout\n");
  23. }
  24. /* 定时器2超时函数 */
  25. static void timeout2(void* parameter)
  26. {
  27. rt_kprintf("one shot timer is timeout\n");
  28. }
  29. void timer_create_init()
  30. {
  31. /* 创建定时器1 */
  32. timer1 = rt_timer_create("timer1", /* 定时器名字是 timer1 */
  33. timeout1, /* 超时时回调的处理函数 */
  34. RT_NULL, /* 超时函数的入口参数 */
  35. 10, /* 定时长度,以OS Tick为单位,即10个OS Tick */
  36. RT_TIMER_FLAG_PERIODIC); /* 周期性定时器 */
  37. /* 启动定时器 */
  38. if (timer1 != RT_NULL)
  39. rt_timer_start(timer1);
  40. else
  41. tc_stat(TC_STAT_END | TC_STAT_FAILED);
  42. /* 创建定时器2 */
  43. timer2 = rt_timer_create("timer2", /* 定时器名字是 timer2 */
  44. timeout2, /* 超时时回调的处理函数 */
  45. RT_NULL, /* 超时函数的入口参数 */
  46. 30, /* 定时长度为30个OS Tick */
  47. RT_TIMER_FLAG_ONE_SHOT); /* 单次定时器 */
  48. /* 启动定时器 */
  49. if (timer2 != RT_NULL)
  50. rt_timer_start(timer2);
  51. else
  52. tc_stat(TC_STAT_END | TC_STAT_FAILED);
  53. }
  54. #ifdef RT_USING_TC
  55. static void _tc_cleanup()
  56. {
  57. /* 调度器上锁,上锁后,将不再切换到其他线程,仅响应中断 */
  58. rt_enter_critical();
  59. /* 删除定时器对象 */
  60. rt_timer_delete(timer1);
  61. rt_timer_delete(timer2);
  62. /* 调度器解锁 */
  63. rt_exit_critical();
  64. /* 设置TestCase状态 */
  65. tc_done(TC_STAT_PASSED);
  66. }
  67. int _tc_timer_create()
  68. {
  69. /* 设置TestCase清理回调函数 */
  70. tc_cleanup(_tc_cleanup);
  71. /* 执行定时器例程 */
  72. timer_create_init();
  73. /* 返回TestCase运行的最长时间 */
  74. return 100;
  75. }
  76. /* 输出函数命令到finsh shell中 */
  77. FINSH_FUNCTION_EXPORT(_tc_timer_create, a dynamic timer example);
  78. #else
  79. /* 用户应用入口 */
  80. int rt_application_init()
  81. {
  82. timer_create_init();
  83. return 0;
  84. }
  85. #endif