Motor Component

Electric motors are machines that convert electricity into rotary motion. They are the most common form of actuator in robotics. The motor component type natively supports brushed DC motors, brushless DC motors, and stepper motors controlled by a variety of motor drivers.

Most machines with a motor need at least the following hardware:

  • The motor itself.
  • A compatible motor driver. This takes signals from the computer and sends the corresponding signals and power to the motor. Selected based on the type of motor (for example, brushed, brushless, or stepper) and its power requirements.
  • A board component to send signals to the motor driver1. For example, a Raspberry Pi, or another model of single-board computer with GPIO (general purpose input/output) pins.

Supported models

To use your motor with Viam, check whether one of the following built-in models or modular resources supports your motor.

Built-in models

For configuration information, click on the model name:

ModelDescription
gpioStandard brushed or brushless DC motor
gpiostepperBipolar stepper motor with current regulation and 1/32 microstepping driven by a basic driver like DRV8825 or TMC2209
28byj48Small unipolar 28BYJ-48 stepper motor driven by a ULN2003 driver
TMC5072Stepper motor driven by the TMC5072 chip
DMC4000Stepper motor driven by a DMC-40x0 series motion controller
roboclawStandard brushed DC motor driven by Basicmicro’s RoboClaw motor controller
fakeUsed to test code without hardware

Modular resources

Search for additional motor models that you can add from the Viam Registry:

For configuration information, click on the model name:

Model
Description

Micro-RDK

If you are using the micro-RDK, navigate to Micro-RDK Motor for supported model information.

Control your motor with Viam’s client SDK libraries

To get started using Viam’s SDKs to connect to and control your machine, go to your machine’s page on the Viam app, navigate to the CONNECT tab’s Code sample page, select your preferred programming language, and copy the sample code generated.

When executed, this sample code will create a connection to your machine as a client. Then control your machine programmatically by adding API method calls as shown in the following examples.

These examples assume you have a motor called "my_motor" configured as a component of your machine. If your motor has a different name, change the name in the code.

Be sure to import the motor package for the SDK you are using:

from viam.components.motor import Motor
import (
  "go.viam.com/rdk/components/motor"
)

API

The motor component supports the following methods:

Method NameDescription
SetPowerSet the power to send to the motor as a portion of max power.
GoForSpin the motor the specified number of revolutions at specified RPM.
GoToSend the motor to a specified position (in terms of revolutions from home) at a specified speed.
ResetZeroPositionSet the current position to be the new zero (home) position.
GetPositionReport the position of the motor based on its encoder. Not supported on all motors.
GetPropertiesReturn whether or not the motor supports certain optional features.
IsPoweredReturn whether or not the motor is currently on, and the amount of power to it.
IsMovingReturn whether the motor is moving or not.
StopCut power to the motor off immediately, without any gradual step down.
GetGeometriesGet all the geometries associated with the motor in its current configuration, in the frame of the motor.
DoCommandSend or receive model-specific commands.
CloseSafely shut down the resource and prevent further use.

SetPower

Sets the portion of max power to send to the motor (between -1 and 1). 1 is 100% power forwards; -1 is 100% power backwards.

Power is expressed as a floating point between -1 and 1 that scales between -100% and 100% power.

Parameters:

  • power (float): Portion of full power to send to the motor expressed as a floating point between -1 and 1. 1 is 100% power forwards; -1 is 100% power backwards.

Returns:

  • None

For more information, see the Python SDK Docs.

my_motor = Motor.from_robot(robot=robot, name="my_motor")

# Set the power to 40% forwards.
await my_motor.set_power(power=0.4)

Parameters:

  • ctx (Context): A Context carries a deadline, a cancellation signal, and other values across API boundaries.
  • powerPct (float64): Portion of full power to send to the motor expressed as a floating point between -1 and 1. 1 is 100% power forwards; -1 is 100% power backwards.
  • extra (map[string]interface{}): Extra options to pass to the underlying RPC call.

Returns:

  • (error): An error, if one occurred.

For more information, see the Go SDK docs.

myMotor, err := motor.FromRobot(robot, "my_motor")

// Set the motor power to 40% forwards.
myMotor.SetPower(context.Background(), 0.4, nil)

GoFor

Spins the motor the specified number of revolutions at specified revolutions per minute. When rpm or revolutions is a negative value, the motor spins in the backward direction. If both rpm and revolutions are negative, the motor spins in the forward direction.

Parameters:

  • rpm (float): Speed at which the motor should move in revolutions per minute (negative implies backwards).
  • revolutions (float): Number of revolutions the motor should run for (negative implies backwards).

Returns:

  • None

For more information, see the Python SDK Docs.

my_motor = Motor.from_robot(robot=robot, name="my_motor")

# Turn the motor 7.2 revolutions at 60 RPM.
await my_motor.go_for(rpm=60, revolutions=7.2)

