中断嵌套和定时器的应用

/*
定时:使用T0作为16位定时器,最小时间单元设定为5ms(晶振为11.0592MHZ);
显示:使用4个LED作为显示器
输入:使用3个独立按键作为输入
中断嵌套:ET0= 1;EX0 = 1; 定时器0 和外部中断0两重嵌套
*/
#include <reg52.h>

#define uint unsigned int //0~65535
#define uchar unsigned char//0~255

uchar code table[] = {
						0xc0,0xf9,0xa4,0xb0,
						0x99,0x92,0x82,0xf8,
						0x80,0x90,0x88,0x83,
						0xc6,0xa1,0x86,0x8e,
					 };

//sbit buzz = P2^4;
sbit wela = P2^5;//74HC573数据锁存器的片选端
sbit dg = P2^3;	 //右边第一个LED
sbit ds = P2^2;	
sbit db = P2^1; 
sbit dq = P2^0;
sbit key1 = P3^2;//INT0的外部输入
sbit key2 = P3^3;
sbit key3 = P3^4;
sbit key4 = P3^5;
sbit key5 = P3^7;

uint t0; //定时器0计数器
uint temp;
uchar keyV1 = 0;//按键1扫描值

void delay(uint z);
void interruptInit();
void TimerInit();
void TestSMG();
void KeyScan();

int main()
{
	TimerInit();
	while(1)
	{
		if (t0 >= 200)//延时1s
		{
			t0 = 0;
			temp++;
		}
		if (temp >= 19)
			temp = 0;

		KeyScan();
		TestSMG();
	}
}
//定时器初始化
void TimerInit()
{
	TMOD = 0x01;//0000 0001   T0 16位定时器
	//延时 5000μm = 5ms
	TH0 = (65535 - 5000)/256;//高八位
	TL0 = (65535 - 5000)%256;//低八位
	interruptInit();
	TR0 = 1;
}
//定时器服务子程序
void Timer0() interrupt 1 //定时器0默认的中断优先级为1
{
	TH0 = (65535 - 5000)/256;//高八位
	TL0 = (65535 - 5000)%256;//低八位
	t0++;	
}
//中断初始化
void interruptInit()
{
	//IT0 = 1;//外部中断设为边沿触发
	EA = 1;
	ET0 = 1; //使能T0中断
	//EX0 = 1;//使能外部中断	
}
/*
//外部中断服务子程序
void key() interrupt 0//按键使用外部中断,优先级为0
{
	temp++;
} 
*/

/*
function : display temp
形参:temp
局部变量:g,s,b,q
全局位变量:dg,ds,db,dq
*/
void TestSMG()
{
	uchar g = temp%10;
	uchar s = (temp/10)%10;
	uchar b = (temp/100)%10;
	uchar q = temp/1000;

	wela = 1;
	P0 = table[g];
	wela = 0;
	dg = 0;
	ds = 1;
	db = 1;
	dq = 1;
	delay(1);

	wela = 1;
	P0 = table[s];
	wela = 0;
	dg = 1;
	ds = 0;
	db = 1;
	dq = 1;
	delay(1);

	wela = 1;
	P0 = table[b];
	wela = 0;
	dg = 1;
	ds = 1;
	db = 0;
	dq = 1;
	delay(1);

	wela = 1;
	P0 = table[q];
	wela = 0;
	dg = 1;
	ds = 1;
	db = 1;
	dq = 0;
	delay(1);
}

/*
按键扫描
全局变量:
sbit key1 = P3^2;//INT0的外部输入
sbit key2 = P3^3;
sbit key3 = P3^4;
sbit key4 = P3^5;
sbit key5 = P3^7;
uchar keyV1 = 0;//按键1扫描值
*/
void KeyScan()
{
	if (key1 == 0)
	{
		delay(1);
		if (key1 == 0)
		{
			switch(keyV1)
			{
				case 0: TR0 = 0; break;
				case 1: //重新装初值
						TH0 = (65535 - 5000)/256;//高八位
						TL0 = (65535 - 5000)%256;//低八位
						TR0 = 1;
						break;
			}
			keyV1++;
			if(keyV1 == 2)
			{
				keyV1 = 0;
			}
			
		}
		while(!key1);//下降沿去抖动
		delay(1);
		while(!key1);//上升沿去抖动
	}
	if (keyV1 == 1)
	{
		if (key2 == 0)
		{
			delay(1);
			if (key2 == 0)
			{
				temp++;
			}
			while(!key2);
			delay(1);
			while(!key2);
		}
		else 
		{
			 if (key3 == 0)
			 {
			 	delay(1);
				if (key3 == 0)
				{
					temp--;
				}
				while(!key3);
				delay(1);
				while(!key3);
			 }
		}
	}			
}

/*
********************************************
延时函数 ,z=1时,延时1ms
局部变量 x,y,z
********************************************
*/
void delay(uint z)
{
	uint x, y;
	for(x = z; z > 0; z--)
		for(y = 110; y > 0; y--); 	
}


你可能感兴趣的:(timer,function,table,X86,delay)