Control a motor in 2 minutes

You can use Viam to control a motor’s speed and direction directly from the Viam app, the mobile app, or programmatically.

Requirements

  • A single-board computer with a supported OS installed (such as Raspberry Pi)
  • A motor and compatible motor driver connected to the board
  • A power supply for the board
  • A separate power supply for the motor

Follow these steps to control your motor:

Step 1: Create a machine

Go to the Viam app. Select a location and add a new machine.

The ‘My Desk’ page on the Viam app with a new machine name in the New machine field and the Add machine button next to the field highlighted.

Step 2: Install viam-server
Navigate to the CONFIGURE tab of your machine’s page in the Viam app. Follow the setup instructions that appear on your new machine’s CONFIGURE page to install viam-server on your computer and connect it to the Viam app.
Step 3: Configure a board

Then, add a board component.

Look through the Supported Models to determine the model of component to configure. For example, configure a pi board for a Raspberry Pi 4, Raspberry Pi 3 or Raspberry Pi Zero 2 W:

An example board configuration in the app builder UI. The name (local), type (board) and model (pi) are shown. No other attributes are configured.

Follow the instructions in the board model’s documentation to configure any required attributes.

Step 4: Configure a motor

Add a motor component that supports the type of motor and motor driver you’re using. Look through the Supported Models to determine the model of component to configure. For example, if you are using a standard DC motor (brushed or brushless) wired to a typical GPIO pin-controlled motor driver, configure a gpio motor:

The CONFIGURE tab of the Viam app populated with a configured gpio motor.

Follow the motor driver manufacturer’s data sheet to properly wire your motor driver to your board and to your motor. Follow the model’s documentation to configure the attributes so that the computer can send signals to the motor.

Step 5: Choose how you will control the motor

You can control your motor directly from the Viam app, using the mobile app, or programmatically.

Option 1: Control from the app

Navigate to your machine’s CONTROL tab in the Viam app and use the Power % slider to set the motor’s speed. Use the Backwards and Forwards buttons to change the direction.

Option 2: Control from the mobile app

You can use the Viam mobile app to control your motor’s speed and direction directly from your smart device.

Open the Viam mobile app and log in to your account. Select the location where your machine is assigned. Choose your machine from the list and use the mobile interface to adjust the motor settings.

Select the location that your machine is assigned to from the Locations tab.

Option 3: Control programmatically

You can use the following code to control the motor’s speed and direction using your preferred SDK. Find your machine’s API key and address on your machine’s CONNECT tab.

import asyncio
import time

from viam.robot.client import RobotClient
from viam.rpc.dial import Credentials, DialOptions
from viam.components.motor import Motor


async def connect():
    opts = RobotClient.Options.with_api_key(
        # Replace "<API-KEY>" (including brackets) with your machine's API key
        api_key='<API-KEY>',
        # Replace "<API-KEY-ID>" (including brackets) with your machine's API
        # key ID
        api_key_id='<API-KEY-ID>'
    )
    return await RobotClient.at_address(
        '<YOUR MACHINE ADDRESS>', opts)


async def main():
    machine = await connect()

    print('Resources:')
    print(machine.resource_names)

    # Instantiate the motor client
    motor_1 = Motor.from_robot(machine, "motor-1")
    # Turn the motor at 35% power forwards
    await motor_1.set_power(power=0.35)
    # Let the motor spin for 4 seconds
    time.sleep(4)
    # Stop the motor
    await motor_1.stop()

    # Don't forget to close the machine when you're done!
    await machine.close()


if __name__ == '__main__':
    asyncio.run(main())
package main

import (
  "context"
  "time"

  "go.viam.com/rdk/logging"
  "go.viam.com/rdk/robot/client"
  "go.viam.com/rdk/utils"
  "go.viam.com/rdk/components/motor")

func main() {
  logger := logging.NewDebugLogger("client")
  machine, err := client.New(
    context.Background(),
    // Replace "<YOUR MACHINE ADDRESS>" (including brackets) with your machine's address
    "<YOUR MACHINE ADDRESS>",
    logger,
    client.WithDialOptions(utils.WithEntityCredentials(
      // Replace "<API-KEY-ID>" (including brackets) with your machine's API key ID
      "<API-KEY-ID>",
      utils.Credentials{
        Type:    utils.CredentialsTypeAPIKey,
        // Replace "<API-KEY>" (including brackets) with your machine's API key
        Payload: "<API-KEY>",
      })),
  )
  if err != nil {
    logger.Fatal(err)
  }

  defer machine.Close(context.Background())
  logger.Info("Resources:")
  logger.Info(machine.ResourceNames())


  // Instantiate the motor client
  motor1Component, err:= motor.FromRobot(machine, "motor-1")
  if err != nil {
    logger.Error(err)
    return
  }
  // Turn the motor at 35% power forwards
  err = motor1Component.SetPower(context.Background(), 0.35, nil)
  if err != nil {
    logger.Error(err)
    return
  }
  // Let the motor spin for 4 seconds
  time.Sleep(4 * time.Second)
  // Stop the motor
  err = motor1Component.Stop(context.Background(), nil)
  if err != nil {
    logger.Error(err)
    return
  }
}

Next steps

Now that you have made a motor move, explore other components or related services:

To see motors in real-world projects, check out these tutorials:

Have questions, or want to meet other people working on robots? Join our Community Discord.

If you notice any issues with the documentation, feel free to file an issue or edit this file.