定时器我首要用来延时和获取程序运转时刻.
#include “system.h”
#include “timer.h”
//定时器0中止处理程序
void (*Timer0_Isr)(void) = NULL;
//定时器0中止处理程序
void (*Timer1_Isr)(void) = NULL;
//定时器2中止处理程序
void (*Timer2_Isr)(void) = NULL;
static void __irq Isr_Timer0(void)
{
rTINT_CSTAT |= BIT5; //铲除中止标志
if(Timer0_Isr != NULL) //注册过中止服务程序
{
Timer0_Isr(); //调用中止处理程序
}
VICInterruptEnd(); //中止完毕
}
void Timer0_Init(u32 RTime,FunctionalState EnInt,void (*TimerIsr)(void))
{
rTCFG0 &= (~0xff); //铲除设置
rTCFG0 |= 65; //定时器0预分频65+1,由PCLK=66供给时钟,66分频发生1MHz的定时器时钟
rTCON &= (~0xff); //铲除设置
rTCON |= BIT3; //定时器0自动更新使能
rTCNTB0 = RTime; //重装值
rTINT_CSTAT |= BIT5; //铲除中止标志
rTINT_CSTAT |= (EnInt == ENABLE) ? BIT0 : 0; //使能定时器0中止
Timer0_Isr = TimerIsr; //注册中止服务程序
Set_IsrAddr(INT_TIMER0,(u32)Isr_Timer0); //设置中止矢量进口
Set_IntEnable(INT_TIMER0,EnInt); //使能定时器0大局中止
//以下操作发动定时器0
rTCON |= BIT1; //手动更新
rTCON &= ~BIT1; //完毕手动更新
rTCON |= BIT0; //发动定时器0
}
static void __irq Isr_Timer1(void)
{
rTINT_CSTAT |= BIT6; //铲除中止标志
if(Timer1_Isr != NULL) //注册过中止服务程序
{
Timer1_Isr(); //调用中止处理程序
}
VICInterruptEnd(); //中止完毕
}
void Timer1_Init(u32 RTime,FunctionalState EnInt,void (*TimerIsr)(void))
{
rTCFG0 &= (~0xff); //铲除设置
rTCFG0 |= 65; //定时器0预分频65+1,由PCLK=66供给时钟,66分频发生1MHz的定时器时钟,
rTCON &= (~0xff00); //铲除设置
rTCON |= BIT11; //定时器1自动更新使能
rTCNTB1 = RTime; //重装值
rTINT_CSTAT |= BIT6; //铲除中止标志
rTINT_CSTAT |= (EnInt == ENABLE) ? BIT1 : 0; //使能定时器0中止
Timer1_Isr = TimerIsr; //注册中止服务程序
Set_IsrAddr(INT_TIMER1,(u32)Isr_Timer1); //设置中止矢量进口
Set_IntEnable(INT_TIMER1,EnInt); //使能定时器1大局中止
//以下操作发动定时器0
rTCON |= BIT9; //手动更新
rTCON &= ~BIT9; //完毕手动更新
rTCON |= BIT8; //发动定时器0
}
static void __irq Isr_Timer2(void)
{
rTINT_CSTAT |= BIT7; //铲除中止标志
if(Timer2_Isr != NULL) //注册过中止服务程序
{
Timer2_Isr(); //调用中止处理程序
}
VICInterruptEnd(); //中止完毕
}
void Timer2_Init(u32 RTime,FunctionalState EnInt,void (*TimerIsr)(void))
{
rTCFG0 &= ~(0xff << 8); //铲除设置
rTCFG0 |= 65 << 8; //定时器2预分频65+1,由PCLK=66供给时钟,66分频发生1MHz的定时器时钟,
rTCON &= ~(0xf << 12); //铲除设置
rTCON |= 1 << 15; //定时器2自动更新使能
rTCNTB2 = RTime; //重装值
rTINT_CSTAT |= BIT7; //铲除中止标志
rTINT_CSTAT |= (EnInt == ENABLE) ? BIT2 : 0; //使能定时器2中止
Timer2_Isr = TimerIsr; //注册中止服务程序
Set_IsrAddr(INT_TIMER2,(u32)Isr_Timer2); //设置中止矢量进口
Set_IntEnable(INT_TIMER2,EnInt); //使能定时器1大局中止
//以下操作发动定时器2
rTCON |= BIT13; //手动更新
rTCON &= ~BIT13; //完毕手动更新
rTCON |= BIT12; //发动定时器2
}
void RunTimeInit(void)
{
Timer2_Init(0xffffffff,DISABLE,NULL);
}
void RunTimeReset(void)
{
rTCON &= ~BIT12; //中止定时器2
nop;nop;
rTCON |= BIT13; //手动更新
rTCON &= ~BIT13; //完毕手动更新
rTCON |= BIT12; //发动定时器2
}
u32 GetRunTime(void)
{
return (0xffffffff – rTCNTO2);
}
#ifndef TIMER_H_
#define TIMER_H_
void Timer0_Init(u32 RTime,FunctionalState EnInt,void (*TimerIsr)(void));//定时器0初始化函数
void Timer1_Init(u32 RTime,FunctionalState EnInt,void (*TimerIsr)(void));//定时器1初始化函数
void Timer2_Init(u32 RTime,FunctionalState EnInt,void (*TimerIsr)(void));//定时器2初始化函数
void RunTimeInit(void);//程序运转时刻核算初始化
void RunTimeReset(void);//程序运转时刻核算计数器复位并开端
u32 GetRunTime(void);//获取程序运转时刻
#endif