Adding sensors on a robot#
Sensors measure the robot and its surroundings. This tutorial adds three types to the ANYmal-C quadruped:
a head-mounted camera for RGB-D images;
a height scanner for terrain measurements; and
foot contact sensors for detecting contact with the ground.
See Sensors for sensor types and their configuration.
We continue this tutorial from the previous tutorial on Using the Interactive Scene,
where we learned about the scene.InteractiveScene class.
The Code#
The tutorial corresponds to the add_sensors_on_robot.py script in the
scripts/tutorials/04_sensors directory.
Code for add_sensors_on_robot.py
1# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md).
2# All rights reserved.
3#
4# SPDX-License-Identifier: BSD-3-Clause
5
6"""
7This script demonstrates how to add and simulate on-board sensors for a robot.
8
9We add the following sensors on the quadruped robot, ANYmal-C (ANYbotics):
10
11* USD-Camera: This is a camera sensor that is attached to the robot's base.
12* Height Scanner: This is a height scanner sensor that is attached to the robot's base.
13* Contact Sensor: This is a contact sensor that is attached to the robot's feet.
14
15.. code-block:: bash
16
17 # Usage
18 uv run --extra ov python scripts/tutorials/04_sensors/add_sensors_on_robot.py --viz newton_rtx
19
20"""
21
22"""Parse the command-line arguments first."""
23
24import argparse
25from types import SimpleNamespace
26from typing import TYPE_CHECKING
27
28from isaaclab_ov.physics import OvPhysxCfg
29from isaaclab_ov.renderers import OVRTXRendererCfg
30
31from isaaclab.app import add_launcher_args, launch_simulation
32
33# add argparse arguments
34parser = argparse.ArgumentParser(description="Tutorial on adding sensors on a robot.")
35parser.add_argument("--num_envs", type=int, default=2, help="Number of environments to spawn.")
36# append simulation launcher cli args
37add_launcher_args(parser)
38parser.set_defaults(visualizer=["newton_rtx"])
39# parse the arguments
40args_cli = parser.parse_args()
41# The scene has a camera sensor, which requires the rendering extensions in headless launches.
42args_cli.enable_cameras = True
43
44"""Rest everything follows."""
45
46import torch
47
48import isaaclab.sim as sim_utils
49from isaaclab.assets import ArticulationCfg, AssetBaseCfg
50from isaaclab.scene import InteractiveSceneCfg
51from isaaclab.sensors import CameraCfg, ContactSensorCfg, RayCasterCfg, patterns
52from isaaclab.utils import configclass, instantiate, replace
53
54if TYPE_CHECKING:
55 from isaaclab.scene import InteractiveScene
56
57##
58# Pre-defined configs
59##
60from isaaclab_assets.robots.anymal import ANYMAL_C_CFG # isort: skip
61
62
63@configclass
64class SensorsSceneCfg(InteractiveSceneCfg):
65 """Design the scene with sensors on the robot."""
66
67 # ground plane
68 ground = AssetBaseCfg(prim_path="/World/defaultGroundPlane", spawn=sim_utils.GroundPlaneCfg())
69
70 # lights
71 dome_light = AssetBaseCfg(
72 prim_path="/World/Light", spawn=sim_utils.DomeLightCfg(intensity=3000.0, color=(0.75, 0.75, 0.75))
73 )
74
75 # robot
76 robot: ArticulationCfg = replace(ANYMAL_C_CFG, prim_path="{ENV_REGEX_NS}/Robot")
77
78 # sensors
79 camera = CameraCfg(
80 renderer_cfg=OVRTXRendererCfg(),
81 prim_path="{ENV_REGEX_NS}/Robot/base/front_cam",
82 update_period=0.1,
83 height=480,
84 width=640,
85 data_types=["rgb", "distance_to_image_plane"],
86 spawn=sim_utils.PinholeCameraCfg(
87 focal_length=24.0, focus_distance=400.0, horizontal_aperture=20.955, clipping_range=(0.1, 1.0e5)
88 ),
89 offset=CameraCfg.OffsetCfg(pos=(0.510, 0.0, 0.015), rot=(0.5, -0.5, 0.5, -0.5), convention="ros"),
90 )
91 height_scanner = RayCasterCfg(
92 prim_path="{ENV_REGEX_NS}/Robot/base",
93 update_period=0.02,
94 offset=RayCasterCfg.OffsetCfg(pos=(0.0, 0.0, 20.0)),
95 ray_alignment="yaw",
96 pattern_cfg=patterns.GridPatternCfg(resolution=0.1, size=[1.6, 1.0]),
97 debug_vis=True,
98 mesh_prim_paths=["/World/defaultGroundPlane"],
99 )
100 contact_forces = ContactSensorCfg(
101 prim_path="{ENV_REGEX_NS}/Robot/.*_FOOT", update_period=0.0, history_length=6, debug_vis=True
102 )
103
104
105def run_simulator(sim: sim_utils.SimulationContext, scene: "InteractiveScene"):
106 """Run the simulator."""
107 # Define simulation stepping
108 sim_dt = sim.get_physics_dt()
109 sim_time = 0.0
110 count = 0
111
112 # Simulate physics
113 while sim.is_running():
114 # Reset
115 if count % 500 == 0:
116 # reset counter
117 count = 0
118 # reset the scene entities
119 # root state
120 # we offset the root state by the origin since the states are written in simulation world frame
121 # if this is not done, then the robots will be spawned at the (0, 0, 0) of the simulation world
122 root_pose = scene["robot"].data.default_root_pose.torch.clone()
123 root_pose[:, :3] += scene.env_origins
124 scene["robot"].write_root_pose_to_sim_index(root_pose=root_pose)
125 root_vel = scene["robot"].data.default_root_vel.torch.clone()
126 scene["robot"].write_root_velocity_to_sim_index(root_velocity=root_vel)
127 # set joint positions with some noise
128 joint_pos, joint_vel = (
129 scene["robot"].data.default_joint_pos.torch.clone(),
130 scene["robot"].data.default_joint_vel.torch.clone(),
131 )
132 joint_pos += torch.rand_like(joint_pos) * 0.1
133 scene["robot"].write_joint_position_to_sim_index(position=joint_pos)
134 scene["robot"].write_joint_velocity_to_sim_index(velocity=joint_vel)
135 # clear internal buffers
136 scene.reset()
137 print("[INFO]: Resetting robot state...")
138 # Apply default actions to the robot
139 # -- generate actions/commands
140 targets = scene["robot"].data.default_joint_pos.torch
141 # -- apply action to the robot
142 scene["robot"].set_joint_position_target_index(target=targets)
143 # -- write data to sim
144 scene.write_data_to_sim()
145 # perform step
146 sim.step()
147 # update sim-time
148 sim_time += sim_dt
149 count += 1
150 # update buffers
151 scene.update(sim_dt)
152
153 # print information from the sensors
154 print("-------------------------------")
155 print(scene["camera"])
156 print("Received shape of rgb image: ", scene["camera"].data.output["rgb"].shape)
157 print("Received shape of depth image: ", scene["camera"].data.output["distance_to_image_plane"].shape)
158 print("-------------------------------")
159 print(scene["height_scanner"])
160 print(
161 "Received max height value: ",
162 torch.max(scene["height_scanner"].data.ray_hits_w.torch[..., -1]).item(),
163 )
164 print("-------------------------------")
165 print(scene["contact_forces"])
166 print("Received max contact force of: ", torch.max(scene["contact_forces"].data.net_normal_forces_w).item())
167
168
169def main():
170 """Main function."""
171
172 # Configure the simulation
173 sim_cfg = sim_utils.SimulationCfg(
174 physics=OvPhysxCfg(),
175 dt=0.005,
176 device=args_cli.device,
177 )
178 # Launch the simulator runtime that the configuration needs
179 scene_cfg = SensorsSceneCfg(num_envs=args_cli.num_envs, env_spacing=2.0)
180 with launch_simulation(SimpleNamespace(sim=sim_cfg, scene=scene_cfg), args_cli):
181 # Initialize the simulation context
182 sim = sim_utils.SimulationContext(sim_cfg)
183 # Set main camera
184 sim.set_camera_view(eye=[3.5, 3.5, 3.5], target=[0.0, 0.0, 0.0])
185 # Design scene
186 scene = instantiate(scene_cfg)
187 # Play the simulator
188 sim.reset()
189 # Now we are ready!
190 print("[INFO]: Setup complete...")
191 # Run the simulator
192 run_simulator(sim, scene)
193
194
195if __name__ == "__main__":
196 # run the main function
197 main()
The Code Explained#
Similar to the previous tutorials, where we added assets to the scene, the sensors are also added
to the scene using the scene configuration. All sensors inherit from the sensors.SensorBase class
and are configured through their respective config classes. Each sensor instance can define its own
update period, which is the frequency at which the sensor is updated. The update period is specified
in seconds through the sensors.SensorBaseCfg.update_period attribute.
Depending on the specified path and the sensor type, the sensors are attached to the prims in the scene. They may have an associated prim that is created in the scene or they may be attached to an existing prim. For instance, the camera sensor has a corresponding prim that is created in the scene, whereas for the contact sensor, activating the contact reporting is a property on a rigid body prim.
In the following, we introduce the different sensors we use in this tutorial and how they are configured.
For more description about them, please check the sensors module.
Camera sensor#
A camera is defined using the sensors.CameraCfg. It is based on the USD Camera sensor and
the different data types are captured using Omniverse Replicator API. Since it has a corresponding prim
in the scene, the prims are created in the scene at the specified prim path.
The configuration of the camera sensor includes the following parameters:
spawn: The type of USD camera to create. This can be eitherPinholeCameraCfgorFisheyeCameraCfg.offset: The offset of the camera sensor from the parent prim.data_types: The data types to capture. This can bergb,distance_to_image_plane,normals, or other types supported by the USD Camera sensor.
To attach an RGB-D camera sensor to the head of the robot, we specify an offset relative to the base
frame of the robot. The offset is specified as a translation and rotation relative to the base frame,
and the convention in which the offset is specified.
In the following, we show the configuration of the camera sensor used in this tutorial. We set the
update period to 0.1s, which means that the camera sensor is updated at 10Hz. The prim path expression is
set to {ENV_REGEX_NS}/Robot/base/front_cam where the {ENV_REGEX_NS} is the environment namespace,
"Robot" is the name of the robot, "base" is the name of the prim to which the camera is attached,
and "front_cam" is the name of the prim associated with the camera sensor.
camera = CameraCfg(
renderer_cfg=OVRTXRendererCfg(),
prim_path="{ENV_REGEX_NS}/Robot/base/front_cam",
update_period=0.1,
height=480,
width=640,
data_types=["rgb", "distance_to_image_plane"],
spawn=sim_utils.PinholeCameraCfg(
focal_length=24.0, focus_distance=400.0, horizontal_aperture=20.955, clipping_range=(0.1, 1.0e5)
),
offset=CameraCfg.OffsetCfg(pos=(0.510, 0.0, 0.015), rot=(0.5, -0.5, 0.5, -0.5), convention="ros"),
)
Camera sensors need the simulator’s rendering extensions, also when running without a visualizer.
launch_simulation() enables them automatically when the configuration it is given contains a
camera. Since this script passes only the simulation configuration and the camera lives in the scene
configuration, the script requests camera rendering explicitly after parsing its arguments:
args_cli = parser.parse_args()
# The scene has a camera sensor, which requires the rendering extensions in headless launches.
args_cli.enable_cameras = True
Height scanner#
The height-scanner is implemented as a virtual ray-casting sensor. Through the
sensors.RayCasterCfg, we specify the ray pattern. PhysX-based backends
cast against the configured meshes, while Newton casts against its live scene
BVH and ignores the mesh list. The ray caster tracks the existing prim selected by
prim_path; it does not spawn a new USD prim.
For this tutorial, the ray-cast based height scanner is attached under the base frame of the robot.
The pattern of rays is specified using the pattern_cfg attribute. For
a uniform grid pattern, we specify the pattern using GridPatternCfg.
Since we only care about the height information, we do not need to consider the roll and pitch
of the robot. Hence, we set the ray_alignment to “yaw”.
For the height-scanner, you can visualize the points where the rays hit the mesh. This is done
by setting the debug_vis attribute to true.
The entire configuration of the height-scanner is as follows:
height_scanner = RayCasterCfg(
prim_path="{ENV_REGEX_NS}/Robot/base",
update_period=0.02,
offset=RayCasterCfg.OffsetCfg(pos=(0.0, 0.0, 20.0)),
ray_alignment="yaw",
pattern_cfg=patterns.GridPatternCfg(resolution=0.1, size=[1.6, 1.0]),
debug_vis=True,
mesh_prim_paths=["/World/defaultGroundPlane"],
)
Contact sensor#
Contact sensors wrap around the PhysX contact reporting API to obtain the contact information of the robot
with the environment. Since it relies of PhysX, the contact sensor expects the contact reporting API
to be enabled on the rigid bodies of the robot. This can be done by setting the
activate_contact_sensors to true in the asset configuration.
Through the sensors.ContactSensorCfg, it is possible to specify the prims for which we want to
obtain the contact information. Additional flags can be set to obtain more information about
the contact, such as the contact air time, contact forces between filtered prims, etc.
In this tutorial, we attach the contact sensor to the feet of the robot. The feet of the robot are
named "LF_FOOT", "RF_FOOT", "LH_FOOT", and "RH_FOOT". We pass a Regex expression
".*_FOOT" to simplify the prim path specification. This Regex expression matches all prims that
end with "_FOOT".
We set the update period to 0 to update the sensor at the same frequency as the simulation. Additionally, for contact sensors, we can specify the history length of the contact information to store. For this tutorial, we set the history length to 6, which means that the contact information for the last 6 simulation steps is stored.
The entire configuration of the contact sensor is as follows:
contact_forces = ContactSensorCfg(
prim_path="{ENV_REGEX_NS}/Robot/.*_FOOT", update_period=0.0, history_length=6, debug_vis=True
)
Running the simulation loop#
Similar to when using assets, the buffers and physics handles for the sensors are initialized only
when the simulation is played, i.e., it is important to call sim.reset() after creating the scene.
# Play the simulator
sim.reset()
Besides that, the simulation loop is similar to the previous tutorials. The sensors are updated as part of the scene update and they internally handle the updating of their buffers based on their update periods.
The data from the sensors can be accessed through their data attribute. As an example, we show how
to access the data for the different sensors created in this tutorial:
# print information from the sensors
print("-------------------------------")
print(scene["camera"])
print("Received shape of rgb image: ", scene["camera"].data.output["rgb"].shape)
print("Received shape of depth image: ", scene["camera"].data.output["distance_to_image_plane"].shape)
print("-------------------------------")
print(scene["height_scanner"])
print(
"Received max height value: ",
torch.max(scene["height_scanner"].data.ray_hits_w.torch[..., -1]).item(),
)
print("-------------------------------")
print(scene["contact_forces"])
print("Received max contact force of: ", torch.max(scene["contact_forces"].data.net_normal_forces_w).item())
The Code Execution#
Now that we have gone through the code, let’s run the script and see the result:
uv run --extra ov python scripts/tutorials/04_sensors/add_sensors_on_robot.py --num_envs 2 --viz newton_rtx
This command should open a stage with a ground plane, lights, and two quadrupedal robots. Around the robots, you should see red spheres that indicate the points where the rays hit the mesh. Additionally, you can switch the viewport to the camera view to see the RGB image captured by the camera sensor. Please check here for more information on how to switch the viewport to the camera view.
To stop the simulation, you can either close the window, or press Ctrl+C in the terminal.
While in this tutorial, we went over creating and using different sensors, there are many more sensors
available in the sensors module. We include minimal examples of using these sensors in the
scripts/tutorials/04_sensors directory. For completeness, these scripts can be run using the
following commands:
# Frame Transformer
uv run --extra ov python scripts/tutorials/04_sensors/run_frame_transformer.py --viz newton_rtx
# Ray Caster
uv run --extra ov python scripts/tutorials/04_sensors/run_ray_caster.py --viz newton_rtx
# Ray Caster Camera
uv run --extra ov python scripts/tutorials/04_sensors/run_ray_caster_camera.py --viz newton_rtx
# USD Camera
uv run --extra ov python scripts/tutorials/04_sensors/run_usd_camera.py --viz newton_rtx