单片机中的ms级软定时器
扫描二维码
随时随地手机看文章
因单片机中常有一些控制与延时关联,这些操作并不需要特别高的精度,为了少敲点字,故做了这个单片机软定时器,不足之处,欢迎指正。
timer.h
#ifndef __SOFT_TIMER_H__
#define __SOFT_TIMER_H__
#define EVENT_TYPE_ONESHOT 0
#define EVENT_TYPE_PERIODIC 1
#define TMR_POOL_SIZE 20
#define HANDLE int
typedef void (*TimerProc)(void*);
void TimerInit(void);
//HANDLE : -1 means fail,
HANDLE SetTimer(unsigned long uElapse,TimerProc pFunc,void *para,unsigned int Tmr_type);
void KillTimer(HANDLE hTmr);
void TimerServer(void); // call in main loop
void TimerSignal(void); // call it in timer isr
unsigned long TmrGetTime(void);
#endif
timer.c
1#include"timer.h"23typedefstruct_tagTimer{4unsignedintelapse;5unsignedintinterval;6TimerProcpFunc;7void*para;8unsignedcharstate;9unsignedcharevent_type;10unsignedchartimeout;11}Timer_Typedef;1213#defineTMR_STATE_FREE014#defineTMR_STATE_RUNNING11516staticTimer_Typedef_timerArray[TMR_POOL_SIZE]={0};17staticunsigned_tmr_tick=0;1819voidTimerInit(void)20{2122}2324HANDLESetTimer(unsignedlonguElapse,TimerProcpFunc,void*para,unsignedintTmr_type)25{26inti,unused_slot=-1;27for(i=0;i=0)&&(hTmr timeout)&&(pTmr->pFunc))64{65(*(pTmr->pFunc))(pTmr->para);66pTmr->timeout=0;67}68pTmr++;69}70}7172voidTimerSignal(void)73{74inti=0;75Timer_Typedef*pTmr=_timerArray;7677++_tmr_tick;78for(i=0;i state==TMR_STATE_RUNNING)81{82if(pTmr->elapse==_tmr_tick)83{84if(pTmr->event_type==EVENT_TYPE_PERIODIC)85{86pTmr->elapse+=pTmr->interval;87}88else89{90pTmr->state=TMR_STATE_FREE;//killtimer91}92pTmr->timeout=1;93}94}95pTmr++;96}97}9899unsignedlongTmrGetTime(void)100{101return_tmr_tick;102}