c语言写的程序如何移植,完全由C语言编写,高度可移植,超级牛逼的软件定时器!...

/*

*     multi_timer.h

*

*      Created on: 20161229

*      @Author   : 晓宇

*      @version  :V1.0.0

*/

#ifndef _MULTI_TIMER_H_

#define _MULTI_TIMER_H_

#include "stdint.h"

typedef struct Timer {

uint32_t timeout;

uint32_t repeat;

void (*timeout_cb)(void);

struct Timer* next;

}Timer;

#ifdef __cplusplus

extern "C" {

#endif

void timer_init(struct Timer* handle, void(*timeout_cb)(), uint32_t timeout, uint32_t repeat);

int  timer_start(struct Timer* handle);

void timer_stop(struct Timer* handle);

void timer_ticks(void);

void timer_loop(void);

// void timer_again(struct Timer* handle);

// void timer_set_repeat(struct Timer* handle, uint32_t repeat);

#ifdef __cplusplus

}

#endif

#endif/*

*     multi_timer.c

*

*      Created on: 20161229

*      @Author   : 晓宇

*      @version  :V1.0.0

*/

#include "multi_timer.h"

//timer handle list head.

static struct Timer* head_handle = NULL;

//Timer ticks

static uint32_t _timer_ticks = 0;

/**

* @brief  Initializes the timer struct handle.

* @param  handle: the timer handle strcut.

* @param  timeout_cb: timeout callback.

* @param  repeat: repeat interval time.

* @retval None

*/

void timer_init(struct Timer* handle, void(*timeout_cb)(), uint32_t timeout, uint32_t repeat)

{

// memset(handle, sizeof(struct Timer), 0);

handle->timeout_cb = timeout_cb;

handle->timeout = _timer_ticks + timeout;

handle->repeat = repeat;

}

/**

* @brief  Start the timer work, add the handle into work list.

* @param  btn: target handle strcut.

* @retval 0: succeed. -1: already exist.

*/

int timer_start(struct Timer* handle)

{

struct Timer* target = head_handle;

while(target) {

if(target == handle) return -1;  //already exist.

target = target->next;

}

handle->next = head_handle;

head_handle = handle;

return 0;

}

/**

* @brief  Stop the timer work, remove the handle off work list.

* @param  handle: target handle strcut.

* @retval None

*/

void timer_stop(struct Timer* handle)

{

struct Timer** curr;

for(curr = &head_handle; *curr; ) {

struct Timer* entry = *curr;

if (entry == handle) {

*curr = entry->next;

//      free(entry);

} else

curr = &entry->next;

}

}

/**

* @brief  main loop.

* @param  None.

* @retval None

*/

void timer_loop()

{

struct Timer* target;

for(target=head_handle; target; target=target->next) {

if(_timer_ticks >= target->timeout) {

if(target->repeat == 0) {

timer_stop(target);

} else {

target->timeout = _timer_ticks + target->repeat;

}

target->timeout_cb();

}

}

}

/**

* @brief  background ticks, timer repeat invoking interval 1ms.

* @param  None.

* @retval None.

*/

void timer_ticks()

{

_timer_ticks++;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值