Electronic – Standard text LCD menu system

clcd

Is there a pattern out there for a simple menu system in C for a text LCD. I find myself re-writing code a lot for handling simple text LCD menus.

I find most systems have a main menu and some sub-menus that when selected allow you to set a parameter with within some minimum and maximum value.

Ideally this menu system could be navigated with 4 simple keys such as enter, cancel, up, and down.

In my application I'm using a 2 line x 16 character text LCD though an ideal solution should be able to be applied to any NxM display.

Best Answer

The pattern I use for menu systems in C is something like this:

struct menuitem
{
  const char *name; // name to be rendered
  functionPointer handlerFunc; // handler for this leaf node (optionally NULL)
  struct menu *child; // pointer to child submenu (optionally NULL)
};

struct menu
{
  struct menu *parent; // pointer to parent menu
  struct **menuitem; // array of menu items, NULL terminated
};

I then declare an array of menus each containing menuitems and pointers to child submenus. Up and down moves through the currently selected array of menuitems. Back moves to the parent menu and forward/select either moves to a child submenu or calls a handlerFunc for a leaf node.

Rendering a menu just involves iterating through its items.

The advantage of this scheme is that it's fully data driven, the menu structures can be statically declared in ROM independent of the renderer and handler functions.