Support » Pololu Simple Motor Controller G2 User’s Guide » 8. Example code »
8.1. Example code to run smcg2cmd in C
The example C code below shows how to invoke the Simple Motor Controller G2 Command-line Utility (smcg2cmd) to control a Simple Motor Controller G2 via USB.
If you have multiple Simple Motor Controller G2 devices connected to your computer via USB, you will need to use the -d
option to specify the serial number of the device you want to use. For example, to set the speed to 2400 on a Simple Motor Controller G2 with serial number 0012-3456-789A-BCDE-F012-3456, you can run the command smcg2cmd -d 0012-3456-789A-BCDE-F012-3456 --resume --speed 2400
. You can run smcg2cmd --list
in a shell to get the serial numbers of all the connected Simple Motor Controller G2 devices.
In the example below, the child smcg2cmd process uses the same error pipe as the parent example program, so you will see any error messages printed by smcg2cmd if you run the example program in a terminal.
// Uses smcg2cmd to set the target speed of the Simple Motor Controlelr G2 // over USB. // // NOTE: The SMC G2's input mode must be "Serial / USB". #include <stdint.h> #include <stdio.h> #include <stdlib.h> // Runs the given shell command. Returns 0 on success, -1 on failure. int run_command(const char * command) { int result = system(command); if (result) { fprintf(stderr, "Command failed with code %d: %s\n", result, command); return -1; } return 0; } // Sends the "Exit safe start" command and also sets the target speed. // Returns 0 on success and -1 on failure. int smc_set_target_speed(int16_t speed) { char command[1024]; snprintf(command, sizeof(command), "smcg2cmd --resume --speed %d", speed); return run_command(command); } int main() { printf("Setting target speed to 2400.\n"); int result = smc_set_target_speed(2400); if (result) { return 1; } return 0; }