51单片机用4个按钮分别控制四个LED的程序

2024-11-17 06:40:54
推荐回答(1个)
回答1:

简单编了一下程序,,,
#include
sbit led1=P1^1; //led灯,按实际再改
sbit led2=P1^2; //led灯,按实际再改
sbit led3=P1^3; //led灯,按实际再改
sbit led4=P1^4; //led灯,按实际再改
sbit key1=P2^1; //按键,按实际再改
sbit key2=P2^2; //按键,按实际再改
sbit key3=P2^3; //按键,按实际再改
sbit key4=P2^4; //按键,按实际再改
void delay(unsigned int t) //延时函数
{
while(--t);
}
void main()
{
while(1)
{
if(key1 == 0) //如果高电平按下按键就==1
{
delay(200); //按键防抖
if(key1 == 0)
{
led1=1; //如果低电平亮就=0
led2=0;
led3=0;
led4=0;
}
}
if(key2 == 0)
{
delay(200); //按键防抖
if(key2 == 0)
{
led1=0; //如果低电平亮就=0
led2=1;
led3=0;
led4=0;
}
}
if(key3 == 0)
{
delay(200); //按键防抖
if(key3 == 0)
{
led1=0; //如果低电平亮就=0
led2=0;
led3=1;
led4=0;
}
}
if(key4 == 0)
{
delay(200); //按键防抖
if(key4 == 0)
{
led1=0; //如果低电平亮就=0
led2=0;
led3=0;
led4=1;
}
}
}
}