利用定时器中断使用独立按键

利用定时器中断实现独立按键

按下独立按键s2(键盘第一个按键)数码管显示1;
按下独立按键s3(键盘第一个按键)数码管显示2;
按下独立按键s5(键盘第一个按键)数码管显示4;

#include <reg52.h>
#include <intrins.h>

#define uint unsigned int
#define uchar unsigned char
sbit DU = P2^6;//数码管段选
sbit WE = P2^7;//数码管位选
sbit s2 = P3^0;//独立按键s2
sbit s3 = P3^1;//独立按键s3
sbit s5 = P3^3;//独立按键s5

uchar num ;

//共阴极数码管段选表1、2、4
uchar code table[] = {0x00,0x06,0x5b,0x66};

//毫秒级延时函数定义
void delay (uint z)
{
	uint x,y;
	for(x = z;x > 0; x--)
		for(y = 114;y > 0;y--);
}

//定时器0初始化
void timer0Init()
{
	EA = 1;//开总中断
	ET0 = 1;//开定时器中断1
	TR0 =1;
	TMOD = 0x01;
	TH0 = 0x4b;
	TL0 = 0xfd;//定时50ms  
}

void display(uchar num)
{
	P0 = 0xff;//清除断码
	WE = 1;//打开位选锁存器
	P0 = 0xfe;//1111 1110
	WE = 0;//锁存位选数据
	DU = 1;
	P0 = table[num];
	DU = 0;
}

//定时器0中断服务程序
void timer0() interrupt 1
{
	TH0 = 0x4b;
	TL0 = 0xfd;
	display(num);		
}

void main()
{
	timer0Init();
	while(1)
	{
		if(s2 == 0)//判断s2是否被按下
		{
			delay(20);//按键消抖
			if(s2 == 0)
			{	
				num = 1;
				while(!s2);//松手检测	
			}	
		}
		else if(s3 == 0)//判断s3是否被按下
		{
			delay(20);//按键消抖
			if(s3 == 0)
			{
				num = 2;
				while(!s3);//松手检测	
			}	
		}
		
		else if(s5 == 0)//判断s5是否被按下
		{
			delay(20);//按键消抖
			if(s5 == 0)
			{
				num = 3;
				while(!s5);//松手检测	
			}	
		}

	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值