Encoder Component
An encoder is a type of sensor that can detect speed and direction of rotation of a motor or a joint. It is often used in conjunction with a motor, and is sometimes even built into a motor. An encoder could also be mounted on a passive joint or other rotating object to keep track of the joint angle.
The encoder component supports:
- Incremental encoders, which can measure the speed and direction of rotation in relation to a given reference point like a starting point. These encoders output two phases. Based on the sequence and timing of these phases, it is determined how far something has turned and in which direction. Each phase output goes to a different pin on the board.
- Single phase or single pin “pulse output” encoders, which measure the position relative to the starting position but not the direction.
- Absolute encoders, which provide the absolute position of a rotating shaft, without requiring a reference point.
Most machines with an encoder need at least the following hardware:
- A board component that can run a
viam-server
instance. For example, a Raspberry Pi, or another model of single-board computer with GPIO (general purpose input/output) pins. - Some sort of rotary machine part (like a motor, joint or dial) for which you want to measure movement.
Related services
Supported models
To use your encoder with Viam, check whether one of the following built-in models supports your encoder.
Built-in models
For configuration information, click on the model name:
Model | Description |
---|---|
AMS-AS5048 | The AMS-AS5048 encoder is an absolute encoder that which can connect using an I2C interface. |
fake | An encoder model for testing. |
incremental | A two phase encoder, which can measure the speed and direction of rotation in relation to a given reference point. |
single | A single pin “pulse output” encoder which returns its relative position but no direction. |
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.
Micro-RDK
If you are using the micro-RDK, navigate to Micro-RDK Encoder for supported model information.
Control your encoder 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.
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 secret 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 an encoder called "my_encoder"
configured as a component of your machine.
If your encoder has a different name, change the name
in the code.
Be sure to import the encoder package for the SDK you are using:
from viam.components.encoder import Encoder
import (
"go.viam.com/rdk/components/encoder"
)
API
The encoder component supports the following methods:
Method Name | Description |
---|---|
GetPosition | Get the current position of the encoder. |
ResetPosition | Reset the position to zero. |
GetProperties | Get the supported properties of this encoder. |
GetGeometries | Get all the geometries associated with the encoder in its current configuration, in the frame of the encoder. |
DoCommand | Send or receive model-specific commands. |
Close | Safely shut down the resource and prevent further use. |
GetPosition
Get the current position of the encoder in ticks or degrees. Relative encoders return ticks since last zeroing. Absolute encoders return degrees.
Parameters:
position_type
(Optional[PositionType.ValueType]): Specify whether to get the current position in ticks (encoder.PositionTypeTicks
) or in degrees (encoder.PositionTypeDegrees
). If you are not sure which position type your encoder supports but it is a built-in Viam-supported model, you can leave this parameter unspecified (encoder.PositionTypeUnspecified
) or empty and it will default to the correct position type.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:
- (Tuple[float, PositionType.ValueType]): The current position in ticks or degrees, and the type of position the encoder returns (ticks or degrees).
For more information, see the Python SDK Docs.
my_encoder = Encoder.from_robot(robot=robot, name='my_encoder')
# Get the position of the encoder in ticks
position = await my_encoder.get_position(encoder.PositionTypeTicks)
print("The encoder position is currently ", position[0], position[1])
Parameters:
ctx
(Context): A Context carries a deadline, a cancellation signal, and other values across API boundaries.positionType
(PositionType): Specify whether to get the current position in ticks (encoder.PositionTypeTicks
) or in degrees (encoder.PositionTypeDegrees
). If you are not sure which position type your encoder supports but it is a built-in Viam-supported model, you can leave this parameter unspecified (encoder.PositionTypeUnspecified
) and it will default to the correct position type.extra
(map[string]interface{}): Extra options to pass to the underlying RPC call.
Returns:
- (float64): The current position in ticks or degrees.
- (PositionType): The type of position the encoder returns (ticks or degrees).
- (error): An error, if one occurred.
For more information, see the Go SDK Docs.
myEncoder, err := encoder.FromRobot(robot, "my_encoder")
if err != nil {
logger.Fatalf("cannot get encoder: %v", err)
}
// Get the position of the encoder in ticks
position, posType, err := myEncoder.Position(context.Background(), encoder.PositionTypeTicks, nil)
ResetPosition
Set the current position of the encoder to be the new zero position.
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:
- None
For more information, see the Python SDK Docs.
my_encoder = Encoder.from_robot(robot=robot, name='my_encoder')
# Reset the zero position of the encoder.
await my_encoder.reset_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:
- (error): An error, if one occurred.
For more information, see the Go SDK Docs.
myEncoder, err := encoder.FromRobot(robot, "my_encoder")
if err != nil {
logger.Fatalf("cannot get encoder: %v", err)
}
err := myEncoder.ResetPosition(context.Background(), nil)
GetProperties
Get a list of all the position types that are supported by a given encoder.
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:
- (Properties): The position types supported by the encoder model.
For more information, see the Python SDK Docs.
my_encoder = Encoder.from_robot(robot=robot, name='my_encoder')
# Get whether the encoder returns position in ticks or degrees.
properties = await my_encoder.get_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): The position types supported by the encoder model.
- (error): An error, if one occurred.
For more information, see the Go SDK docs.
myEncoder, err := encoder.FromRobot(robot, "my_encoder")
// Get whether the encoder returns position in ticks or degrees.
properties, err := myEncoder.Properties(context.Background(), nil)
GetGeometries
Get all the geometries associated with the encoder in its current configuration, in the frame of the encoder. 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:
- (List[Geometry]): The geometries associated with the encoder, in any order.
For more information, see the Python SDK Docs.
my_encoder = Encoder.from_robot(robot=robot, name="my_encoder")
geometries = await my_encoder.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.
If you are implementing your own encoder as a modular resource and are adding 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_encoder = Encoder.from_robot(robot=robot, name='my_encoder')
reset_dict = {
"command": "reset",
"example_param": 30
}
do_response = await my_encoder.do_command(reset_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.
myEncoder, err := encoder.FromRobot(robot, "my_encoder")
resp, err := myEncoder.DoCommand(ctx, map[string]interface{}{"command": "reset", "example_param": 30})
For more information, see the Go SDK Code.
Close
Safely shut down the resource and prevent further use.
Parameters:
- None
Returns:
- None
my_encoder = Encoder.from_robot(robot, "my_encoder")
await my_encoder.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.
myEncoder, err := encoder.FromRobot(robot, "my_encoder")
err := myEncoder.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
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!