多个软件定时器

时间:2016-05-17 00:28:35

标签: c

我一直在使用以下方法在代码中实现软件定时器:

typedef enum TIMER_CONFIG
{
    ENABLE_TIMER,
    DISABLE_TIMER,
} TIMER_CONFIG;

struct timer_module{
    uint32_t count;
    uint32_t start_count;
    unsigned int enable;
};

struct timer_module timer_1;
struct timer_module timer_2;

void tc_ms_tick(struct tc_module *const module_inst)
{
    ms_count++;     
}

volatile uint32_t get_ms_count(void){
    return(ms_count);
}

void checkTimers(void){

    if (timerIsDone(&timer_1)){
        timerConfig(&timer_1, DISABLE_TIMER,0);
        // Do something
    }

    if (timerIsDone(&timer_2)){
        timerConfig(&timer_2, DISABLE_TIMER,0);
        // Do something
    }
}

void timerConfig(struct timer_module *timer, TIMER_CONFIG timer_config, uint32_t timer_time){

    switch (timer_config)
    {
        case ENABLE_TIMER:
            timer->enable = 1;
            timer->start_count = get_ms_count();
            timer->count = timer_time;
            break;
        case DISABLE_TIMER:
            timer->enable = 0;
            break;
        default:
            //Do Nothing
            break;
    }
}

bool timerIsDone(struct timer_module *timer)
{
    bool timer_status = false;

    if (timer->enable){
        if(((get_ms_count() - timer->start_count) >= timer->count)){
            timer_status = true;
        }
    }

    return timer_status;
}

// Main loop    
int main(void)
{       
    // Set the timer for 5 seconds
    timerConfig(&timer_1, ENABLE_TIMER, 5000);

    while (1) {
        checkTimers();      // Check background timers
    }

    return 0;
}

此实现适用于大多数情况,但它不能很好地扩展。我听说过使用链接列表这样的东西,但我对C很新,我找不到一个我理解的例子。任何帮助表示赞赏!

凯尔

0 个答案:

没有答案