软件定时器基于MultiTimer改写

定时器分为硬件定时器和软件定时器,硬件定时器个数是硬件特性,与采用的mcu有关,软件定时器理论可以无限扩展,主要受mcu的ram大小限制,易移植到任何平台,本文基于MultiTimer改写的软件定时器,跟multitimer差不多,水平有限,不足之处请谅解!!

以下代码在vs中验证过;

头文件

#ifndef __MULTI_TIMER_H__
#define __MULTI_TIMER_H__


#define TIMER_DEBUG


typedef unsigned char time_tick_type;

typedef void (*timeout_cb_typedef)(void *);

typedef struct Timer_Type{
	time_tick_type tick;
	time_tick_type timeout;
	time_tick_type repeat;
	timeout_cb_typedef timeout_cb;
	void* context;
#ifdef TIMER_DEBUG
	char *name;
#endif

	struct Timer_Type* next;
}Timer_Typedef;


#define TIMER_MODE_SINGLE		(0)
#define TIMER_MODE_REPEAT		(1)


void Timer_Init(Timer_Type* handle, time_tick_type timeout, time_tick_type repeat, timeout_cb_typedef cb, void* context);
void Timer_Start(Timer_Type* handle);
void Timer_Stop(Timer_Type* handle);
int Timer_IsRun(Timer_Type* handle);
void Timer_Loop(void);
void Timer_Ticks(void);
#ifdef TIMER_DEBUG
void Timer_Print(void);
#endif
#endif

c文件

#include "multi_timer.h"

static Timer_Type *s_Timer_HeadNode = nullptr;
static time_tick_type s_Timer_Tick = 0;
void Timer_Init(Timer_Type *handle, time_tick_type timeout, time_tick_type repeat, timeout_cb_typedef cb, void *context)
{
	if (!handle)
	{
		return;
	}
	if (!cb)
	{
		return;
	}

	handle->timeout = timeout;
	handle->repeat = repeat;
	handle->timeout_cb = cb;
	handle->context = context;
	handle->next = nullptr;
}

void Timer_Start(Timer_Type* handle)
{
	Timer_Type* node = s_Timer_HeadNode;

	if (!handle)
	{
		return;
	}
	
	if (s_Timer_HeadNode == nullptr)
	{
		handle->next = nullptr;
		s_Timer_HeadNode = handle;
		return;
	}
	while (node->next)
	{
		if (node->next == handle)
		{
			return;
		}
		node = node->next;
	}
	handle->next = nullptr;
	node->next = handle;
	node->tick = s_Timer_Tick;
}

void Timer_Stop(Timer_Type* handle)
{
	Timer_Type* node = s_Timer_HeadNode;
	Timer_Type* front_node = nullptr;

	while (node)
	{
		if (node == handle)
		{
			if (front_node)
			{
				front_node->next = node->next;
			}
			else 
			{
				s_Timer_HeadNode = node->next;
			}
			return;
		}
		front_node = node;
		node = node->next;
	}
}
int Timer_IsRun(Timer_Type* handle)
{
	Timer_Type* node = s_Timer_HeadNode;

	while (node)
	{
		if (node == handle)
		{
			return 1;
		}
		node = node->next;
	}
	return 0;
}

void Timer_Loop(void)
{
	Timer_Type* node = s_Timer_HeadNode;
	
	for(; node; node = node->next)
	{
		if((time_tick_type)(s_Timer_Tick - node->tick) >= node->timeout)
		{
			node->tick = s_Timer_Tick;
			if (node->timeout_cb)
			{
				node->timeout_cb(node->context);
			}
			if (node->repeat == TIMER_MODE_SINGLE) //单次
			{
				Timer_Stop(node);
				Timer_Print();
			}
		}
	}

}

void Timer_Ticks(void)
{
	s_Timer_Tick++;
}

#ifdef TIMER_DEBUG
#include 
void Timer_Print(void)
{
	Timer_Type* node = s_Timer_HeadNode;

	printf("Timer Print ...\r\n");
	for (; node; node = node->next)
	{
		printf("%s\r\n", node->name);
	}
	printf("-------------------\r\n");
}
#endif

你可能感兴趣的:(单片机,单片机,嵌入式)