/
ceTmr.c
100 lines (98 loc) · 2.66 KB
/
ceTmr.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
// Description: Simple software timer
// File: ceTmr.c
// Author: Yan Naing Aye
// References:
// http://cool-emerald.blogspot.com/2010/06/soft-timer-module-for-8051.html
//ceTmrTask() is to be polled regularly e.g., by main() loop
//*****************************************************************************
#include "ceTmr.h"
//-----------------------------------------------------------------------------
volatile uint32_t _ceTmrTickCounter = 0;
uint32_t _ceTmr_index = 0;
ceTmr_t T[CE_TMR_MAX_NUMBER];//declare timers array
//-----------------------------------------------------------------------------
// Call ceTmrTick() every tick interval by an interrupt
void ceTmrTick(void)
{
_ceTmrTickCounter++;
}
//-----------------------------------------------------------------------------
// TmrTask() is to be polled regularly e.g., by main()
void ceTmrTask()
{
uint32_t i;
ceTmr_t *ptmr;
if(_ceTmrTickCounter)
{
_ceTmrTickCounter--;//_ceTmrTickCounter increases every interval, decrease it to 0 again
for(i=0;i<_ceTmr_index;i++,ptmr++)
{
ptmr = &T[i];
if(ptmr->en)//if it is enabled
{
if(--(ptmr->tick)==0)//accuracy <= one tick interval
{
ptmr->tick=ptmr->interval;//restart
if(ptmr->oneshot) ptmr->en = false;
ptmr->cbFunc(); //call time out function
}
}
}
}
}
//-----------------------------------------------------------------------------
// create timer
ceTmr_t* ceTmrCreate(uint32_t interval, bool oneshot, ceTmr_CB_t cbFunc)
{
ceTmr_t *ptmr;
if(_ceTmr_index<CE_TMR_MAX_NUMBER){
ptmr = &T[_ceTmr_index++];
ptmr->en = false;
ptmr->interval = interval;
ptmr->tick = ptmr->interval;
ptmr->oneshot = oneshot;
ptmr->cbFunc = cbFunc;
}
else {
ptmr = 0;
}
return ptmr;
}
//-----------------------------------------------------------------------------
// set timer interval
void ceTmrSetInterval(ceTmr_t *ptmr,uint32_t Interval)
{
if(ptmr)
{
ptmr->interval=Interval;
ptmr->tick=ptmr->interval;
}
}
//-----------------------------------------------------------------------------
// start timer
void ceTmrStart(ceTmr_t *ptmr)
{
if(ptmr)
{
ptmr->en=true;
}
}
//-----------------------------------------------------------------------------
// stop timer
void ceTmrStop(ceTmr_t *ptmr)
{
if(ptmr)
{
ptmr->en=false;
}
}
//-----------------------------------------------------------------------------
//Reloads a timer with its initial value
void ceTmrReset(ceTmr_t *ptmr)
{
if(ptmr)
{
ptmr->tick=ptmr->interval;
}
}
//-----------------------------------------------------------------------------