天天看点

RT-Thread定时器以及结构体指针的一些思考

定时器分为软件定时器和硬件定时器。顾名思义,软件定时器就是有操作系统提供的软件定时器,硬件定时器就是用硬件芯片提供的定时器。

而在RT-Thread操作系统提供的定时器是软件定时器,但是为了便于管理,也分了硬件定时器和软件定时器(都属于上面的软件定时器)。

RT-Thread中的HARD_TIMER与SOFT_TIMER最大区别就是指向超时函数的执行位置不同,HARD_TIMER超时函数在中断上下文环境中执行,SOFT_TIMER超时函数在定时器线程上下文中执行。

下面代码将会创建两个静态定时器单次触发和周期触发

static struct rt_timer timer1; // 加上static限定只能在本文件
static struct rt_timer timer2;
static int cnt = 0;

static void timer_out1(void *parameter)
{
	rt_kprintf("periodic timer is timeout %d\n", cnt);
	if(cnt++ >= 9)
	{
		rt_timer_stop(&timer1);
		rt_kprintf("periodic timer was stop!\n");
	}
}

static void timer_out2(void *parameter)
{
	rt_kprintf("one shot timer was stop!\n");
	
}

static void timer_sample4(void) //加上void,养成好的代码习惯
{
	rt_timer_init(&timer1, "timer1", timer_out1, RT_NULL, 10, RT_TIMER_FLAG_PERIODIC);
		rt_timer_start(&timer1);
	rt_timer_init(&timer2, "timer2", timer_out2, RT_NULL, 30, RT_TIMER_FLAG_ONE_SHOT);
		rt_timer_start(&timer2);
}
MSH_CMD_EXPORT(timer_sample4, timer_active);
      

  此时仿真时能够正常执行,但是下面这个代码会报错。

static rt_timer_t timer1; // 加上static限定只能在本文件
static rt_timer_t timer2;
static int cnt = 0;

static void timer_out1(void *parameter)
{
	rt_kprintf("periodic timer is timeout %d\n", cnt);
	if(cnt++ >= 9)
	{
		rt_timer_stop(timer1);
		rt_kprintf("periodic timer was stop!\n");
	}
}

static void timer_out2(void *parameter)
{
	rt_kprintf("one shot timer was stop!\n");
	
}

static void timer_sample4(void) //加上void,养成好的代码习惯
{
	rt_timer_init(timer1, "timer1", timer_out1, RT_NULL, 10, RT_TIMER_FLAG_PERIODIC);
		rt_timer_start(timer1);
	rt_timer_init(timer2, "timer2", timer_out2, RT_NULL, 30, RT_TIMER_FLAG_ONE_SHOT);
		rt_timer_start(timer2);
}
MSH_CMD_EXPORT(timer_sample4, timer_active);
      

  我猜想是因为结构体指针不是一个对象,只是一个能够指向结构体对象的指针。后来用下面这段代码进行了测试,验证猜想正确。

static struct rt_timer timer1; // 加上static限定只能在本文件
static struct rt_timer timer2;
static rt_timer_t timer3; // 加上static限定只能在本文件
static rt_timer_t timer4;
static int cnt = 0;

static void timer_out1(void *parameter)
{
	rt_kprintf("periodic timer is timeout %d\n", cnt);
	if(cnt++ >= 9)
	{
		rt_timer_stop(&timer1);
		rt_kprintf("periodic timer was stop!\n");
	}
}

static void timer_out2(void *parameter)
{
	rt_kprintf("one shot timer was stop!\n");
	
}

static void timer_sample4(void) //加上void,养成好的代码习惯
{
	timer3 = &timer1;
	timer4 = &timer2;
	rt_timer_init(timer3, "timer1", timer_out1, RT_NULL, 10, RT_TIMER_FLAG_PERIODIC);
		rt_timer_start(&timer1);
	rt_timer_init(timer4, "timer2", timer_out2, RT_NULL, 30, RT_TIMER_FLAG_ONE_SHOT);
		rt_timer_start(&timer2);
}
MSH_CMD_EXPORT(timer_sample4, timer_active);
      

  如果有错误,欢迎在评论区指正。