Keypad Input Validation using State Machine Programming

The Problem:

You have a project that accepts commands using a 16 button keypad and want to perform validation on the commands as each character is typed.  But how?
Here is the sample or typical protocol (commands) using only a 4 x 4 – 16 button keypad:
XX is a value from 1-99
HH:MM is a time format (24 hr clock or military time)
Alpha-Numeric Key Mappings:
A = @ (at sign)
C = Clear
* = : (colon)
# = Execute (accept or enter or execute) the command

The Solution:

Use state machine logic / programming to solve the problem.

Introduction to State Machine Logic / Programming

If you aren’t familiar with or haven’t used state machine logic in programming, it is the easiest way to to break complex problems into manageable states and state transitions especially for handling serial input.
One of the easiest ways to implement a state machine is to use a switch statement.  In my opinion it is the only way to implement serial input commands.
Example of a state machine using a switch statement:

Let’s now apply this logic to your project.

Here is a step by step approach to solve the problem:

  • Break the commands into states.
    • The easiest way is to consider each character in the command as a state.
    • Given the command:  XX@HH:MM#
      • Here are suggested state names:
        • VALUE1 – First digit of value
        • VALUE2 – Second digit of value
        • ATSIGN – At sign (@)
        • HOUR1 – First digit of hour
        • HOUR2 – Second digit of hour
        • COLON – Colon (:)
        • MIN1 – First digit of minute
        • MIN2 – Second digit of minute
        • EXECUTE – Pound sign (#)
      • Then create an additional state called INITIAL
  •  Create a list or table of all the combinations within a command or commands.
    • Given the command: XX@HH:MM#
      • All combinations of the command:
        • XX@HH:MM# (45@12:45#)
        • XX@HH:MM# (45@1:26#)
        • X@HH:MM# (9@12:45#)
        • X@H:MM# (9@1:26#)
  • Determine all ranges for values
    • XX has a range 1 to 99 but 01-09 is also valid
    • HH has a range of 0-24 but 00-09 is also valid
    • MM has a range of 00-59
    • Start with a table or spreadsheet with all the states entered:
      Create a state diagram.
    • For each state determine what keys are valid and the next state.
    • INITIAL is the first digit of the value so valid keys are 0-9
    • VALUE1 can be the second digit of the value or the at sign (@)
    • Continue until you have completed all the valid key and next state.

Read More: Keypad Input Validation using State Machine Programming

Leave a Comment

Your email address will not be published. Required fields are marked *