单片机之旅——1

5 篇文章 0 订阅

题目:

         单片机接9LED灯,4个按键,按上图所示排列。4个按键分别代表 上、左、下、右。初始时9个灯的最中间那个点亮,按下按键后灯按照按键所代表的方向移动。当所亮灯到达边缘后,再次按下就循环进行。例如,如果当前所亮灯为左上角的那个红色的时,再次按下“向上键”时,所亮灯变为绿色那个;如果当前所亮灯为左上角的那个红色的时,再次按下“向左键”时,所亮灯变为黑色那个;其余以此类推。



#include<reg52.h>

sbit up 	= P2^1;
sbit right 	= P2^2;
sbit down 	= P2^3;
sbit left 	= P2^4;
sbit LED09 = P2^0;
unsigned char code LED[] = {0xfe, 0xfd, 0xfb, 0xf7,
							0xef, 0xdf, 0xbf, 0x7f};
unsigned int currentLED_light;

void delayms(unsigned int m);
void scanKey();
void main()
{
	P1 = LED[4];
	currentLED_light = 5;
	while(1)
	{
		scanKey();		
	}
}

void scanKey()
{
	if(up == 0)
	{
		delayms(10);
		if(up == 0)
		{
			if(currentLED_light == 1)
			{
				LED09 = 1;
				P1 = LED[6];
				currentLED_light = 7;
			}else if(currentLED_light == 2){
				LED09 = 1;
				P1 = LED[7];
				currentLED_light = 8;
			}else if(currentLED_light - 3 > 0){
				LED09 = 1;
				P1 = LED[currentLED_light - 4];	
				currentLED_light = 	currentLED_light - 3;
			}else if(currentLED_light - 3 == 0){
				P1 = 0xff;
				LED09 = 0;
				currentLED_light = 9;
			}								
		}
		while(!up)
		;
	}
	if(down == 0)
	{
		delayms(10);
		if(down == 0)
		{
			if(currentLED_light + 3 < 9)
			{
				LED09 = 1;
				P1 = LED[currentLED_light + 3 - 1];
				currentLED_light = currentLED_light + 3;
			}else if(currentLED_light + 3 == 9){
				P1 = 0xff;
				LED09 = 0;
				currentLED_light = 9;
			}else{
				LED09 = 1;
				P1 = LED[currentLED_light + 3 - 9 - 1];	
				currentLED_light = 	currentLED_light + 3 - 9;
			}	
		}
		while(!down)
		;
	}	
	if(left == 0)
	{
		delayms(10);
		if(left == 0)
		{
			if(currentLED_light == 7){
				P1 = 0xff;
				LED09 = 0;
				currentLED_light = 9;	
			}else if(currentLED_light - 1 == 0){
				LED09 = 1;
				P1 = LED[currentLED_light + 2 - 1];
				currentLED_light += 2;
			}else if((currentLED_light - 1)%3 == 0){
				LED09 = 1;
				P1 = LED[currentLED_light + 2 - 1];
				currentLED_light += 2;
			}else{
				LED09 = 1;
				P1 = LED[currentLED_light-1-1];
				currentLED_light -= 1;
			}
		}
		while(!left)
		;
	}
	if(right == 0)
	{
		delayms(10);
		if(right == 0)
		{
			if(currentLED_light == 8)
			{
				LED09 = 0;
				P1 = 0xff;
				currentLED_light = 9;
			}else if(currentLED_light == 3 || currentLED_light == 6)
			{
				LED09 = 1;
				P1 = LED[currentLED_light - 2 - 1];
				currentLED_light -= 2; 
			}else if(currentLED_light == 9){
				LED09 = 1;
				P1 = LED[currentLED_light - 2 - 1];
				currentLED_light -= 2;
			}else{
				P1 = LED[currentLED_light + 1 - 1];
				LED09 = 1;
				currentLED_light += 1;
			}	
		}
		while(!right)
		;
	}
}
							 
void delayms(unsigned int m)
{
	unsigned int i, j;
	for(i = m; i > 0; i--)
	{
		for(j = 110; j > 0; j--)
		;				
	}
}



评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值