Support » Pololu Simple Motor Controller G2 User’s Guide » 8. Example code »
8.2. Example code to run smcg2cmd in Python
The example Python code below shows how to invoke the Simple Motor Controller G2 Command-line Utility (smcg2cmd) to send and receive data from a Simple Motor Controller G2 via USB. It demonstrates how to set the target speed of the controller using the --speed
option and how to read variables using the -s
option. This code works with either Python 2 or Python 3.
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 Python process, so you will see any error messages printed by smcg2cmd if you run the Python program in a terminal. Additionally, if there is an error, Python’s subprocess.check_output
method will detect it (by checking the smcg2cmd process exit status) and raise an exception.
# Uses smcg2cmd to control a Simple Motor Controller G2 over USB. # Works with either Python 2 or Python 3. # # NOTE: The Simple Motor Controller's input mode must be "Serial / USB". import subprocess import re def smcg2cmd(*args): return subprocess.check_output(['smcg2cmd'] + list(args)) def get_target_speed_from_status(status): e = re.compile('^Target Speed:\s*(-?\d+)\s*\r$', re.IGNORECASE | re.MULTILINE) r = e.search(status) if r is None: raise RuntimeError('Failed to parse status') return int(r.group(1)) status = smcg2cmd('-s').decode() target_speed = get_target_speed_from_status(status) print("Target speed is {}.".format(target_speed)) new_speed = 3200 if target_speed <= 0 else -3200 print("Setting target speed to {}.".format(new_speed)) smcg2cmd('--resume', '--speed', str(new_speed))