An example for command processing

Hi all.
There are so many users who want to send commands and parameters to arduino,
and let it to do different jobs according to the commands and parameters.
I also used to think so.
I found the hint (,or the answer itself) to implement a command processor in this book on chapter 9.
I translated the sample codes into a sketch called ProcessCommans.
The code is here.

The form of the commands is;
"the name of the command", "integer parameter";
where ,' separates the parameter value from the command's name and ;' terminates the command.
The name of the command is case-insensitive.
Since the white spaces are ignored, we can add them in a command line.

At the moment, the following three commands are implemented.

  1. help
    prints the names of all the commands.

Arduino command processing example

help;
HELP
LED
BUZZER

  1. led
    changes the brightness of the LED which is hooked up to the digital port #11.
    Valid values of the parameter are 0 to 255.

led, 100;
LED command received.
parameter value is 100
led, 0x100;
LED command received.
parameter value is 256
wrong parameter value
led;
LED command received.
parameter value is 0

  1. buzzer
    is a dummy command, only prints the parameter value.

buzzer, -50;
BUZZER command received.
parameter value is -50

We can send a negative value as an parameter.

In the next post, I'll show you how to add a new command and its function.

Adding a new command is very easy task.
Let's add a new command "age" which determines if you are an adult or not.
The command form is
"age", "your age";

  1. Change the command table size 4 to 5.

#define COMMAND_TABLE_SIZE (5)

  1. Add a new command entry above the NULL entry in the gCommandTable struct.

command_t const gCommandTable[COMMAND_TABLE_SIZE] = {
{"HELP", commandsHelp,},
{"LED", commandsLed, },
{"BUZZER", commandsBuzzer, },
{"AGE", commandsAge, },
{NULL, NULL }
};

The commandsAge is a pointer to a function which is called by age command.

  1. Add the body of a function below the commandsHelp function body.

void commandsAge(void) {
int threshold = 18;
int maxage = 150;
if (gParamValue < 0) {
Serial.println("You are unborn.");
}else if (gParamValue >=0 && gParamValue < threshold) {
Serial.println("You are not an adult.");
}else if (gParamValue >= threshold && gParamValue < maxage) {
Serial.println("You are an adult");
}else {
Serial.println("You are probably dead.");
}
}

We can access the parameter value as gParamValue variable which is already converted to long integer value.
The task is finished. Compile and upload it.

  1. Open the SerialMonitor and let's test the new command.

Arduino command processing example

help;
HELP
LED
BUZZER
AGE
age, 15;
You are not an adult.
age, 40;
You are an adult
age, -4;
You are unborn.
age, 600;
You are probably dead.

Ok, it works.