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