As we grow in our engineering careers, we must continually add new tools to our collective tool kits. One favorite tool in my toolkit will be obvious to many experienced embedded software engineers. I still remember learning this approach early in my career via code written by colleague David Starling. The tool in question:
Look up tables
Look up tables simplify code and improve firmware maintenance. What is a look up table? A look up table is often nothing more complex than a constant statically defined array of information. It could be a dynamic std::map data structure created during program initialization or other container as appropriate. The table elements often consist of data structures defining behavior, translating between types, or providing access to additional metadata. Let’s dive into an example.
A device consists of a keypad with buttons that must initiate actions in the firmware. Perhaps the product specification requires some keys to behave with a discrete one time action while other keys must exhibit a repeating behavior. Among the repeating keys some should repeat at different rates. Using a look up table, example code implementing these requirements might appear as:
Key points to notice in the above example:
- Business logic is now trivial to modify. Maybe the product decides that volume up and volume down should repeat at different rates. Just change the values in the table.
- A new key is added to the hardware? Add a new row to the table.
- The table provides a nice location for metadata, such as debug friendly strings for each key.
There are many other ways to use look up tables in our embedded software. If code consists of a long series of if()/else if() blocks or an extensive switch() statement, a look up table might be appropriate. Other examples include:
- Mapping enumerated types to metadata. Examples:
- Debug strings
- Hardware register addresses or offsets
- Extracting business logic/parameters into a single easy to read table/location
- Simple state machines
- e.g. Map a state enumerated value to various callback function handlers for the state.
- Internationalization of user interface strings
Look up tables are a handy tool to add to our collective toolkit, simplifying code and improving maintenance. Where have you found a look up table useful in your embedded software?
Note: This post was originally published here https://www.embeddedrelated.com/showarticle/1009.php