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.
Related services
Available models
To use your motor component, check whether one of the following models supports it.
For configuration information, click on the model name:
Add support for other models
If none of the existing models fit your use case, you can create a modular resource to add support for it.
Model | Description |
---|---|
gpio | Standard brushed or brushless DC motor |
Add support for other models
If none of the existing models fit your use case, you can create a modular resource to add support for it.
viam-micro-server
works differently from the RDK, so creating modular resources for it is different.
Refer to the Micro-RDK Module Template on GitHub for information on how to create custom resources for your viam-micro-server
machine.
You will need to recompile and flash your ESP32 yourself instead of using Viam’s prebuilt binary and installer.
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.
API key and API key ID
By default, the sample code does not include your machine API key and API key ID. We strongly recommend that you add your API key and API key ID as an environment variable and import this variable into your development environment as needed.
To show your machine’s API key and API key ID in the sample code, toggle Include API key on the CONNECT tab’s Code sample page.
Caution
Do not share your API key or machine address publicly. Sharing this information could compromise your system security by allowing unauthorized access to your machine, or to the computer running your machine.
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 Name | Description | viam-micro-server Support |
---|---|---|
SetPower | Set the portion of max power to send to the motor (between -1 and 1 ). | |
SetRPM | Spin the motor indefinitely at the specified speed, in revolutions per minute. If rpm is positive, the motor will spin forwards, and if rpm is negative, the motor will spin backwards. | |
GoFor | Spin the motor the specified number of revolutions at specified revolutions per minute. | |
GoTo | Turn the motor to a specified position (in terms of revolutions from home/zero) at a specified speed in revolutions per minute (RPM). | |
ResetZeroPosition | Set the current position (modified by offset ) to be the new zero (home) position. | |
GetPosition | Report the position of the motor based on its encoder. | |
GetProperties | Report a dictionary mapping optional properties to whether it is supported by this motor. | |
IsPowered | Return 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 ). | |
GetGeometries | Get all the geometries associated with the motor in its current configuration, in the frame of the motor. | |
IsMoving | Return whether the motor is actively moving (or attempting to move) under its own power. | |
Stop | Cut the power to the motor immediately, without any gradual step down. | |
Reconfigure | Reconfigure this resource. | |
DoCommand | Execute model-specific commands that are not otherwise defined by the component API. | |
FromRobot | Get the resource from the provided robot with the given name. | |
GetResourceName | Get the ResourceName for this motor with the given name. | |
Close | Safely shut down the resource and prevent further use. |
SetPower
Set the portion of max power to send to the motor (between -1
and 1
).
A value of 1
represents 100% power forwards, while a value of -1
represents 100% power backwards.
Power is expressed as a floating point between -1
and 1
that scales between -100% and 100% power.
Supported by viam-micro-server
.
Parameters:
power
(float) (required): Power between -1 and 1 (negative implies backwards).extra
(Mapping[str, Any]) (optional): Extra options to pass to the underlying RPC call.timeout
(float) (optional): An option to set how long to wait (in seconds) before calling a time-out and closing the underlying RPC call.
Returns:
- None.
Example:
my_motor = Motor.from_robot(robot=robot, name="my_motor")
# Set the power to 40% forwards.
await my_motor.set_power(power=0.4)
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.powerPct
(float64): Portion of full power to send to the motor expressed as a floating point between-1
and1
. A value of1
represents 100% power forwards, while a value of-1
represents 100% power backwards.extra
(map[string]interface{}): Extra options to pass to the underlying RPC call.
Returns:
- (error): An error, if one occurred.
Example:
myMotorComponent, err := motor.FromRobot(machine, "my_motor")
// Set the motor power to 40% forwards.
myMotorComponent.SetPower(context.Background(), 0.4, nil)
For more information, see the Go SDK Docs.
Parameters:
Returns:
- Future<void>
Example:
// Set the power to 40% forwards.
await myMotor.setPower(0.4);
For more information, see the Flutter SDK Docs.
SetRPM
Spin the motor indefinitely at the specified speed, in revolutions per minute. If rpm
is positive, the motor will spin forwards, and if rpm
is negative, the motor will spin backwards.
Parameters:
rpm
(float) (required): Speed at which the motor should rotate.extra
(Mapping[str, Any]) (optional): Extra options to pass to the underlying RPC call.timeout
(float) (optional): An option to set how long to wait (in seconds) before calling a time-out and closing the underlying RPC call.
Returns:
- None.
Example:
my_motor = Motor.from_robot(robot=robot, name="my_motor")
# Spin the motor at 75 RPM.
await my_motor.set_rpm(rpm=75)
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.rpm
(float64): The speed in RPM for the motor to move at.extra
(map[string]interface{}): Extra options to pass to the underlying RPC call.
Returns:
- (error): An error, if one occurred.
Example:
// Set the motor's RPM to 50
myMotorComponent.SetRPM(context.Background(), 50)
For more information, see the Go SDK Docs.
Parameters:
Returns:
- Future<void>
Example:
// Set the motor to turn backwards at 120.5 RPM.
await myMotor.setRPM(-120.5);
For more information, see the Flutter SDK Docs.
GoFor
Spin 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) (required): Speed at which the motor should move in rotations per minute (negative implies backwards).revolutions
(float) (required): Number of revolutions the motor should run for (negative implies backwards).extra
(Mapping[str, Any]) (optional): Extra options to pass to the underlying RPC call.timeout
(float) (optional): An option to set how long to wait (in seconds) before calling a time-out and closing the underlying RPC call.
Returns:
- None.
Example:
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)
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.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 is0
, this runs the motor atrpm
indefinitely. If revolutions not equal to0
, 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.
Example:
myMotorComponent, err := motor.FromRobot(machine, "my_motor")
// Turn the motor 7.2 revolutions at 60 RPM.
myMotorComponent.GoFor(context.Background(), 60, 7.2, nil)
For more information, see the Go SDK Docs.
GoTo
Turn 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) (required): Speed at which the motor should rotate (absolute value).position_revolutions
(float) (required): Target position relative to home/zero, in revolutions.extra
(Mapping[str, Any]) (optional): Extra options to pass to the underlying RPC call.timeout
(float) (optional): An option to set how long to wait (in seconds) before calling a time-out and closing the underlying RPC call.
Returns:
- None.
Example:
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)
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.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.
Example:
// Turn the motor to 8.3 revolutions from home at 75 RPM.
myMotorComponent.GoTo(context.Background(), 75, 8.3, nil)
For more information, see the Go SDK Docs.
ResetZeroPosition
Set the current position (modified by offset
) to be the new zero (home) position.
Parameters:
offset
(float) (required): The offset from the current position to new home/zero position.extra
(Mapping[str, Any]) (optional): Extra options to pass to the underlying RPC call.timeout
(float) (optional): An option to set how long to wait (in seconds) before calling a time-out and closing the underlying RPC call.
Returns:
- None.
Example:
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)
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.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.
Example:
// Set the current position as the new home position with no offset.
myMotorComponent.ResetZeroPosition(context.Background(), 0.0, nil)
For more information, see the Go SDK Docs.
Parameters:
Returns:
- Future<void>
Example:
// Set the current position as the new home position with no offset.
await myMotor.resetZeroPosition(0.0);
For more information, see the Flutter SDK Docs.
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.
Supported by viam-micro-server
.
Parameters:
extra
(Mapping[str, Any]) (optional): Extra options to pass to the underlying RPC call.timeout
(float) (optional): An option to set how long to wait (in seconds) before calling a time-out and closing the underlying RPC call.
Returns:
- (float): Number of revolutions the motor is away from zero/home.
Example:
my_motor = Motor.from_robot(robot=robot, name="my_motor")
# Get the current position of the motor.
position = await my_motor.get_position()
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.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.
Example:
// Get the current position of an encoded motor.
position, err := myMotorComponent.Position(context.Background(), nil)
// Log the position
logger.Info("Position:")
logger.Info(position)
For more information, see the Go SDK Docs.
Parameters:
Returns:
Example:
// Get the current position of an encoded motor.
var position = await myMotor.position();
For more information, see the Flutter SDK Docs.
GetProperties
Report a dictionary mapping optional properties to whether it is supported by this motor.
Supported by viam-micro-server
.
Parameters:
extra
(Mapping[str, Any]) (optional): Extra options to pass to the underlying RPC call.timeout
(float) (optional): An option to set how long to wait (in seconds) before calling a time-out and closing the underlying RPC call.
Returns:
- (viam.components.motor.motor.Motor.Properties): Map of feature names to supported status.
Example:
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}')
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.extra
(map[string]interface{}): Extra options to pass to the underlying RPC call.
Returns:
- (Properties): A map indicating whether or not the motor supports certain optional features.
- (error): An error, if one occurred.
Example:
// Return whether or not the motor supports certain optional features.
properties, err := myMotorComponent.Properties(context.Background(), nil)
// Log the properties.
logger.Info("Properties:")
logger.Info(properties)
For more information, see the Go SDK Docs.
Parameters:
Returns:
Example:
// Return whether the motor supports certain optional features
var properties = await myMotor.properties();
For more information, see the Flutter SDK Docs.
IsPowered
Return 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:
extra
(Mapping[str, Any]) (optional): Extra options to pass to the underlying RPC call.timeout
(float) (optional): An option to set how long to wait (in seconds) before calling a time-out and closing the underlying RPC call.
Returns:
- (Tuple[bool, float]): A tuple containing two values; the first [0] value indicates whether the motor is currently powered, andthe second [1] value indicates the current power percentage of the motor. .
Example:
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)
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.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.
Example:
// Check whether the motor is currently running.
powered, pct, err := myMotorComponent.IsPowered(context.Background(), nil)
logger.Info("Is powered?")
logger.Info(powered)
logger.Info("Power percent:")
logger.Info(pct)
For more information, see the Go SDK Docs.
Parameters:
Returns:
Example:
// Check whether the motor is currently powered and
// check the percentage of max power to the motor.
var powerState = await myMotor.powerState();
var powered = powerState.isOn;
var pct = powerState.powerPct;
For more information, see the Flutter SDK Docs.
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
(Mapping[str, Any]) (optional): Extra options to pass to the underlying RPC call.timeout
(float) (optional): An option to set how long to wait (in seconds) before calling a time-out and closing the underlying RPC call.
Returns:
- (List[viam.proto.common.Geometry]): The geometries associated with the Component.
Example:
geometries = await component.get_geometries()
if geometries:
# Get the center of the first geometry
print(f"Pose of the first geometry's centerpoint: {geometries[0].center}")
For more information, see the Python SDK Docs.
IsMoving
Return whether the motor is actively moving (or attempting to move) under its own power.
Supported by viam-micro-server
.
Parameters:
timeout
(float) (optional): An option to set how long to wait (in seconds) before calling a time-out and closing the underlying RPC call.
Returns:
- (bool): Whether the motor is moving.
Example:
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)
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:
Example:
// This example shows using IsMoving with an arm component.
myArm, err := arm.FromRobot(machine, "my_arm")
// Stop all motion of the arm. It is assumed that the arm stops immediately.
myArm.Stop(context.Background(), nil)
// Log if the arm is currently moving.
is_moving, err := myArm.IsMoving(context.Background())
logger.Info(is_moving)
For more information, see the Go SDK Docs.
Parameters:
Returns:
Example:
// Check whether the motor is moving.
var moving = await myMotor.isMoving();
For more information, see the Flutter SDK Docs.
Stop
Cut the power to the motor immediately, without any gradual step down.
Supported by viam-micro-server
.
Parameters:
extra
(Mapping[str, Any]) (optional): Extra options to pass to the underlying RPC call.timeout
(float) (optional): An option to set how long to wait (in seconds) before calling a time-out and closing the underlying RPC call.
Returns:
- None.
Example:
my_motor = Motor.from_robot(robot=robot, name="my_motor")
# Stop the motor.
await my_motor.stop()
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.extra
(map[string]interface{}): Extra options to pass to the underlying RPC call.
Returns:
- (error): An error, if one occurred.
Example:
// This example shows using Stop with an arm component.
myArm, err := arm.FromRobot(machine, "my_arm")
// Stop all motion of the arm. It is assumed that the arm stops immediately.
err = myArm.Stop(context.Background(), nil)
For more information, see the Go SDK Docs.
Parameters:
Returns:
- Future<void>
Example:
// Stop the motor.
await myMotor.stop();
For more information, see the Flutter SDK Docs.
Reconfigure
Reconfigure this resource. Reconfigure must reconfigure the resource atomically and in place.
Parameters:
ctx
(Context): A Context carries a deadline, a cancellation signal, and other values across API boundaries.deps
(Dependencies): The resource dependencies.conf
(Config): The resource configuration.
Returns:
- (error): An error, if one occurred.
For more information, see the Go SDK Docs.
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
(Mapping[str, ValueTypes]) (required): The command to execute.timeout
(float) (optional): An option to set how long to wait (in seconds) before calling a time-out and closing the underlying RPC call.
Returns:
- (Mapping[str, viam.utils.ValueTypes]): Result of the executed command.
Raises:
- (NotImplementedError): Raised if the Resource does not support arbitrary commands.
Example:
command = {"cmd": "test", "data1": 500}
result = component.do(command)
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{}): The command response.
- (error): An error, if one occurred.
Example:
// This example shows using DoCommand with an arm component.
myArm, err := arm.FromRobot(machine, "my_arm")
command := map[string]interface{}{"cmd": "test", "data1": 500}
result, err := myArm.DoCommand(context.Background(), command)
For more information, see the Go SDK Docs.
FromRobot
Get the resource from the provided robot with the given name.
Parameters:
robot
RobotClient (required)name
String (required)
Returns:
For more information, see the Flutter SDK Docs.
GetResourceName
Get the ResourceName
for this motor with the given name.
Parameters:
name
(str) (required): The name of the Resource.
Returns:
- (viam.proto.common.ResourceName): The ResourceName of this Resource.
Example:
# Can be used with any resource, using an arm as an example
my_arm_name = my_arm.get_resource_name("my_arm")
For more information, see the Python SDK Docs.
Parameters:
name
String (required)
Returns:
Example:
var name = Motor.getResourceName('myMotor');
For more information, see the Flutter SDK Docs.
Close
Safely shut down the resource and prevent further use.
Parameters:
- None.
Returns:
- None.
Example:
await component.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.
Example:
// This example shows using Close with an arm component.
myArm, err := arm.FromRobot(machine, "my_arm")
err = myArm.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
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!