1. Button circuit diagram
Define four button pins
1. When the button is pressed, the input is low level
2. If the button is not pressed, the IO has a pull-up resistor, which is high level
// Define the discipline of the key
sbit KEY1 = P3^1;
sbit KEY2 = P3^0;
sbit KEY3 = P3^2;
sbit KEY4 = P3^3;
2. LED lamp circuit diagram
LED output high level is bright
// Define the LED light control
sbit LED1 = P2^0;
sbit LED2 = P2^1;
sbit LED3 = P2^2;
sbit LED4 = P2^3;
3. Programming thought design
1. Define button management
2. Definition of LED light management
3. Define the key value of the button
4. Define a function to determine whether the button is pressed
5. First judge whether the button is pressed --> how about judging that the button is not pressed --> otherwise return not pressed
static u8 key =1; // Define a variable key of u8 type that will not be changed and assign it a value of 1
if(mode)key=1; // Continuously scan keys, here the word scan is 0, and multiple scans are 1if(key=1 && (KEY1==0 || KEY2==0 || KEY3==0 || KEY4==0)) // key1 ==0 is pressed, why use || or operator only If one is true, that button is pressed
#include "reg52.h"
// 重新命名类型
typedef unsigned char u8;
typedef unsigned int u16;
// 定义 按键的 管教
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
// 延时函数
void delay_times(u16 times)
{
while(times--);
}
// 按键函数
u8 key_scan(u8 mode)
{
static u8 key =1; // 定义一个不被改变的u8 类型的 变量 key 赋值为1
if(mode)key=1; // 连续扫描按键,这里给 是单词扫描为0 ,多次扫描为1
if(key=1 && (KEY1==0 || KEY2==0 || KEY3==0 || KEY4==0)) // key1 ==0 为按下, 为什么用 || 或运算符 只有有一个为真,就是那个按键按下了
{
delay_times(1000); // 消抖 1000us = 10 ms
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()
{
u8 key=0;
while(1)
{
key=key_scan(1); // key_scan 有返回值需要被接收
if(key==KEY1_PRESS)
LED1=~LED1; // LED1灯 取反 发光
else if(key==KEY2_PRESS)
LED2=~LED2;
else if(key==KEY3_PRESS)
LED3=~LED3;
else if(key==KEY4_PRESS)
LED4=~LED4;
}
}