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发光。