51单片机 用1个按键控制8盏灯,进行花样显示
发布网友
发布时间:2023-01-04 17:53
我来回答
共3个回答
热心网友
时间:2023-10-13 22:04
#include<reg51.h>
#define uint unsigned int
#define uchar unsigned char
sbit key=P2^1;//这里看你把按键设置在哪个引脚上
void delay(uint z)
unit x,y;
for(x=z;x>0;x--)
for(y=110;y>0;y--);
}
void key1()
{
if(key==0)
{
P1=0x00; //灯全亮
}
void key2()
{
if(key==0)
{
P1=0xfe;
P1=P1<<1; //左移或右移,这个自己试一下
delay(1000);
.//继续移动到最后一个灯亮
if(P1=0x80) //判断最后一个灯是否亮了,亮了就全部灭
{
P1=0xff;
}
}
}
void key3()
{
if(key==0)
{
P1=0x00; //全亮
delay(1000);
P1=~P1; //全灭 这里灭亮几次可以用for循环,不过我是直接写的顺序
//亮灭到达三次
P1=0Xff; //最后全都灭了
}
}
void main()
{
while(1)
{
key1();
while(key);
key2();
while(key);
key3();
while(key);
}
}
不知道对不,你自己试下然后修改修改吧
热心网友
时间:2023-10-13 22:04
按照你的要求写的,你可以测试一下看看!
/*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
**/
#include "REG52.H"
/*
* 按键
*/
sbit Key_In1 = P2^0;
sbit Key_In2 = P2^1;
sbit Key_In3 = P2^2;
bit Update_Flag1;
bit Update_Flag2;
bit Update_Flag3;
/* LED 0- 7 */
unsigned char const TABLE[] =
{
0xFE,
0xFD,
0xFB,
0xF7,
0xEF,
0xDF,
0xBF,
0x7F
};
/*
* 延时1ms
*/
void Delay_1ms(unsigned int Cnt)
{
unsigned int x, y;
for(x = Cnt; x > 0; x--)
for(y = 110; y > 0; y--);
}
void KeyScang(void)
{
unsigned char i;
/* 按键1 */
if(Key_In1 == 0)
{
Delay_1ms(5);
if(Key_In1 == 0)
{
Update_Flag1 = 1;
}
while(Key_In1 == 0);
}
/* 按键2 */
if(Key_In2 == 0)
{
Delay_1ms(5);
if(Key_In2 == 0)
{
Update_Flag2 = 1;
}
while(Key_In2 == 0);
}
/* 按键3 */
if(Key_In3 == 0)
{
Delay_1ms(5);
if(Key_In3 == 0)
{
Update_Flag3 = 1;
}
while(Key_In3 == 0);
}
//
/* LED全亮 */
if(Update_Flag1)
{
Update_Flag1 = 0;
P1 = 0x00; /* P1口LED全亮 */
}
/* 循环显示最后全灭 */
if(Update_Flag2)
{
Update_Flag2 = 0;
for(i = 0; i < 8; i++)
{
P1 = TABLE[i];
Delay_1ms(500);
}
P1 = 0xFF;
}
/* LED闪烁3次 */
if(Update_Flag3)
{
Update_Flag3 = 0;
P1 = 0x00;
Delay_1ms(500);
P1 = 0xFF;
Delay_1ms(500);
P1 = 0x00;
Delay_1ms(500);
P1 = 0xFF;
Delay_1ms(500);
P1 = 0x00;
Delay_1ms(500);
P1 = 0xFF;
Delay_1ms(500);
}
}
/*
*
*/
int main(void)
{
P0 = 0xFF;
P1 = 0xFF;
P2 = 0xFF;
P3 = 0xFF;
while(1)
{
KeyScang();
}
}
热心网友
时间:2023-10-13 22:04
是需要编程吗?
用什么语言?
还检测按下第四下吗?追问需要编程 C51语言 要按第四下 跪求啊
追答#include "REG52.H"
sbit Key = P1^0;
void Delay_1ms(unsigned int Cnt)
{
unsigned int x, y;
for(x = Cnt; x > 0; x--) for(y = 110; y > 0; y--);
}
bit KeyRead(void)
{
if(!Key) {
Delay_1ms(5);
if(!Key) {
while(!Key);
return 0;
}
}
return 1;
}
void main()
{
while (1) {
while (KeyRead()); //等待第一次按键
P0 = 0; //全亮
while (KeyRead()); //等待第二次按键
P0 = 0xfe; Delay_1ms(500);//流水
P0 = 0xfd; Delay_1ms(500);
P0 = 0xfb; Delay_1ms(500);
P0 = 0xf7; Delay_1ms(500);
P0 = 0xef; Delay_1ms(500);
P0 = 0xdf; Delay_1ms(500);
P0 = 0xbf; Delay_1ms(500);
P0 = 0x7f; Delay_1ms(500);
P0 = 0xFF; //全灭
while (KeyRead()); //等待第三次按键
P0 = 0; Delay_1ms(500); //全亮
P0 = 0xFF; Delay_1ms(500); //全灭
P0 = 0; Delay_1ms(500); //全亮
P0 = 0xFF; Delay_1ms(500); //全灭
P0 = 0; Delay_1ms(500); //全亮
P0 = 0xFF; Delay_1ms(500); //全灭
}
}