一种简单好用的单片机液晶屏按键菜单控制程序

这是一种古老的方法,得有十几年了吧,当年在某论坛上很火,实现的方式简洁明了,只需要一个结构体和一个对应的结构体数组,构思实属巧妙,一些概念很绕我就不具体解释了,以免误人,贴一个实现菜单的程序代码部分,菜单实现的是四个单片机方块游戏,通过上下键进行选择,确定键进入游戏。

其他无关紧要的代码就不贴了,来看

首先定义一个变量用来保存按键功能索引号和一个指向按键功能函数的指针。

uchar KeyFunctionIndex=0;//按键功能索引号
void (*KeyFunctionPtr)(); //按键功能指针

void Function0(void);
void Function1(void);
void Function2(void);
void Function3(void);
void Function4(void);
void Function5(void);
void Function6(void);
void Function7(void);

然后定义一个结构体和一个结构体数组

typedef struct 
{
   uchar CurrentIndex;   //当前功能索引号
   uchar UpKeyIndex;     //按下上键时的功能索引号
   uchar DownKeyIndex;   //按下下键时的功能索引号
   uchar LeftKeyIndex;   //按下左键时的功能索引号
   uchar RightKeyIndex;  //按下右键时的功能索引号
   uchar OkKeyIndex;     //按下确定键时的功能索引号
   void (*CurrentFunction)();  //当前执行的功能
} KeyIndex;

KeyIndex code IndexTab[8]=
{
   {0,3,1,0,0,4,(*Function0)},//当前功能0 按上键对应功能3,按下键对应功能1,以此类推 选择上刀山
   {1,0,2,0,0,5,(*Function1)},//功能1 选择赛车
   {2,1,3,0,0,6,(*Function2)},//功能2 选择贪吃蛇
   {3,2,0,0,0,7,(*Function3)},//功能3 选择俄罗斯方块
   {4,0,0,0,0,0,(*Function4)},//功能4 进入游戏上刀山
   {5,0,0,0,0,0,(*Function5)},//功能5 进入游戏赛车
   {6,0,0,0,0,0,(*Function6)},//功能5 进入游戏贪吃蛇
   {7,0,0,0,0,0,(*Function7)},//功能5 进入游戏俄罗斯方块
};

前面这些数字都是功能索引号, 比如当前在第零条(功能0)菜单中{0,3,1,0,0,4,(*Function0)},我有五个按键,上下左右中, 其中0代表执行此菜单中的 Function0();函数中的功能,3代表上键按下对应选中第三条菜单(功能3){3,2,0,0,0,7,(*Function3)}并执行Function3();函数中的功能,1代表下键按下对应选中第1条菜单{1,0,2,0,0,5,(*Function1)}并执行Function1();函数中的功能,0代表左键没用到指向功能0,还有一个0表示右键按下也没用到,最后一个4,代表选中功能4执行{4,0,0,0,0,0,(*Function4)},每条菜单,以此类推。

通过按键是怎么选中对应的菜单索引号,以及是如何执行其中的功能函数,且看

 if(UpKeyPress==0)
{
	UpKeyPress=1;Clear_Screen();
	KeyFunctionIndex=IndexTab[KeyFunctionIndex].UpKeyIndex; //查找按上键对应的功能索引
}
if(DownKeyPress==0)
{
	DownKeyPress=1;Clear_Screen();			   
        KeyFunctionIndex=IndexTab[KeyFunctionIndex].DownKeyIndex;
}
if(OkKeyPress==0)
{
	OkKeyPress=1;Clear_Screen();
	KeyFunctionIndex=IndexTab[KeyFunctionIndex].OkKeyIndex;
}			
KeyFunctionPtr=IndexTab[KeyFunctionIndex].CurrentFunction; //根据功能索引,执行当前功能
(*KeyFunctionPtr)();

下面是一些功能函数,就是你要实现的功能写在里面。

void Function0(void)
{
}
void Function1(void)
{
}
void Function2(void)
{
}
void Function3(void)
{
}
void Function4(void)
{
}
void Function5(void)
{
}
void Function6(void)
{
}
void Function7(void)
{
}

好了,一个完整的菜单程序代码就是这样的了。

 

版权声明:
作者:wawooo
链接:http://www.wawooo.com/345.html
来源:挖窝网
文章版权归作者所有,未经允许请勿转载。

THE END
分享
二维码
< <上一篇
下一篇>>