开关控制流水灯

 这里主要是因为电子发烧友没有编辑代码功能。。。

代码:

#include
/*四个开关分别控制	 S0 开始 S1 停止 S2	 由上往下流动	 s3  由下往上流动	   p 要求大写
*/
sbit key0 = P1^0;
sbit key1 = P1^1; 
sbit key2 = P1^2;
sbit key3 = P1^3;

//下面是延时子程序
void delay()
{	//可以计算一下时间 如果是DJNZ 那么是两个时钟周期  执行  225*225 次 计算系统时间频率
    unsigned char  i,j;
	for(i = 225; i > 0 ; i--)
	     for(j = 225; j>0 ; j--);
}
unsigned char keyscan()
{	//扫描键盘看哪个键按下这个c51 编程 其实还是有很多值得思考的

    unsigned char  keyscan_num, temp;
	 
	 P1  = 0xff ;
	 temp = P1;
	 
	 if(~(temp&0xff))
	 {		//如果按键不全为1 也就是说有键按下	这里按下时是接0的

	      if(key0 == 0)
		  {
		     keyscan_num = 0;
		  }
		  else if(key1 == 0)
		  {
	       	 keyscan_num = 1;
		  }
		  else if(key2 == 0)
		  {
		      keyscan_num = 2;
		  }
		  else if(key3 == 0)
		  {	 
		      keyscan_num = 3;
		  }
		  return keyscan_num;
	 }
}
void main()
{
    unsigned char key_num;
	
	while(1)
	{	 //要让程序持续走下去那就必须是1
	 
	     key_num = keyscan();	  //将前面的数取出来
		 switch(key_num)
		 {		 //这里面要用一些goto 语句了 这样就不用写子程序了	  goto 语句以前c 里面从来没有用过
		     case 0 :goto function0;
			 case 1 :goto function1;
			 case 2 :goto function2;
			 case 3 :goto function3;
			 default :
			 break;
		 }
		 function0:
		 P0 = 0xfe; //最后一盏灯先亮
		 delay();  //延时 其实这个我一直觉得下面一盏0xfd会很啰嗦但是这样简单 要我会这样写 
		 /*P1 = 0xfe temp = P1 for(i = 0 ; i <8; i++) a = temp>>i ; b = temp>>(8-i) P1 = a|b 右移同理*/
		 P0 = 0xfd;
		 delay();
		 P0 = 0xfb;
		 delay();
		 P0 = 0xf7;
		 delay();
		 P0 = 0xef;
		 delay();
		 P0 = 0xdf;
		 delay();
		 P0 = 0xbf;
		 delay();
		 P0 = 0x7f;
		 delay();
		 key_num = keyscan();
		 switch(key_num)
		 {
		     case 0: goto function0;
			 case 1: goto function1;
			 case 2: goto function2;
			 case 3: goto function3;
			 default: goto function0;
			 break;
		 }
		 function1:
		 P0 = 0xff; //全灭
		 key_num = keyscan();

		 switch(key_num)
		 {
		    case 0 : goto function0 ;
			case 1 : goto function1;
			case 2 : goto function2;
			case 3 : goto function3;
			default: goto function1;
			break;
		} 
		//由下往上
		function2 :
		P0 = 0xfe;
		delay();
		 P0 = 0xfd;
		 delay();
		 P0 = 0xfb;
		 delay();
		 P0 = 0xf7;
		 delay();
		 P0 = 0xef;
		 delay();
		 P0 = 0xdf;
		 delay();
		 P0 = 0xbf;
		 delay();
		 P0 = 0x7f;
		 delay();
		 key_num = keyscan();
		 switch(key_num)
		 {
		     case 0: goto function0;
			 case 1: goto function1;
			 case 2: goto function2;
			 case 3: goto function3;
			 default:goto function2;
		     break;
		 }
		 //由上往下
		 function3: 
		 P0 = 0x7f;
		 delay();
		 P0 = 0xbf;
		 delay();
		 P0 = 0xdf;
		 delay();
		 P0 = 0xef;
		 delay();
		 P0 = 0xf7;
		 delay();
		 P0 = 0xfb;
		 delay();
		 P0 = 0xfd;
		 delay();
		 P0 = 0xfe;
		 delay();
		 key_num = keyscan();
		 switch(key_num)
		 {
		    case 0 : goto function0;
			case 1 : goto function1;
			case 2 : goto function2;
			case 3 : goto function3;
			default : goto function3;
			break;

		 }

	}
}

下面给出网站链接: 点击打开链接

你可能感兴趣的:(单片机)