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?

Example:

Here is the protocol (commands) using only a 4 x 4 - 16 button keypad:

XX@HH:MM#

Where:

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)
B
= NOT USED
D
= NOT USED
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:

switch(state) {
   case INITIAL:
     // process INITIAL state  
   break;
   case STATE1:
     // process STATE1 state       
   break;
   case CLEAR:
     clearAll();
     state = INITIAL;
   break;
   default:
   break;
} 

Let's now apply this logic to your project.

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

It's as simple as that!

Source Code:

The complete working example is available here.

Working Demo: 

Watch my video here

Future Enhancements / Ideas:

Questions?

If you have any questions please feel free to ask.

I hope this article is helpful and useful to someone interested in validating keypad input using state machine programming. Feel free to use this code and example to validate you next project using a keypad for input command.

The original blog appeared here.

Thanks,
Tony