#include <reg52.h>
//对系统默认数据类型重新定义
typedef unsigned int u16;
typedef unsigned char u8;
//定义独立按键控制脚
sbit KEY1 = P3^1;
sbit KEY2 = P3^0;
sbit KEY3 = P3^2;
sbit KEY4 = P3^3;
//定义LED灯的管脚
sbit LED1 = P2^0; //后三个管脚我蒙的,电路板图没看,但正常运行
sbit LED2 = P2^1;
sbit LED3 = P2^2;
sbit LED4 = P2^3;
//使用宏定义独立按键下的键值
#define KEY1_PRESS 1 //易出错,部分程序写的时候加了=号,还有采用复制粘贴,容易把宏定义名或后面的对于值不改动导致出错
#define KEY2_PRESS 2
#define KEY3_PRESS 3
#define KEY4_PRESS 4
#define KEY_UNPRESS 0
//调用延时函数,Ten_us大约为10us
void delay_10us(u16 ten_us)
{
while(ten_us--); //ten_us大概时10us
}
//调用扫描函数,扫描独立按键状态
u8 key_scan(u8 mode)
{
static u8 key = 1; //声明静态变量key赋初值1
if(mode) key = 1; //mode=0时单次扫描按键,mode=1时连续扫面按键
if(key == 1 && (KEY1 == 0||KEY2 == 0||KEY3 == 0||KEY4 == 0))
{
delay_10us(1000); //1000*10=10000us=10ms
key = 0;
if(KEY1==0)
return KEY1_PRESS;
else if(KEY2 == 0)
return KEY2_PRESS;
else if(KEY3 == 0)
return KEY3_PRESS;
else if(KEY4 == 0)
return KEY4_PRESS;
}
else if(KEY1 == 1 && KEY2 == 1 && KEY3 == 1 && KEY4 == 1)
{
key = 1;
}
return KEY_UNPRESS;
}
void main() //主函数,赋无符号key初值,调用扫描程序,确认按键按下,点亮LED灯
{
u8 key = 0; //主函数必须赋初值
while(1)
{
key = key_scan(0);
if(key==KEY1_PRESS) //按键是否按下
LED1 = !LED1;
if(key==KEY2_PRESS) //按键是否按下
LED2 = !LED2;
if(key==KEY3_PRESS) //按键是否按下
LED3 = !LED3;
if(key==KEY4_PRESS) //按键是否按下
LED4 = !LED4;
}
}