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 robots 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.
Configuration
How you configure your motor with Viam depends more on the motor driver than on the motor itself. Click the model names below for configuration information:
Model | Description |
---|---|
gpio | Standard brushed or brushless DC motor |
gpiostepper | Bipolar stepper motor with current regulation and 1/32 microstepping driven by a basic driver like DRV8825 or TMC2209 |
28byj48 | Small unipolar 28BYJ-48 stepper motor driven by a ULN2003 driver |
TMC5072 | Stepper motor driven by the TMC5072 chip |
DMC4000 | Stepper motor driven by a DMC-40x0 series motion controller |
roboclaw | Standard brushed DC motor driven by Basicmicro’s RoboClaw motor controller |
fake | Used to test code without hardware |
Viam also provides the following motor models as modular resources:
Model | Description |
---|---|
viam:odrive:canbus | An ODrive S1 motor driver with CANbus communication |
viam:odrive:serial | An ODrive S1 motor driver with serial communication |
These modules can be added to your robot from the Viam registry.
Control your motor with Viam’s client SDK libraries
To get started using Viam’s SDKs to connect to and control your robot, go to your robot’s page on the Viam app, navigate to the Code sample tab, select your preferred programming language, and copy the sample code generated.
Location secret
By default, the sample code does not include your robot location secret. We strongly recommend that you add your location secret as an environment variable and import this variable into your development environment as needed.
To show your robot’s location secret in the sample code, toggle Include secret on the Code sample tab. You can also see your location secret on the locations page.
Caution
Do not share your location secret, part secret, or robot address publicly. Sharing this information could compromise your system security by allowing unauthorized access to your robot, or to the computer running your robot.
When executed, this sample code will create a connection to your robot as a client. Then control your robot 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 robot.
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 Name | Description |
---|---|
SetPower | Set the power to send to the motor as a portion of max power. |
GoFor | Spin the motor the specified number of revolutions at specified RPM. |
GoTo | Send the motor to a specified position (in terms of revolutions from home) at a specified speed. |
ResetZeroPosition | Set the current position to be the new zero (home) position. |
GetPosition | Report the position of the motor based on its encoder. Not supported on all motors. |
GetProperties | Return whether or not the motor supports certain optional features. |
IsPowered | Return whether or not the motor is currently on, and the amount of power to it. |
IsMoving | Return whether the motor is moving or not. |
Stop | Cut power to the motor off immediately, without any gradual step down. |
DoCommand | Send or receive model-specific commands. |
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 atrpm
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:
- (Properties): Map of feature names to supported status.
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:
- (map[Feature][bool]): A map indicating whether or not the motor supports certain optional features.
- (error): An error, if one occurred.
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:
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)
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:
command
(Dict[str, Any]): The command to execute.
Returns:
- (Dict[str, Any]): Result of the executed command.
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:
ctx
(Context): A Context carries a deadline, a cancellation signal, and other values across API boundaries.cmd
(map[string]interface{}): The command to execute.
Returns:
- (map[string]interface{}): Result of the executed command.
- (error): An error, if one occurred.
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.
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
The
DMC4000
model does not require a board. ↩︎
Was this page helpful?
Glad to hear it! If you have any other feedback please let us know:
We're sorry about that. To help us improve, please tell us what we can do better:
Thank you!