Parameters:

  • ctx (Context): A Context carries a deadline, a cancellation signal, and other values across API boundaries.
  • rpm (float64): Speed at which the motor should move in revolutions per minute (negative implies backwards).
  • revolutions (float64): Number of revolutions the motor should run for (negative implies backwards). If revolutions is 0, this runs the motor at rpm indefinitely. If revolutions != 0, this blocks until the number of revolutions has been completed or another operation comes in.
  • extra (map[string]interface{}): Extra options to pass to the underlying RPC call.

Returns:

  • (error): An error, if one occurred.

For more information, see the Go SDK docs.

myMotor, err := motor.FromRobot(robot, "my_motor")

// Turn the motor 7.2 revolutions at 60 RPM.
myMotor.GoFor(context.Background(), 60, 7.2, nil)

GoTo

Turns the motor to a specified position (in terms of revolutions from home/zero) at a specified speed in revolutions per minute (RPM). Regardless of the directionality of the rpm, the motor will move towards the specified target position. This blocks until the position has been reached.

Parameters:

  • rpm (float): Speed at which the motor should move in revolutions per minute (absolute value).
  • position_revolutions (float): Target position relative to home/zero, in revolutions.

Returns:

  • None

For more information, see the Python SDK Docs.

my_motor = Motor.from_robot(robot=robot, name="my_motor")

# Turn the motor to 8.3 revolutions from home at 75 RPM.
await my_motor.go_to(rpm=75, revolutions=8.3)

Parameters:

  • ctx (Context): A Context carries a deadline, a cancellation signal, and other values across API boundaries.
  • rpm (float64): Speed at which the motor should move in revolutions per minute (absolute value).
  • positionRevolutions (float64): Target position relative to home/zero, in revolutions.
  • extra (map[string]interface{}): Extra options to pass to the underlying RPC call.

Returns:

  • (error): An error, if one occurred.

For more information, see the Go SDK docs.

myMotor, err := motor.FromRobot(robot, "my_motor")

// Turn the motor to 8.3 revolutions from home at 75 RPM.
myMotor.GoTo(context.Background(), 75, 8.3, nil)

ResetZeroPosition

Set the current position (modified by offset) to be the new zero (home) position.

Parameters:

  • offset (float): The offset from the current position to the new home (zero) position.

Returns:

  • None

For more information, see the Python SDK Docs.

my_motor = Motor.from_robot(robot=robot, name="my_motor")

# Set the current position as the new home position with no offset.
await my_motor.reset_zero_position(offset=0.0)

Parameters:

  • ctx (Context): A Context carries a deadline, a cancellation signal, and other values across API boundaries.
  • offset (float64): The offset from the current position to the new home (zero) position.
  • extra (map[string]interface{}): Extra options to pass to the underlying RPC call.

Returns:

  • (error): An error, if one occurred.

For more information, see the Go SDK docs.

myMotor, err := motor.FromRobot(robot, "my_motor")

// Set the current position as the new home position with no offset.
myMotor.ResetZeroPosition(context.Background(), 0.0, nil)

GetPosition

Report the position of the motor based on its encoder. The value returned is the number of revolutions relative to its zero position. This method raises an exception if position reporting is not supported by the motor.

Parameters:

  • None

Returns:

  • (float) Number of revolutions the motor is away from zero/home.

For more information, see the Python SDK Docs.

my_motor = Motor.from_robot(robot=robot, name="my_motor")

# Get the current position of the motor.
position = await my_motor.get_position()

Parameters:

  • ctx (Context): A Context carries a deadline, a cancellation signal, and other values across API boundaries.
  • extra (map[string]interface{}): Extra options to pass to the underlying RPC call.

Returns:

  • (float64): The unit returned is the number of revolutions which is intended to be fed back into calls of GoFor.
  • (error): An error, if one occurred.

For more information, see the Go SDK docs.

myMotor, err := motor.FromRobot(robot, "my_motor")

// Get the current position of the motor.
position, err := myMotor.Position(context.Background(), nil)

GetProperties

Report a dictionary mapping optional properties to whether it is supported by this motor.

Parameters:

  • None

Returns:

For more information, see the Python SDK Docs.

my_motor = Motor.from_robot(robot=robot, name="my_motor")

# Report a dictionary mapping optional properties to whether it is supported by
# this motor.
properties = await my_motor.get_properties()

# Print out the properties.
print(f'Properties: {properties}')

Parameters:

  • ctx (Context): A Context carries a deadline, a cancellation signal, and other values across API boundaries.
  • extra (map[string]interface{}): Extra options to pass to the underlying RPC call.

Returns:

For more information, see the Go SDK docs.

myMotor, err := motor.FromRobot(robot, "my_motor")

// Return whether or not the motor supports certain optional features.
properties, err := myMotor.Properties(context.Background(), nil)

// Log the properties.
logger.Info("Properties:")
logger.Info(properties)

IsPowered

