8.9. Example serial code for Linux or macOS in Bash

The Bash shell script below works on Linux and macOS. It demonstrates how to control a Simple Motor Controller G2 using its USB virtual serial port.

For this script to work, the Simple Motor Controller G2’s input mode must be Serial/USB, the serial mode must be Binary, and CRC must be 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
# macOS example: bash smc-set-speed.sh /dev/cu.usbmodemfa121 3200
# Cygwin example: bash smc-set-speed.sh '/dev/ttyS16' 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

Related Products

High-Power Simple Motor Controller G2 18v15 (Connectors Soldered)
High-Power Simple Motor Controller G2 18v15
High-Power Simple Motor Controller G2 24v12 (Connectors Soldered)
High-Power Simple Motor Controller G2 24v12
High-Power Simple Motor Controller G2 18v25
High-Power Simple Motor Controller G2 24v19
Log In
Pololu Robotics & Electronics
Shopping cart
(702) 262-6648
Same-day shipping, worldwide
Menu
Shop Blog Forum Support
My account Comments or questions? About Pololu Contact Ordering information Distributors