Support » Jrk G2 Motor Controller User’s Guide » 15. Writing PC software to control the Jrk »
15.10. Example I²C code for MicroPython
The example code below uses the machine.I2C
class in MicroPython to send and receive data from a Jrk G2 via I²C. It demonstrates how to set the target of the Jrk by sending a “Set target” command and how to read variables using a “Get variables” command. This example is designed to run on the Raspberry Pi Pico and can be ported to other boards by changing the line at the top that sets up the i2c
object.
from machine import I2C, Pin i2c = I2C(0, sda=Pin(8), scl=Pin(9), freq=400000) class JrkG2I2C(object): def __init__(self, address): self.address = address # Sets the target. For more information about what this command does, # see the "Set Target" command in the "Command reference" section of # the Jrk G2 user's guide. def set_target(self, target): command = [0xC0 + (target & 0x1F), (target >> 5) & 0x7F] i2c.writeto(self.address, bytes(command)) # Gets one or more variables from the Jrk (without clearing them). # Returns a bytes object. def get_variables(self, offset, length): i2c.writeto(self.address, bytes([0xE5, offset])) return i2c.readfrom(self.address, length) # Gets the Target variable from the Jrk. def get_target(self): b = self.get_variables(0x02, 2) return b[0] + 256 * b[1] # Gets the Feedback variable from the Jrk. def get_feedback(self): b = self.get_variables(0x04, 2) return b[0] + 256 * b[1] # Select the I2C address of the Jrk (the device number). address = 11 jrk = JrkG2I2C(address) feedback = jrk.get_feedback() print("Feedback is {}.".format(feedback)) target = jrk.get_target() print("Target is {}.".format(target)) new_target = 2248 if target < 2048 else 1848 print("Setting target to {}.".format(new_target)) jrk.set_target(new_target)