Command Parser for Arduino

This is day zero of my Month Of Writing

Controlling an Arduino project over a serial connection is one of the most common tasks you might want to do, and yet it's surprisingly hard to find a good library. I really don't like the official ones because they are limited and require too much setup. After much googling with Bing I found one called *CmdArduino* by Akiba at Freaklabs.

CmdArduino does exactly what I want, minus a few tweaks. I emailed Akiba about it. Even though he had never done an update to the library in three years he responded right away. I asked if I could take over the lib and he said yes! So I'm now the official maintainer for CmdArduino. For my first release I've added Stream support so it will work with more than just the regular Serial port; very important for working with alternative streams like Bluetooth LE modules.

CmdArduino is super easy to use. Create your command functions with a signature like:

void left(int arg_cnt, char **args)

Then register it like this:

cmdInit(&MyStream);
cmdAdd('left',left);

Now the `left` function will be called whenever you type 'left' into the other end of the stream. If you add arguments after the command they will show up in the `args` array. At OSCON I build a robot controlled by a chat app on my phone over BLE. When I typed in `spin 3000` the robot's spin function would be called with the value 3000 for the duration. The code looks like this:

void spin(int arg_cnt, char **args) {
    int time = 1000;
    if(arg_cnt > 0) {
        time = parseInt(args[0]);
    }
    LeftMotor->run(BACKWARD);
    RightMotor->run(FORWARD);
    delay(time);
    RightMotor->run(RELEASE);
    LeftMotor->run(RELEASE);
}

void setup() {
    Serial.begin(9600);
    cmdInit(&ble);
    cmdAdd('spin',spin);
}

It's that easy. The code is up in my github repo now.

https://github.com/joshmarinacci/CmdArduino

Thanks Akiba!

Talk to me about it on Twitter

Posted July 31st, 2014

Tagged: arduino github