52單片機Timer2的中斷應(yīng)用
#define MSB_reload_value 0x36
/* msb reload value exemple 高位重載值:延時60ms*/
#define LSB_reload_value 0x36
/* lsb reload value exemple 低位重載值*/
#include "reg_c51.h" //當(dāng)前文件夾內(nèi)的文件
/*
* FUNCTION_PURPOSE: This file set up timer 2 in mode 0 (16 bits auto-reload up/down counting timer).
* 用于模式0: 16位自動重載 向上/下計時
* The 16-bits register consist of all 8 bits of TH2 and all 8 bits of TL2.
* 16位寄存器由8位的TH2 和8位的TL2組成
* The EXF2 bit toggles when timer2 overflow or underflow occurs.
* 當(dāng)timer2向上/下溢出時,置位EXF2位
* EXF2 does not generate interrupt. This bit can be used to provide 17-bit resolution
* FUNCTION_INPUTS: P1.1(T2EX)=0 for down counting or 1 for up counting.
* EXF2位并不引起中斷。此位可以用來提供17位輸入功能:向上/下計數(shù)功能
* FUNCTION_OUTPUTS: void
*/
void main(void)
{
T2MOD &= 0xFC; /* T2OE=0;定時器2輸出不允許 */
T2MOD |= 0x01; /* DCEN=1;可以設(shè)置為向上/下計數(shù):此程序中為向上達(dá)到0xff時溢出*/
EXF2 = 0; /* reset flag 定時器2外部標(biāo)志位清除*/
TCLK = 0; RCLK = 0; /* disable baud rate generator 不用于波特率發(fā)生器*/
EXEN2 = 0; /* ignore events on T2EX 視T2EX(P1.1)端信號無效*/
TH2 = MSB_reload_value; /* Init msb_value 填入初始化值*/
TL2 = LSB_reload_value; /* Init lsb_value */
RCAP2H = MSB_reload_value; /* reload msb_value重載值 */
RCAP2L = LSB_reload_value; /* reload lsb_value */
C_T2 = 0; /* timer mode 定時模式*/
CP_RL2 = 0; /* reload mode 重載模式*/
EA = 1; /* interupt enable 中斷允許*/
ET2 = 1; /* enable timer2 interrupt 允許T2中斷*/
TR2 = 1; /* timer2 run 開始計時*/
while(1); /* endless */
}
/*
void main(void)
{
T2MOD &= 0xFC; /* T2OE=0;定時器2輸出不允許 */
T2MOD |= 0x01; /* DCEN=1;可以設(shè)置為向上/下計數(shù):此程序中為向上達(dá)到0xff時溢出*/
EXF2 = 0; /* reset flag 定時器2外部標(biāo)志位清除*/
TCLK = 0; RCLK = 0; /* disable baud rate generator 不用于波特率發(fā)生器*/
EXEN2 = 0; /* ignore events on T2EX 視T2EX(P1.1)端信號無效*/
TH2 = MSB_reload_value; /* Init msb_value 填入初始化值*/
TL2 = LSB_reload_value; /* Init lsb_value */
RCAP2H = MSB_reload_value; /* reload msb_value重載值 */
RCAP2L = LSB_reload_value; /* reload lsb_value */
C_T2 = 0; /* timer mode 定時模式*/
CP_RL2 = 0; /* reload mode 重載模式*/
EA = 1; /* interupt enable 中斷允許*/
ET2 = 1; /* enable timer2 interrupt 允許T2中斷*/
TR2 = 1; /* timer2 run 開始計時*/
while(1); /* endless */
}
/*
* FUNCTION_PURPOSE: timer2 interrupt
* FUNCTION_INPUTS: void
* FUNCTION_OUTPUTS: P1.2 toggle period = 2
* (65536-reload_value) cycles
*/
void it_timer2(void) interrupt 5
/* interrupt address is 0x002b 定時器2中斷向量入口*/
{
void it_timer2(void) interrupt 5
/* interrupt address is 0x002b 定時器2中斷向量入口*/
{
P0_2 = ~P0_2; /* P1.2 toggle when interrupt. 中斷時取反*/
TF2 = 0; /* reset interrupt flag 復(fù)位中斷標(biāo)志位*/
}
TF2 = 0; /* reset interrupt flag 復(fù)位中斷標(biāo)志位*/
}
評論