When exploring a new codebase, it’s a great luxury to also reference it in running form, a luxury I have with the Hackaday badge code project and a physical badge on hand to see it run. What’s the first point of interaction with running code? The main menu! So that’s where I decided to start looking at details of the code.
main() function, the main menu is handled by function
badge_menu() in file
badge.c. The first thing it calls is
showmenu() in the same file which draws everything visible onscreen for the main menu. Including title bar, screen border, menu entries, and the user input prompt. This is a great reference for writing code to output text on screen.
Most of the code in
badge_menu() reads user key presses and builds up the typed command in
menu_buff. Upon pressing
ENTER, the command is checked against the list of known commands. This is a chunk of code that can easily be recycled for processing user text input.
When a user enters a command that’s none of the recognized list items, the badge selects one of a set of error messages at random. This pseudo-random number is seeded with the standard
srand() call using a PIC chip’s timer counter value at the time of user’s first key press. Seeding with a time value is common practice, but usually done with a real-time clock on the assumption that the current time is unpredictable. Here, the unpredictability comes from the amount of time a human user would take before pushing their first key after powerup, every person has a slightly different reaction time.
When an user command is recognized,
badge_menu() calls into corresponding code to make things happen. The menu entries are straightforward, but there are a series of “easter egg” behavior. Rather than a direct string comparison, which spoils the surprise by embedding the secret code in source code, the responses are actually keyed against a hash of the string.