Use input to determine actions

You can program your machine to move based on sensor readings or other inputs.

Prerequisites

A running machine connected to the Viam app. Click to see instructions.
Add a new machine in the Viam app. On the machine’s page, follow the setup instructions to install viam-server on the computer you’re using for your project. Wait until your machine has successfully connected to the Viam app.
Components configured on your machine.

Configure your sensing and actuation hardware as components of your machine.

This may include sensors, cameras, motors, bases, arms, gantries, servos, grippers, or other components.

Program your machine

1. Start building your app

Depending on your use case, see Create a web app, Create a mobile app, or Create a headless app for information on installing an SDK and connecting your code to your machine.

2. Get an input

Use one of the input APIs, such as a sensor’s GetReadings method:

my_sensor = Sensor.from_robot(robot=machine, name='my_sensor')

# Get the readings provided by the sensor.
readings = await my_sensor.get_readings()

Other common inputs include the methods of a board (GetGPIO, GetPWM, PWMFrequency, GetDigitalInterruptValue, and ReadAnalogReader), or a power sensor (GetVoltage, GetCurrent, GetPower, and GetReadings).

You can also use camera input, for example to detect objects and pick them up with an arm. See Act based on inferences for relevant examples.

If you want to send alerts based on computer vision or captured data, see Alert on inferences or Alert on data.

3. Actuate based on the input

To move your actuator, use your actuator component’s API, with logic based on your input.

For example, use the motor API’s which includes methods like SetPower, SetRPM, GoFor, GoTo, and Stop. A Python example:

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

# Assume your sensor returns a reading with a key called "level"
# If the sensor reads less than 50, spin the motor at 95 RPM.
current_level = readings.get('level')
if (current_level < 50):
    await my_motor.set_rpm(rpm=95)
else:
    await my_motor.stop()

Other actuation methods include the servo API’s Move method, the gripper API’s Open, Grab, and Stop methods, and the board API’s SetGPIO, SetPWM, SetPWMFrequency, and WriteAnalog methods.

If your use case involves planning coordinated motion of multiple motors, see Move a base, Move an arm, or Move a gantry for more information on how to automate intelligent motion planning. Instead of actuating using the component API, you can use the motion service API’s Move, MoveOnMap, or MoveOnGlobe commands.

Usage examples

To water a plant based on moisture sensor readings using the board API, see Plant watering robot with a Raspberry Pi.

To turn a fan on or off based on air quality sensor data, see Automate air filtration with air quality sensors.