1 /*
2 * Copyright (C) 2015-2020 Alibaba Group Holding Limited
3 */
4
5 #include <stdio.h>
6
7 #include <aos/kernel.h>
8
9 #if AOS_COMP_CLI
10 #include "aos/cli.h"
11 #endif
12
13 /**
14 * 该示例使用定时器管理函数来控制定时器的执行,具体场景为创建一个周期性定时器,定时调用回调函数执行,\n\r
15 * 停止定时器该变定时器的时间参数,则定时器按照修改后的时间间隔定时调用回调函数执行。
16 * 示例说明如下:
17 * 1. t0时刻,测试任务调用aos_timer_new()创建一个周期性的定时器,周期间隔为1秒,回调函数为timer1_func。然后测试任务调用aos_sleep()进入休眠状态。
18 * 2. t1时刻,相对t0过去1秒,定时器到期,回调函数timer1_func被执行。该过程重复10次。
19 * 3. tn时刻,测试任务休眠到期,调用aos_timer_stop()停止定时器。然后调用aos_timer_change()接口修改周期间隔为2秒。
20 * 4. tn+1时刻,相对tn过去2秒,定时器到期,回调函数timer1_func被执行。该过程重复5次
21 */
22
23 /* module name used by log print */
24 #define MODULE_NAME "aos_timer_example"
25
26 /* timer handle */
27 static aos_timer_t timer1;
28 static volatile int timer_count = 0;
29
30 /**
31 * timer callback function.
32 * The current use case is executed every 1000ms.
33 */
timer1_func(void * timer,void * arg)34 static void timer1_func(void *timer, void *arg)
35 {
36 /*
37 * Warning: an interface that causes a block is not allowed to be called within this function.
38 * Blocking within this function will cause other timers to run incorrectly.
39 * The printf function may also block on some platforms, so be careful how you call it.
40 */
41
42 timer_count++;
43 }
44
aos_timer_example_task(void * data)45 static void aos_timer_example_task(void *data)
46 {
47 aos_status_t status;
48
49 /**
50 * Create timer. Timer starts automatically after successful creation.
51 * some of the parameters are as follows:
52 * fn: timer1_func (this function is called when the timer expires)
53 * ms: 1000 (the cycle of the timer)
54 * option: AOS_TIMER_REPEAT (set to periodic timer), AOS_TIMER_AUTORUN (set to auto start)
55 */
56 status = aos_timer_create(&timer1, timer1_func, NULL, 1000, (AOS_TIMER_REPEAT | AOS_TIMER_AUTORUN));
57 if (status != 0) {
58 printf("[%s]create timer error\n", MODULE_NAME);
59 return;
60 }
61
62 aos_msleep(10000);
63
64 /* stop the timer before modifying the timer parameter */
65 aos_timer_stop(&timer1);
66
67 printf("[%s]timer expires %d times\n", MODULE_NAME, timer_count);
68
69 timer_count = 0;
70
71 /* the timer cycle is modified to 2000ms */
72 aos_timer_change(&timer1, 2000);
73
74 /* start the timer after the timer parameter modification is complete */
75 aos_timer_start(&timer1);
76
77 aos_msleep(10000);
78
79 printf("[%s]timer expires %d times\n", MODULE_NAME, timer_count);
80
81 }
82
aos_timer_example(int argc,char ** argv)83 static void aos_timer_example(int argc, char **argv)
84 {
85 aos_status_t status;
86 aos_task_t task_handle;
87 status = aos_task_create(&task_handle, "task_timer_test", aos_timer_example_task, NULL, NULL, 1024, 50, AOS_TASK_AUTORUN);
88 if (status != 0) {
89 printf("[%s]create %s error\n", MODULE_NAME, "task_timer_test");
90 return;
91 }
92 }
93
94 #if AOS_COMP_CLI
95 /* reg args: fun, cmd, description*/
96 ALIOS_CLI_CMD_REGISTER(aos_timer_example, timer_example, aos timer example)
97 #endif