In the previous example, we mentioned that aside from int
, there are also float
and string
(char*) argument types.
- The
float
type works just like int
—nothing complicated there.
- The
string
type, however, requires a little extra care because we need a buffer to store the parsed text.
Here’s how to handle it:
char stringBuffer[30];
Argument stringArg(args, 0);
if (!stringArg.parseString(stringBuffer)) {
caller->print("Argument error! A string is required!");
return false;
}
If parseString()
returns true
, that means:
- The argument was successfully parsed.
- The string fits in the buffer.
If it fails, the buffer might be too small, or the provided argument isn't a valid string.
This approach ensures that string arguments are safely stored and processed!
Live Demo
Quick Tip for Using String Arguments
Here’s a quick tip for handling string arguments as a user:
If you try the command:
The result will be:
But if you run:
You’ll still get:
Why? Because by default, command-line arguments are separated by spaces.
If your string contains spaces, you need to enclose it in quotation marks, just like in the C programming language.
For example:
This will correctly return:
This small trick helps ensure your full string argument is passed correctly!
Whole Code
#include "Commander-API.hpp"
#include "Commander-Arguments.hpp"
Commander commander;
bool upper_func( char *args, CommandCaller* caller );
bool area_func( char *args, CommandCaller* caller );
Commander::systemCommand_t API_tree[] = {
systemCommand( "upper", "Replaces all characters in a string to upper-case.", upper_func ),
systemCommand( "area", "Calculates the volume of two float numbers", area_func ),
};
void setup(){
Serial.begin(115200);
shell.clear();
commander.attachDebugChannel( &Serial );
commander.attachTree( API_tree );
commander.init();
shell.attachCommander( &commander );
shell.begin( "arnold" );
}
void loop(){
shell.update();
}
bool upper_func(char *args, CommandCaller* caller ){
char stringBuffer[ 30 ];
int i;
Argument stringArg( args, 0 );
if( !stringArg.parseString( stringBuffer ) ){
caller -> print( "Argument error! A string is required!" );
return false;
}
for( i = 0; i < strlen( stringBuffer ); i++ ){
stringBuffer[ i ] = toupper( stringBuffer[ i ] );
}
caller -> print( "Upper case string: " );
caller -> println( stringBuffer );
return true;
}
bool area_func(char *args, CommandCaller* caller ){
float area;
Argument a( args, 0 );
Argument b( args, 1 );
if( !( a.parseFloat() && b.parseFloat() ) ){
caller -> print( "Argument error! Two float numbers are required, separated with a blank space.\r\n" );
return false;
}
area = (float)a * (float)b;
caller -> print( (float)a );
caller -> print( " * " );
caller -> print( (float)b );
caller -> print( " = " );
caller -> println( area );
return true;
}