独立按键
#include <reg51.h>
#define uint unsigned int
#define uchar unsigned char
void delay(uint timer)
{
uchar j = 124;
while(timer--)
{
while(j--);
}
}
void main()
{
uchar i;
uchar keyVal=0; //保存按键的值
bit bFlash=1; //保存灯的状态
uchar i_val=0;
P3=0xff;
keyVal=P3;
while(1)
{
for(i=0;i<8;i++)
{
if(keyVal!=P3)
{
keyVal=P3;
if((P3&0x04)==0)
{
if(bFlash)
{
i_val=i; //保存当前哪个灯在闪烁
} else
{
i = i_val;
}
bFlash = ~ bFlash;// ÐÞ¸ÄÉÁ˸״̬
}
}
if (bFlash)
{
P1 = ~(1<<i);
}
delay(200);
}
}
}
复杂的按键程序
#include <reg51.h>
#define uint unsigned int
#define uchar unsigned char
sbit k1=P3^2;
sbit k2=P3^3;
sbit led1=P2^5;
sbit led2=P2^6;
uchar code seg[] = {0xC0,0xF9,0xA4,0xB0,0x99,
0x92,0x82,0xF8,0x80,0x90,
0xff,0x0c};
void delay(uint timer)
{
uchar j = 124;
while(timer--)
{
while(j--);
}
}
void main()
{
uchar keyVal=0;
P3=0xff;
keyVal=P3;
P0 = seg[11];
while(1)
{
if(keyVal!=P3)
{
keyVal=P3;
if(k1==0)
{
delay(10);
if(k1==0)
{
led1=0;
led2=1;
P0=seg[1];
}
}
if(k2==0)
{
delay(10);
if(k2==0)
{
led1=1;
led2=0;
P0=seg[2];
}
}
}
delay(20);
}
}
按键复用
矩阵键盘
#include <reg51.h>
#define uint unsigned int
#define uchar unsigned char
uchar code seg[] = {
0x3f,0x06,0x5b,0x4f,0x66,
0x6d,0x7d,0x07,0x7f,0x6f,
0x00};
void delay(uint timer)
{
uchar j = 124;
while(timer--)
{
while(j--);
}
}
void display(uint num)
{
P2 = 0xfd;
P0 = seg[num%10];
delay(5);
P2 = 0xfe;
P0 = seg[num/10];
delay(5);
}
uchar keyscan()
{
uchar key_val = 0;
uchar tmp = 0;
P3 = 0x0f;
delay(1);
if(P3 != 0x0f)
{
delay(10);
if(P3 != 0x0f)
{
tmp = P3^0x0f;
switch(tmp)
{
case 1: key_val = 1; break;
case 2: key_val = 2; break;
case 4: key_val = 3; break;
case 8: key_val = 4; break;
default: key_val = 0;
}
P3 = 0xf0;
delay(1);
tmp = P3^0xf0;
switch(tmp)
{
case 0x10: key_val += 0; break;
case 0x20: key_val += 4; break;
case 0x40: key_val += 8; break;
case 0x80: key_val += 12; break;
default: key_val = 0;
}
}
}
return key_val;
}
void main()
{
uchar key_val = 0;
uchar tmp = 0;
P0 = 0xff;
P2 = 0xff;
key_val = 0;
while(1)
{
tmp = keyscan();
if(key_val != tmp)
{
if(tmp != 0)
{
key_val = tmp;
}
}
display(key_val);
}
}
应用编码器74ls148
#include <reg51.h>
#define uint unsigned int
#define uchar unsigned char
uchar code seg[] = {0xC0,0xF9,0xA4,0xB0,0x99,
0x92,0x82,0xF8,0x80,0x90,
0xff,0x0c};
void int1_init() interrupt 2
{
P0 = seg[P3&0x07];
}
void main()
{
EA = 1;
EX1 = 1;
IT1 = 1;
P0 = seg[0];
while(1)
{
}
}