题目:
单片机接9个LED灯,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--)
;
}
}