1 概述
在单片机系统中,会有几个硬件定时器。在程序需要延时或者定时功能的时候需要使用定时器,但是在整个单片机里面定时器的数量是有限的。不可能每一个功能都去使用一个硬件定时器。对于时间要求不是很严格的场合,可以多个应用层功能共享使用一个定时器。所以这篇文章是基于一个硬件定时器写的一个软件定时器框架,可以移植到任何带有32位,16位,8位定时器的单片机中。本程序在GD32F350上面已经测试完成。有需要的朋友们可以移植到自己的平台上。这个定时器可以用在低功耗场景下(不能频繁中断),定时器不会频繁产生中断,根据具体时间计算产生中断的间隔。不会大量占用CPU资源。
2 定时器实现
soft_timer.h
#ifdef __cplusplus
extern "C" {
#endif
#ifndef __SOFT_TIMER_H__
#define __SOFT_TIMER_H__
#include
typedef void (*sw_func_cb_t)(void *cb_data);
#define SW_TIMER_HANDLE_MAGIC (0xdcba0000)
/*
* Step1: Call sw_timer_alloc() to allocate a software timer handle.
* Step2: Call sw_timer_start() to register the callback function and start the timer.
* Step3: Call sw_timer_stop() to stop timer , and you can call sw_timer_start to restart
* the timer.
* Step4: Call sw_timer_free() to free the allocated timer if it's no longer in use.
*/
int sw_timer_alloc(uint32_t *handle);
int sw_timer_free(uint32_t handle);
int sw_timer_start(uint32_t handle, uint32_t timeout_ms, sw_func_cb_t func, void *cb_data, uint8_t repeat);
int sw_timer_stop(uint32_t handle);
/*
* Call by hardware timer interrupt server
*/
void sw_timer_timeout_irq(void);
#endif
#ifdef __cplusplus
}
#endif
soft_timer.c
/*
* Copyright (C) 2020, 2020 huohongpeng
* Author: huohongpeng <1045338804@qq.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* Change logs:
* Date Author Notes
* 2020-09-18 huohongpeng First add
*
*/
#ifdef __cplusplus
extern "C" {
#endif
#include "soft_timer.h"
#include
#include
/*
* Software timer max number
* User to configurate [1-65535]
*/
#define SW_TIMER_MAX_NUMBER 100
/*
* Hardware timer max count value
* Note : depend on hardware platform, user to overwrite
*/
#define __HW_TIME_MAX_COUNT (0xffff)
/*
* Hardware timer how many count value equal 1ms
* Note : depend on hardware platform, user to overwrite
*/
#define __HW_TIME_COUNT_PER_MS 10
#include