单片机作业练习1
实验用单片机:AT89C51
编写程序,通过按键控制LED流动方式
K1定义为测试键,按下后,8个LED同时闪烁10次以测试各LED能否正常显示
K2定义为正向流动,按下后8个LED从上到下流水
K3定义为反向流动,按下后8个LED从下到上流水
K4定义为停止,按下后停止流水,所有灯熄灭
要求:
程序基本符合日常操作逻辑
注释中写明操作注意事项
(初学者,代码中有很多需要完善的地方,仅作笔记用)
实验用电路图如下:
实现代码如下:
#include <reg52.h>
unsigned char code TABLE[]={
0xff,0x7f,0xbf,0xdf,0xef,
0xf7,0xfb,0xfd,0xfe
};
sbit K1=P1^0;
sbit K2=P1^1;
sbit K3=P1^2;
sbit K4=P1^3;
unsigned char i;
unsigned char j=8;
unsigned char n=10,m;
delay()
{
unsigned int t;
for(t=0;t<32500;t++);
}
main()
{
P3=0xff;
if(K1==0)
{
for(m=1;m<=10&&K4==1&&K1==0;m++) //K1可随时断开,led不再闪烁
{ //K4闭合时灯熄灭
delay();
P3=0x00;
delay();
P3=0xff;
}
while(1&&K1==0)
P3=0xff;
}
if(K2==0) //闭合K2之前请先将开关K1断开
while(1&&K2==0&&K4==1) //K2可随时断开,led不再闪烁,K4闭合时灯熄灭
{
if(j)
{
P3=TABLE[j];
j--;
delay();
}
else j=8;
}
if(K3==0) //闭合K3之前请先将开关K2断开
while(1&&K3==0&&K4==1) //K3可随时断开,led不再闪烁,K4闭合时灯熄灭
{
if(i!=9)
{
P3=TABLE[i];
i++;
delay();
}
else i=0;
}
if(K4==0)
P3=0xff;
}