标题:
C语言写的单片机定时器回调函数
[打印本页]
作者:
ddk2018
时间:
2018-7-15 16:18
标题:
C语言写的单片机定时器回调函数
C语言写的定时器回调函数,可以移植到任何有定时器的单片机上,只要设置单片机定时器1ms中断,这样在主循环中定时时间到了就会调用相应的函数,这样我们就有了无数个软件定时器使用,软件定时器可以启动,停止,一次性的。从别的网站下载的,分享给大家。具体参考附件程序。
0.png
(37.9 KB, 下载次数: 36)
下载附件
2018-7-15 16:51 上传
单片机源程序如下:
/*
* multi_timer.c
*
* Created on: 20161229
* @Author : 晓宇 <karaxiaoyu@gmail.com>
* @id : 芯片之家
* @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++;
}
复制代码
所有资料51hei提供下载:
MultiTimer.rar
(2.14 KB, 下载次数: 64)
2018-7-15 16:18 上传
点击文件名下载附件
定时器回掉函数
下载积分: 黑币 -5
作者:
Jodelin
时间:
2020-4-20 08:35
时钟_timer_ticks不清零,timeout一直累加,这样会出问题的
作者:
Jodelin
时间:
2020-4-20 09:30
这个程序里面会出现一个问题,就是数据溢出的问题,把判断条件改下就行了
if(_timer_ticks >= target->timeout)改为 if(_timer_ticks == target->timeout)
这样就不会在数据溢出后从零开始出现的误判问题
欢迎光临 (http://www.51hei.com/bbs/)
Powered by Discuz! X3.1