This is a small part of the article series titled "C Language Embedded System Programming Practice," which I wrote as a graduate student 13 years ago. It demonstrates an object-oriented approach to implementing an LCD menu system in C.
  The menu operation was the result of countless brainstorming sessions. In this article, we'll see how even a little object-oriented thinking in C can completely transform the software structure! I used to be a programming beginner who got stuck on menu systems, creating messy code like this:
The system required switching the menu focus using the "↠→" keys on the keyboard. When a user selected a menu item, pressing the OK or CANCEL key would trigger the corresponding function. Back then, I handled it in a very inefficient way:
/* Press the OK button */void onOkKey(){ /* determine which menu is focused and call the handler function */ Switch(currentFocus) { case MENU1: menu1OnOk(); break; case MENU2: menu2OnOk (); break; ... }}/* Press the Cancel button */void onCancelKey(){ /* determine which menu is focused and call the handler function */ Switch(currentFocus) { case MENU1: menu1OnCancel( ); break; case MENU2: menu2OnCancel(); break; ... }} |
But one day, I decided to rethink the whole approach.
/* Combine the menu's properties and operations into a single structure */typedef struct tagSysMenu{ char *text; /* menu text */ BYTE xPos; /* x position on LCD */ BYTE yPos; /* y position on LCD*/ void (*onOkFun)(); /* function pointer for OK press */ void (*onCancelFun)(); /* function pointer for CANCEL press */}SysMenu, *LPSysMenu; |
By defining a menu, I just needed to do this:
Static SysMenu menu[MENU_NUM] ={ { "menu1", 0, 48, menu1OnOk, menu1OnCancel } , { " menu2", 7, 48, menu2OnOk, menu2OnCancel } , { " menu3", 7, 48, menu3OnOk, menu3OnCancel } , { " menu4", 7, 48, menu4OnOk, menu4OnCancel } ...}; |
Then, the processing of OK and CANCEL became much simpler:
/* Press OK */void onOkKey(){ menu[currentFocusMenu].onOkFun(); }/* Press Cancel */void onCancelKey(){ menu[currentFocusMenu].onCancelFun(); |
This made the program significantly cleaner and more scalable. By applying basic encapsulation from object-oriented design, the code became easier to manage. Now, adding new menus to the system requires minimal changes, and the core key handling functions remain untouched. Object-oriented design truly makes a difference!
Embed Barcode Module,Mini Auto-Scanning Module ,Auto-Scanning Module ,2D Scanner Barcode
Guangzhou Winson Information Technology Co., Ltd. , https://www.barcodescanner-2d.com