EmbeddedRelated.com

Very simple software timer framework

April 5, 2013 Coded in C

 

A very simple framework for implementing periodical timers. The library uses macros, so the source code can be difficult to read. But as you can see from the example below, using is simple and user friendly.

/*********************************************************************************/
/*                                sample usage                                   */
/*********************************************************************************/
#include <lt_timer.h>

LT_TIMER_DEC(slow_timer)		/* declaration */
LT_TIMER_IMP(slow_timer)		/* implementation */

LT_TIMER_DEC(fast_timer)		/* declaration */
LT_TIMER_IMP(fast_timer)		/* implementation */

int main(void)
{
    fast_timer_init();
    slow_timer_init();

    while(1)
    {
	if (slow_timer_expired(1000))
	{
	    //do something each 1000ms 
	}

	if (fast_timer_expired(10))
	{
	    //do something each 10ms 
        }		
	//...............
        //main program functionality
        //...............	
    }
}

/*********************************************************************************/
/*                           lt_timer definition                                 */
/*********************************************************************************/
#ifndef _LT_TIMER_H
#define _LT_TIMER_H

#include <stdint.h>

/* these definitions can vary on different platforms */
typedef unsigned int lt_ticks_t;
typedef int lt_tidiff_t;
typedef unsigned long lt_mstime_t;
typedef signed long lt_msdiff_t;

static lt_ticks_t last_ticks;
static lt_mstime_t actual_msec; 

/* it is expected increment "sys_timer_ticks" variable in some timer interrupt */
/* alternatively some function which return ticks can be provided */
#define lt_get_ticks()      (sys_timer_ticks)		
										
/* in ms (SYS_TIMER_HZ must be provided by user)*/									
#define lt_get_msbase()     (1000/SYS_TIMER_HZ)		

static inline void
lt_mstime_update()
{
  lt_ticks_t act_ticks;
  lt_mstime_t msec_diff;

  act_ticks=lt_get_ticks();
  msec_diff=((lt_tidiff_t)(act_ticks-last_ticks))*lt_get_msbase();
  last_ticks=act_ticks;

  actual_msec+=msec_diff;
}

#define LT_TIMER_DEC(cust_prefix) \
\
extern lt_mstime_t cust_prefix##_last_expired; \
static inline void \
cust_prefix##_init() \
{\
  lt_mstime_update();\
  cust_prefix##_last_expired=actual_msec;\
}\
static inline int \
cust_prefix##_expired(lt_mstime_t expiration) \
{\
  lt_mstime_update();\
  \
  if ((lt_msdiff_t)(actual_msec-cust_prefix##_last_expired)>=expiration) {\
    cust_prefix##_last_expired=actual_msec;\
    return 1;\
  }\
  \
  return 0;\
}

#define LT_TIMER_IMP(cust_prefix) \
\
lt_mstime_t cust_prefix##_last_expired; \

#endif /* _LT_TIMER_H */