时钟管理之定时器

1.示例代码

/*
 * Copyright (c) 2006-2020, RT-Thread Development Team
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Change Logs:
 * Date           Author       Notes
 * 2021-02-07     冷月枫       the first version
 */

/* 动态创建两个定时器,一个单次定时,一个周期性定时并让周期性定时器运行一段时间后停止运行 */
#include <rtthread.h>

/* 定时器的控制块 */
static rt_timer_t timer1;
static rt_timer_t timer2;

static int cnt = 0;

/* 定时器1超时函数 */
static void timeout1(void* parameter)
{
  rt_kprintf("periodic timer is timeout %d\n",cnt);  // 周期性定时器运行次数

  /* 运行10次,停止周期性定时器 */
  if(cnt ++ >= 9)
  {
      rt_timer_stop(timer1);  // 停止定时器1
      rt_kprintf("periodic timer was stopped !\n");
  }
}

/* 定时器2超时函数*/
static void timeout2(void* parameter)
{
  rt_kprintf("one shot timer is timeout\n"); // 只执行1次
  rt_kprintf("one shot was stopped !\n");
}


int timer_sample(void)
{
  /* 创建定时器1 周期定时 */
    timer1 = rt_timer_create("timer1",  // 定时器名称
                             timeout1,  // 定时器超时函数
                             RT_NULL,   // 定时器超时函数参数
                             200,   // 定时器时间 10个tick  200*1ms = 200ms
                             RT_TIMER_FLAG_PERIODIC); // 周期定时

    /* 启动定时器1 */
    if(timer1 != RT_NULL)
        rt_timer_start(timer1); // 开启定时器1

    /* 创建定时器2 单次定时 */
       timer2 = rt_timer_create("timer2",  // 定时器名称
                                timeout2,  // 定时器超时函数
                                RT_NULL,   // 定时器超时函数参数
                                300,   // 定时器时间 10个tick  300*1ms = 300ms
                                RT_TIMER_FLAG_ONE_SHOT); // 单次定时

       /* 启动定时器2 */
       if(timer2 != RT_NULL)
           rt_timer_start(timer2); // 开启定时器2
return 0;
}


/* 导出到msh命令列表中 */
MSH_CMD_EXPORT(timer_sample, timer sample);

2.测试结果

在这里插入图片描述
详细文档
链接

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值