TV remote: a table of key actions
Look a key code up in a table and call its action with the device's context. A medium embedded C problem (Function pointers and state machines), run and…
medium · Function pointers and state machines · function-pointers · dispatch-table · context · product
Product: TV remote control (Consumer electronics)
Requirement. The same remote firmware ships with different key layouts for TVs and soundbars, so each model is a table of {key code, action} pairs rather than a long switch.
Find the entry for code in the first n entries of table and call its action with ctx. Return true if an action ran. Return false, doing nothing, if no entry has that code or its action is NULL (a key that exists on the case but does nothing on this model). Key codes are arbitrary numbers, not positions in the table.
Starter code
bool remote_dispatch(const key_entry_t *table, size_t n, uint8_t code, void *ctx) {
table[code].fn(ctx);
return true;
}Example tests
Volume up twice, channel up once
key_entry_t keys[] = { { 0x10, vol_up }, { 0x11, ch_up }, { 0x20, mute } };
tv_t tv = { 5, 1 };
remote_dispatch(keys, 3, 0x10, &tv);
remote_dispatch(keys, 3, 0x10, &tv);
remote_dispatch(keys, 3, 0x11, &tv);
printf("%d %d\n", tv.volume, tv.channel);Expected output:
7 2A key this model does not have
key_entry_t keys[] = { { 0x10, vol_up }, { 0x11, ch_up }, { 0x20, mute } };
tv_t tv = { 5, 1 };
int r = remote_dispatch(keys, 3, 0x55, &tv);
printf("%d %d %d\n", r, tv.volume, tv.channel);Expected output:
0 5 1Learn it first
- Function pointers and callbacks · Callbacks, dispatch tables and the context pointer that makes them reusable.
More Function pointers and state machines problems
- Dispatch through a vector table · Call the handler registered for an interrupt number, with a safe fallback.
- Replace a switch with a table · Select an operation by opcode using an array of function pointers.
- Apply a function to a buffer · Transform every element of an array with a caller-supplied function.
- Command table lookup · Find a command by name in a table and call its handler.
- Sort with a comparator · Sort an array into an order defined by a callback.
- State transition function · Implement the transition rules of a motor controller.
- Publish and subscribe · Keep a fixed-size list of callbacks and notify them in order.
- Callback with context · Invoke a callback for every set bit, passing through a user context.
- Generic minimum · Find the smallest element of an array of any type using a comparator.
- State handlers · Build a state machine in which each state is a function.