6.7.5. Bash Script Example

The Bash shell script below works on Linux and Mac OS X 10.7 or later. It demonstrates how to control a Simple Motor Controller over USB. You can run it using the example commands given below. You will need to change the DEVICE argument to be the name of the Simple Motor Controller’s virtual serial port (see Section 6).

For this script to work, the Simple Motor Controller’s input mode must be Serial/USB, the serial mode must be Binary, and the CRC Mode must be set to Disabled. These are the default settings that the controller is shipped with. The controller should be connected to the computer via USB.

#!/bin/bash
# Sets the speed of a Simple Motor Controller via its virtual serial port.
# Usage: smc-set-speed.sh DEVICE SPEED
# Linux example: bash smc-set-speed.sh /dev/ttyACM0 3200
# Mac OS X example: bash smc-set-speed.sh /dev/cu.usbmodemfa121 3200
# Windows example: bash smc-set-speed.sh '\\.\USBSER000' 3200
# Windows example: bash smc-set-speed.sh '\\.\COM6' 3200
# DEVICE is the name of the virtual COM port device.
# SPEED is a number between -3200 and 3200
DEVICE=$1
SPEED=$2

byte() {
  printf "\\x$(printf "%x" $1)"
}

{
  byte 0x83  # exit safe-start
  if [ $SPEED -lt 0 ]; then
    byte 0x86  # motor reverse
    SPEED=$((-$SPEED))
  else
    byte 0x85  # motor forward
  fi
  byte $((SPEED & 0x1F))
  byte $((SPEED >> 5 & 0x7F))
} > $DEVICE

This script can also be run on Windows, but since Windows does not have bash installed by default it is easier to use SmcCmd.