Returns whether or not the motor is currently running, and the portion of max power (between 0 and 1; if the motor is off the power will be 0). Stepper motors will report true if they are being powered while holding a position, as well as when they are turning.

Parameters:

  • None

Returns:

  • (tuple[bool, float]): The bool is true if the motor is currently running; false if not. The float represents the current portion of max power to the motor (between 0 and 1).

For more information, see the Python SDK Docs.

my_motor = Motor.from_robot(robot=robot, name="my_motor")

# Check whether the motor is currently running.
powered = await my_motor.is_powered()

print('Powered: ', powered)

Parameters:

  • ctx (Context): A Context carries a deadline, a cancellation signal, and other values across API boundaries.
  • extra (map[string]interface{}): Extra options to pass to the underlying RPC call.

Returns:

  • (bool): True if the motor is currently running; false if not.
  • (float64): The current portion of max power to the motor (between 0 and 1).
  • (error): An error, if one occurred.

For more information, see the Go SDK docs.

myMotor, err := motor.FromRobot(robot, "my_motor")

// Check whether the motor is currently running.
powered, pct, err := myMotor.IsPowered(context.Background(), nil)

logger.Info("Is powered?")
logger.Info(powered)
logger.Info("Power percent:")
logger.Info(pct)

IsMoving

Returns whether the motor is actively moving (or attempting to move) under its own power.

Parameters:

  • None

Returns:

  • (bool): True if the motor is currently moving; false if not.

For more information, see the Python SDK Docs.

my_motor = Motor.from_robot(robot=robot, name="my_motor")

# Check whether the motor is currently moving.
moving = await my_motor.is_moving()
print('Moving: ', moving)

Parameters:

  • ctx (Context): A Context carries a deadline, a cancellation signal, and other values across API boundaries.

Returns:

  • (bool): True if the motor is currently moving.
  • (error): An error, if one occurred.

For more information, see the Go SDK docs.

myMotor, err := motor.FromRobot(robot, "my_motor")

// Check whether the motor is currently moving.
moving, err := myMotor.IsMoving(context.Background())

logger.Info("Is moving?")
logger.Info(moving)

Stop

Cut the power to the motor immediately, without any gradual step down.

Parameters:

  • None

Returns:

  • None

For more information, see the Python SDK Docs.

my_motor = Motor.from_robot(robot=robot, name="my_motor")

# Stop the motor.
await my_motor.stop()

Parameters:

  • ctx (Context): A Context carries a deadline, a cancellation signal, and other values across API boundaries.
  • extra (map[string]interface{}): Extra options to pass to the underlying RPC call.

Returns:

  • (error): An error, if one occurred.

For more information, see the Go SDK docs.

myMotor, err := motor.FromRobot(robot, "my_motor")

// Stop the motor.
myMotor.Stop(context.Background(), nil)

GetGeometries

Get all the geometries associated with the motor in its current configuration, in the frame of the motor. The motion and navigation services use the relative position of inherent geometries to configured geometries representing obstacles for collision detection and obstacle avoidance while motion planning.

Parameters:

  • extra (Optional[Dict[str, Any]]): Extra options to pass to the underlying RPC call.
  • timeout (Optional[float]): An option to set how long to wait (in seconds) before calling a time-out and closing the underlying RPC call.

Returns:

For more information, see the Python SDK Docs.

my_motor = Motor.from_robot(robot=robot, name="my_motor")

geometries = await my_motor.get_geometries()

if geometries:
    # Get the center of the first geometry
    print(f"Pose of the first geometry's centerpoint: {geometries[0].center}")

DoCommand

Execute model-specific commands that are not otherwise defined by the component API. For built-in models, model-specific commands are covered with each model’s documentation. If you are implementing your own motor and add features that have no built-in API method, you can access them with DoCommand.

Parameters:

Returns:

my_motor = Motor.from_robot(robot=robot, name="my_motor")

raw_dict = {
  "command": "raw",
  "raw_input": "home"
}

await my_motor.do_command(raw_dict)

For more information, see the Python SDK Docs.

Parameters:

Returns:

myMotor, err := motor.FromRobot(robot, "my_motor")

resp, err := myMotor.DoCommand(ctx, map[string]interface{}{"command": "jog", "raw_input": "home"})

For more information, see the Go SDK Code.

Close

Safely shut down the resource and prevent further use.

Parameters:

  • None

Returns:

  • None
my_motor = Motor.from_robot(robot, "my_motor")

await my_motor.close()

For more information, see the Python SDK Docs.

Parameters:

  • ctx (Context): A Context carries a deadline, a cancellation signal, and other values across API boundaries.

Returns:

  • (error) : An error, if one occurred.
myMotor, err := motor.FromRobot(robot, "my_motor")

err := myMotor.Close(ctx)

For more information, see the Go SDK Docs.

Troubleshooting

You can find additional assistance in the Troubleshooting section.

You can also ask questions on the Viam Community Slack and we will be happy to help.

Next steps


  1. The DMC4000 model does not require a board. ↩︎