ArduinoLibs
 All Classes Files Functions Variables Typedefs Enumerations Enumerator Friends Groups Pages
Serial port Shell example

The Shell class provides a Unix-like shell for issuing commands to the Arduino. This example shows how to use Shell to provide command-line access via a serial port. The example has one command "led" for turning the status LED on D13 on and off.

We start by including the shell library definitions and declaring a variable of type Shell:

#include <Shell.h>
Shell shell;

Next we need to initialize the serial port and tell the shell object to use it for communications:

void setup()
{
pinMode(ledPin, OUTPUT);
Serial.begin(9600);
shell.setPrompt("Command: ");
shell.begin(Serial, 5);
}

The call to shell.setPrompt() specifies the prompt to display whenever a new line of input is required. The default value is "$ " but we have changed it to "Command: " in this example. The string can be anything and can be changed later if necessary.

The call to shell.begin() starts the actual shell. The first argument is the underlying stream to use for communications, the Serial port in our case. The second argument sets the size of the history stack so that Shell can remember previous commands and let the user navigate back to them with the up/down arrow keys.

The shell needs to regularly process input from the serial port and handle commands. We accomplish this by calling shell.loop() from the application's main loop() function:

void loop()
{
shell.loop();
}

At this point the application will have two builtin commands, "help" and "exit". But we also want a command of our own. We do this by declaring a command handler:

int ledPin = 13;
void cmdLed(Shell &shell, int argc, const ShellArguments &argv)
{
if (argc > 1 && !strcmp(argv[1], "on"))
digitalWrite(ledPin, HIGH);
else
digitalWrite(ledPin, LOW);
}
ShellCommand(led, "Turns the status LED on or off", cmdLed);

The ShellCommand() macro informs the shell of a new command with its name, help string, and the name of the handler function.

The full source code for the example follows:

/*
This example demonstrates how to create a simple shell on the serial port.
This example is placed into the public domain.
*/
#include <Shell.h>
Shell shell;
int ledPin = 13;
void cmdLed(Shell &shell, int argc, const ShellArguments &argv)
{
if (argc > 1 && !strcmp(argv[1], "on"))
digitalWrite(ledPin, HIGH);
else
digitalWrite(ledPin, LOW);
}
ShellCommand(led, "Turns the status LED on or off", cmdLed);
void setup()
{
pinMode(ledPin, OUTPUT);
Serial.begin(9600);
shell.setPrompt("Command: ");
shell.begin(Serial, 5);
}
void loop()
{
shell.loop();
}