Sensor Component

This page explains how to set up a generic sensor component with Viam. Viam has a few types of sensor implemented including an ultrasonic sensor, and certain temperature sensors, but this doc covers setting up a custom sensor so you can build a robot using almost any sort of sensor.

Most robots with a sensor need at least the following hardware:

  • Some sort of sensor, such as an ultrasonic sensor or temperature sensor
  • A board
  • Depending on your sensor’s output type (analog or digital), an analog to digital converter may be necessary to allow the sensor to communicate with the board.

Wiring

The wiring for your sensor depends on the specific sensor you are using. Refer to the sensor’s data sheet for wiring details.

Configuration

To create a custom sensor, you must create a set of attributes unique to that sensor model:

KeyDescription
nameThe name that you use to refer to the sensor in your code.
typeFor a sensor, the type is sensor.
modelThe model of sensor used (for example, “ultrasonic”). Either a built-in Viam model or one you define when implementing a custom sensor model.

Don’t forget to include any required attributes you define in your custom sensor component implementation.

{
    "name": "mySensorName",
    "type": "sensor",
    "model": "mySensorModel",
    "attributes": {},
    "depends_on": []
}

Control your sensor with Viam’s client SDK libraries

The following example connects to and gets readings from an ultrasonic sensor component named mySensorName:

from viam.components.sensor import Sensor

robot = await connect()
sensor = Sensor.from_robot(robot, "mySensorName")
readings = await sensor.get_readings()
import (
    "context"
    "github.com/edaniels/golog"
    "go.viam.com/rdk/components/sensor"
)

func main() {
    // Connect to your robot.
    robot, err := client.New(
        context.Background(),
        "ADD YOUR ROBOT ADDRESS HERE. You can find this on the Code Sample tab of app.viam.com.",
        logger,
      client.WithDialOptions(rpc.WithCredentials(rpc.Credentials{
          Type:    utils.CredentialsTypeRobotLocationSecret,
          Payload: "ADD YOUR LOCATION SECRET HERE. You can find this on the Code Sample tab of app.viam.com.",
      })),
  )

    ultra, err := sensor.FromRobot(robot, "ultra1")
    readings, err := ultra.Readings(context.Background())
 }

You can read more about sensor implementation in the Python SDK Documentation or the Go SDK Documentation.