Polo-BOO! Halloween Sale going on now – click for details!

15.2. Example code to run jrk2cmd in Ruby

The example Ruby code below shows how to invoke the Jrk G2 Command-line Utility (jrk2cmd) to send and receive data from a Jrk G2 via USB. It demonstrates how to set the target of the Jrk using the --target option and how to read variables using the -s option. This code uses the YAML parser that comes with Ruby to parse the output of jrk2cmd when reading data from the Jrk. This code should work on any system with jrk2cmd and Ruby.

If you have multiple Jrk 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 get the status of the Jrk G2 with serial number 00123456, you can run the Ruby code jrk2cmd('-d', '00123456', '-s', '--full'). You can run jrk2cmd --list in a shell to get the serial numbers of all the connected Jrk G2 devices.

In the example below, the child jrk2cmd process uses the same error pipe as the Ruby process, so you will see any error messages printed by jrk2cmd if you run the Ruby program in a terminal. If you want to instead capture the standard error output so that you can use it in your Ruby program, you can change the code to use Ruby’s Open3.capture3 method.

# Uses jrk2cmd to send and receive data from the Jrk G2 over USB.
#
# NOTE: The Jrk's input mode must be "Serial / I2C / USB".

require 'open3'
require 'yaml'

def jrk2cmd(*args)
  command = 'jrk2cmd ' + args.join(' ')
  stdout, process_status = Open3.capture2(command)
  if !process_status.success?
    raise "Command failed with code #{process_status.exitstatus}: #{command}"
  end
  stdout
end

status = YAML.load(jrk2cmd('-s', '--full'))

feedback = status.fetch('Feedback')
puts "Feedback is #{feedback}."

target = status.fetch('Target')
puts "Target is #{target}."

new_target = target < 2048 ? 2248 : 1848
puts "Setting target to #{new_target}."
jrk2cmd('--target', new_target)

Related Products

Jrk G2 18v19 USB Motor Controller with Feedback
Jrk G2 24v13 USB Motor Controller with Feedback
Jrk G2 18v27 USB Motor Controller with Feedback
Jrk G2 24v21 USB Motor Controller with Feedback
Jrk G2 21v3 USB Motor Controller with Feedback
Jrk G2 21v3 USB Motor Controller with Feedback (Connectors Soldered)
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