12.10. Example I²C code for MicroPython

The example Python code below uses the machine.I2C class in MicroPython to send and receive data from a Tic via I²C. It demonstrates how to set the target position of the Tic and how to read variables from it. 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 TicI2C(object):
  def __init__(self, address):
    self.address = address

  # Sends the "Exit safe start" command.
  def exit_safe_start(self):
    command = [0x83]
    i2c.writeto(self.address, bytes(command))

  # Sets the target position.
  #
  # For more information about what this command does, see the
  # "Set target position" command in the "Command reference" section of the
  # Tic user's guide.
  def set_target_position(self, target):
    command = [0xE0,
        target >> 0 & 0xFF,
        target >> 8 & 0xFF,
        target >> 16 & 0xFF,
        target >> 24 & 0xFF]
    i2c.writeto(self.address, bytes(command))
    
  # Gets one or more variables from the Tic.
  def get_variables(self, offset, length):
    i2c.writeto(self.address, bytes([0xA1, offset]))
    return i2c.readfrom(self.address, length)
 
  def get_current_position(self):
    b = self.get_variables(0x22, 4)
    position = b[0] + (b[1] << 8) + (b[2] << 16) + (b[3] << 24)
    if position >= (1 << 31):
      position -= (1 << 32)
    return position 


# Select the I2C address of the Tic (the device number).
address = 14
 
tic = TicI2C(address)
 
position = tic.get_current_position()
print("Current position is {}.".format(position))
 
new_target = -200 if position > 0 else 200
print("Setting target position to {}.".format(new_target));
tic.exit_safe_start()
tic.set_target_position(new_target)

Related Products

Tic T825 USB Multi-Interface Stepper Motor Controller (Connectors Soldered)
Tic T825 USB Multi-Interface Stepper Motor Controller
Tic T834 USB Multi-Interface Stepper Motor Controller (Connectors Soldered)
Tic T834 USB Multi-Interface Stepper Motor Controller
Tic T500 USB Multi-Interface Stepper Motor Controller (Connectors Soldered)
Tic T500 USB Multi-Interface Stepper Motor Controller
Tic T249 USB Multi-Interface Stepper Motor Controller (Connectors Soldered)
Tic T249 USB Multi-Interface Stepper Motor Controller
Tic 36v4 USB Multi-Interface High-Power Stepper Motor Controller (Connectors Soldered)
Tic 36v4 USB Multi-Interface High-Power Stepper Motor Controller

Related Categories

Tic Stepper Motor Controllers
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