C51单片机——多个按键中断控制实现

C51单片机——多个按键中断控制实现

1.实现代码

/*
* 2018-10-22
*/
#include<STC15F2K60S2.h>
#define uchar unsigned char
#define uint unsigned int

sbit KEY_1 = P3^2;
sbit KEY_2 = P3^3;
sbit KEY_3 = P1^7;
sbit led_sel = P2^3;

uchar keysta[] = {1,1,1};//the current state of the key
uchar led[] = {0x80,0x40,0x20,0x10,0x08,0x04,0x02,0x01}; //The light settings
uchar i;  //number of keys
uchar j;  //number of keys
uchar backup[3] = {1,1,1};

void Init()
{
	P0M0 = 0xff; //push-pull output
 P0M1 = 0x00;
	P2M0 = 0xff;
	P2M1 = 0x00;
	
	TMOD = 0x01; //mode selection , way 1
	EA = 1;      //Open total interrupt
	TH0 = 0xf8;  //the high octet setting of the timer
	TL0 = 0xcd;  //the low octet setting of the timer
	ET0 = 1;     //start timer interruption
	TR0 = 1;     //starting switch
	
	led_sel = 1;
	P0 = 0;      //initialize
}

void InterruptTimer0() interrupt 1
{
	static uchar keybuf[3] = {0xff,0xff,0xff};//key buffer initial value

	TH0=0xf8; //The initial value is loaded each time
	TL0=0xcd;
		
	//key values into buffer
	keybuf[0] = (keybuf[0] << 1)|KEY_1;
	keybuf[1] = (keybuf[1] << 1)|KEY_2;
	keybuf[2] = (keybuf[2] << 1)|KEY_3;
	
	//update the key 
	for(i=0;i<3;i++)  //Loop check
	{
		if(keybuf[i] == 0x00) // move 8 times
		{
			keysta[i] = 0;  
		}
		else if(keybuf[i] == 0xff)
		{
			keysta[i] = 1;
		}
	}
}

void main()
{
	Init();

	while(1)
	{
		for(j=0;j<3;j++)  //Loop check
		{
			if(keysta[j] != backup[j])
			{
				if(backup[j] == 0)
				{
					P0 = led[j];
				}
			}
			backup[j]=keysta[j];
		}
	}
}

2.程序说明
若KEY1被按下,则LED灯L7发光。(其他灯熄灭)
若KEY2被按下,则LED灯L6发光。
若KEY3被按下,则LED灯L5发光。

  • 8
    点赞
  • 65
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值