实验内容:
电路如图,只有一个键按下有效,软件延时,功能如下。
按下P1.0键—D0D2与D5D7交替点亮;
按下P1.1键—D0D7→D1D6→D2D5→D3D4→D0D7…
按下P1.2键—D3D4→D2D5→D1D6→D0D7→D3D4…
按下P1.3键—8只LED全灭;
实现思路:封装函数
#include "reg51.h"
#define uchar unsigned char
sbit k1=P2^0;
sbit k2=P2^1;
sbit k3=P2^2;
sbit k4=P2^3;
void delay(unsigned int ms){
unsigned int x,y;
for(x=0;x<ms;x++)
for(y=0;y<110;y++);
}
void k1yes()
{
P2=0xfa;
delay05s();
P2=0x5f;
delay05s();
}
void k2yes()
{
unsigned char i,count1,count2;
count1=0x10;
count2=0x08;
for(i=0;i<4;i++)
{
P2=~(count1+count2);
delay02s();
count1=count1<<1;
count2=count2>>1;
}
}
//测试
//void k3yes()
//{
//unsigned char i,count;
//count=0x01;
//for(i=0;i<8;i++)
//{
//P2=~count;
//delay02s();
//count=count<<1;
//}
//}
void k3yes()
{
unsigned char i,count1,count2;
count1=0x01;
count2=0x80;
for(i=0;i<4;i++)
{
P2=~(count1+count2);
delay02s();
count1=count1<<1;
count2=count2>>1;
}
}
void k4yes()
{
P2=0xff;
}
void main(void)
{
while(1)
{
if(k1==0&&k2!=0&&k3!=0&&k4!=0) k1yes();
if(k2==0&&k1!=0&&k3!=0&&k4!=0) k2yes();
if(k3==0&&k1!=0&&k2!=0&&k4!=0) k3yes();
if(k4==0&&k2!=0&&k3!=0&&k1!=0) k4yes();
P2=0xff;
}
}