Robot Manipulation Using MoveIt 2
local graph
Chapter 9 — Robot Manipulation Using MoveIt 2
Section titled “Chapter 9 — Robot Manipulation Using MoveIt 2”In previous chapters, we covered designing and simulating a robotic arm and controlling it using Gazebo. Now, we’ll dive into the arm motion planning problem. Manually controlling a robot’s joints, especially with position or speed limits, can be tricky, since when we control a robot by joints, each joint movement affects the whole structure, making precise positioning of its end-effector hard. That’s why we need an automated way to safely manage the robot’s movements. To do this, we’ll use ROS MoveIt 2, a powerful toolkit in ROS 2 designed to perform robot manipulation tasks. MoveIt 2 simplifies tasks such as motion planning with kinematic models, obstacle detection, and trajectory planning. It offers both a command-line interface and an easy-to-use GUI for adding new robots, plus an RViz2 plugin for planning movements right within the RViz2 environment. Finally, we’ll discuss how to plan motions and avoid obstacles using the MoveIt C++ wrapper.
Manipulation is one of the most complex problems of robotics, since it involves different elements, including collision avoidance, trajectory planning, perception, and trajectory execution. Solving this problem also requires good mathematical knowledge to implement the algorithm moving the robot. Using a tool that helps developers to accomplish this task is fundamental to implementing advanced robotic applications.
Here’s a list of the main topics that will be covered in the chapter:
- Introduction to MoveIt 2
- Preparing the robot model to use MoveIt 2
- Configuring new robots for MoveIt 2
- Testing MoveIt 2 using RViz2
- Motion planning using the
move_groupROS 2 wrapper - Planning with obstacles
- Detecting obstacles using a depth sensor
Technical requirements
Section titled “Technical requirements”To follow this chapter, you need the following requirements:
- A standard computer running the Ubuntu 24.04 LTS operating system
- A Linux machine with a ROS 2 Jazzy installed or with a running Docker container configured as discussed in Chapter 2
The reference code for this chapter can be found in the Chapter09 folder of the following code repository: https://github.com/PacktPublishing/Mastering-ROS-2-for-Robotics-Programming/tree/main/Chapter09.
Introduction to MoveIt 2
Section titled “Introduction to MoveIt 2”Before starting programming MoveIt 2, let’s discuss its basic components and its architecture. Understanding the architecture of MoveIt 2 is crucial for effectively programming and interfacing a robot with the system. We will briefly review the architecture and key concepts of MoveIt before diving into robot interfacing and programming. You can explore the complete MoveIt 2 architecture on the MoveIt 2 website: https://moveit.picknik.ai/main/doc/concepts/concepts.html.
MoveIt 2 system architecture
Section titled “MoveIt 2 system architecture”The move_group node is the core of MoveIt 2, integrating robot components and providing actions and services based on user commands. It retrieves robot data (such as kinematics) from URDF, SRDF, and configuration files. Once set up, users can command MoveIt 2 through C++, Python, or RViz2. The move_group node connects functionalities via plugins, sending planned trajectories to the robot’s controllers through the FollowJointTrajectoryAction interface. It relies on external data, using the /joint_states topic for current joint positions and connecting to robot controllers to move motors. It also uses the ROS 2 Tf framework to manage frame relationships. MoveIt 2 uses various motion planning algorithms, mainly from the Open Motion Planning Library (OMPL), which includes sample-based planners such as RRT. MoveIt 2 supports mainly sample-based planners, designed for complex environments and large planning spaces, where planning in six dimensions (position and orientation) can be slow with optimal planners.
Sampling-based planners, such as RRT and PRM, quickly find valid paths without focusing on optimality, making them suitable for real-time tasks. In contrast, optimal planners aim for the best path but are slower and require more computing power, making them less ideal for real-time applications. Let’s discuss the planning pipeline in the next section.
MoveIt 2 planning pipeline
Section titled “MoveIt 2 planning pipeline”Once MoveIt starts, it just waits for new planning requests. In this section, we will discuss how the planning process starts and is handled by the MoveIt framework with the following entities:
- Motion planning request: Defines start and goal positions and the planning constraints
- Planning scene: Represents the robot’s environment, including obstacles and constraints
- Collision detection: Ensures the planned path avoids collisions
- Kinematic model: Helps compute feasible movements for the robot
- Planner: Generates a path using algorithms such as RRT, PRM, or similar
- Trajectory post-processing: Refines the trajectory for smoothness and feasibility
- Execution: Sends commands to the robot’s controller to follow the planned path
Let’s discuss these steps in detail. A new planning process starts with the planning request. We will use a ROS 2 node with a wrapper for the move_group module. In the planning request, we must specify the start and goal states (positions, orientations, or poses of the robot’s end effector or joints), and the eventual planning constraints, such as the allowed tolerance on the final goal of the constraints on the cartesian path.
When a planning request is made, MoveIt 2 creates a planning scene, capturing the robot’s environment and current state. This scene includes the robot model and collision objects, allowing MoveIt 2 to perform collision detection and ensure the trajectory avoids obstacles and meets constraints. The system uses the robot’s kinematic model to compute forward kinematics (determining a link’s position based on joint angles) and inverse kinematics (calculating joint angles to achieve a desired end-effector position).
MoveIt 2 uses a modular architecture to integrate various planning algorithms via the Open Motion Planning Library (OMPL). Once a specific planner is selected, it generates a trajectory from start to goal while meeting constraints. The planning process involves sampling paths, checking constraints and obstacles, and optimizing the path. If a valid path cannot be found or constraints are not met, the planning process may fail.
After the planner produces an initial trajectory, MoveIt 2 can apply additional post-processing steps such as path smoothing to ensure the robot moves smoothly between waypoints, time parameterization to adjust velocities and accelerations to match the robot’s capabilities and dynamic constraints (e.g., maximum joint speeds), and interpolation to add intermediate waypoints for finer control. Once the final trajectory is planned, it is passed to the controller for execution. The execution phase involves the following:
- Converting the planned trajectory into motor commands that the robot’s actuators can follow
- Using feedback (from joint sensors, cameras, etc.) to make real-time adjustments if necessary
- Ensuring the robot adheres to the planned path and avoids any dynamic obstacles that may have appeared after the planning phase
Finally, during execution, MoveIt 2 monitors the robot’s progress, checking that the actual trajectory matches the planned one. If discrepancies or errors are detected (e.g., dynamic obstacles or collisions), the pipeline can trigger a re-planning process or halt the execution.
Now that the basic elements of MoveIt 2 have been introduced, we are ready to put them into practice by integrating it with a simulated robot in Gazebo. First, let’s start to prepare a robot model to be controlled with ROS 2.
Preparing the robot model to use MoveIt 2
Section titled “Preparing the robot model to use MoveIt 2”In this chapter, we will use the Gazebo simulator to test MoveIt 2. We’ll prepare the Panda robot model, developed by Franka Emika, which is a versatile arm with 7 degrees of freedom and sensors for force and torque control. The Panda’s integration with MoveIt 2 and ROS 2 facilitates advanced motion planning, kinematics, and real-time communication, making it suitable for research and industrial applications.
The robot model is implemented in the panda_robot package, which can be downloaded from the GitHub repository of the book. It consists of a set of xacro files to define the robot structure. To enable communication between MoveIt 2 and the robot model, the following steps must be taken.
Step 1 – Adding robot controllers
Section titled “Step 1 – Adding robot controllers”As already discussed in Chapter 6, to actuate a simulated robot model, the gz_ros2_control plugin must be integrated into the robot model. Let’s edit the panda.urdf.xacro and panda_arm.xacro files in the following way:
- Add the controller plugins in
panda.urdf.xacro:<gazebo><plugin filename="gz_ros2_control-system" name="gz_ros2_control::GazeboSimROS2ControlPlugin"> - This plugin requires as input the controller configuration file. Let’s create this file in the config folder of the
panda_descriptionpackage. Later in this section, we will discuss the content of this file:<parameters>$(find panda_description)/config/ros2_controllers.yaml</parameters> - Add the
ros2_controltag to thepanda_arm.xacrofile. Within this tag, we must include a name that is arbitrary and a type, which must be"system":<ros2_control name="IgnitionSystem" type="system"> - The hardware interface of the simulation of the
ros2_controltag is the one to be used in the Gazebo simulation:<hardware><plugin>gz_ros2_control/GazeboSimSystem</plugin></hardware> - In this section, we must specify the command and the state interfaces for each arm. In the current example, the joints are controlled in position, while the position and the velocity are included in the state. The robot model has eight joints (
joint1,…,joint8) plus two joints for the gripper. We will report here the configuration only for the first joint:controller_manager:ros__parameters:update_rate: 100arm_controller:type: joint_trajectory_controller/JointTrajectoryControllerarm_controller:ros__parameters:joints:- joint1...command_interfaces:- positionstate_interfaces:- position- velocity
Now we must start the robot simulation with the controllers. To do this, we can use a launch file to start the simulation and the controllers.
Step 2 – Enabling the controllers from the launch file
Section titled “Step 2 – Enabling the controllers from the launch file”To start the simulation with the controllers provided, a convenient launch file is needed. The main elements of this file are discussed in the following:
- Configure the environment to find the meshes of the Panda robot. To do this, the
GZ_SIM_RESOURCE_PATHenvironment variable must be set to the location where the robot meshes are included. Of course, the files are placed in theinstallfolder of the ROS 2 workspace:workspace_path = os.environ.get('COLCON_PREFIX_PATH') or os.environ.get('AMENT_PREFIX_PATH')pkg_panda_description = workspace_path + "/panda_description/share" - The
SetEnvironmentVariablefunction of the Python launch file is used to export the variable to a desired value:gz_resource_path = SetEnvironmentVariable(name='GZ_GAZEBO_RESOURCE_PATH',value=[pkg_panda_description] - Configure the controller to start it in an active state using
ExecuteProcessin the launch file:load_position_controller = ExecuteProcess(cmd=['ros2', 'control', 'load_controller', '--set-state', 'active', 'arm_controller'], output='screen') - Now everything is ready to start the Gazebo simulation. Let’s compile the workspace, source it, and launch the simulator:
$ colcon build --symlink-install$ source install/setup.bash$ ros2 launch panda_description panda_gazebo.launch.py
After Gazebo starts, the simulation scene will appear as shown in Figure 9.1. In this example, the initial value of the joints set in the ros2 control tag is the following: [0.0, -0.78, 0.0, -2.35, 0.0, 1.57, 0.78].

Figure 9.1: The Panda robot created in the simulation scene
Figure 9.1: The Panda robot created in the simulation scene
Now that the robot is ready to work with MoveIt 2, we must create the proper configuration files. We can do this by using the MoveIt Setup Assistant, as discussed in the next section.
Configuring new Robots for MoveIt 2
Section titled “Configuring new Robots for MoveIt 2”Before starting the robot configuration, we must properly install MoveIt 2 in our system. In fact, MoveIt 2 is not installed with the full installation of ROS 2. So, to use the MoveIt 2 package, install it using the following:
$ sudo apt -get install ros-jazzy-moveitMoveIt 2 is continuously updated, and sometimes the version available in the Ubuntu repository may be older than the latest MoveIt release. If the repository version has any bugs, you may have to wait for the next repository update for them to be resolved. Therefore, it’s often better to download and compile the latest MoveIt 2 version directly from the GitHub repository. Use the following commands to do so. First, move into the source directory of the ROS 2 workspace and download MoveIt 2:
cd ros2_ws/srcgit clone https://github.com/moveit/moveit2.gitThen, install the dependencies. The next commands will download new packages in your workspace:
for repo in moveit2/moveit2.repos $(f="moveit2/moveit2_$ROS_DISTRO.repos"; test -r $f && echo $f); do vcs import < "$repo"; donerosdep install -r --from-paths . --ignore-src --rosdistro $ROS_DISTRO -yFinally, compile the workspace:
colcon build --event-handlers desktop_notification- status- --cmake-args -DCMAKE_BUILD_TYPE=ReleaseNotice that the compilation could fully occupy the whole CPU, making your PC stuck. For this reason, we can fix the number of parallel threads started during the compilation using the --parallel-workers NUMBER option:
colcon build --event-handlers desktop_notification- status- --cmake-args -DCMAKE_BUILD_TYPE=Release --parallel-workers 1After installing MoveIt 2, we are now ready to configure the Panda robot discussed in the previous section to work with it and implement ROS 2 nodes or configure new robots. To configure new robots, we can use the MoveIt Setup Assistant tool. It is a graphical interface designed to configure any robot for MoveIt 2. This tool generates essential files, including the SRDF, configuration files, launch files, and scripts, based on the robot’s URDF model and our configuration. To launch the MoveIt Setup Assistant, use this command:
$ ros2 launch moveit_setup_assistant setup_assistant.launch.pyThis command opens a window with two options: Create New MoveIt Configuration Package and Edit Existing MoveIt Configuration Package, as shown in Figure 9.2. Since we’re creating a new package, select the first option. If you already have a MoveIt package, choose the second option. Next, click on Create New MoveIt Configuration Package, and use the browse button to locate and select the URDF file. Navigate to panda_description/urdf/panda.urdf.xacro, select it, and then click Load to import the URDF file.

Figure 9.2: Regenerating the Self-Collision matrix
Figure 9.2: Regenerating the Self-Collision matrix
You can now navigate through the panels to configure your robot:
- Self-Collisions: MoveIt optimizes collision checking by categorizing robot links as always, never, or sometimes in collision, and disabling pairs prone to collisions. The Self-Collisions window lets you adjust sampling density, balancing computation, and collision detection, with a default of 10,000 samples.
Clicking Regenerate Default Collision Matrix updates the list of disabled link pairs. This panel is shown in Figure 9.3:

Figure 9.3: MoveIt 2 Setup Assistant
Figure 9.3: MoveIt 2 Setup Assistant
- Virtual joints: Virtual joints connect the robot to the world and are necessary when the robot’s base position isn’t fixed. For static robots that don’t move, virtual joints aren’t required. However, if a robot arm is mounted on a mobile base, a virtual joint should be defined relative to the odometry frame.
- Planning groups: To create a planning group for a robotic arm, navigate to the Planning Groups tab and click Add Group. Planning groups represent a fundamental element of MoveIt, grouping joints and links of the robot model to define a subset of the robot for which motion planning should be performed. For example, in a robot with multiple arms, each arm might be a separate planning group.
To add a new planning group, in the window that opens (Figure 9.4, left), name the group arm and set Kinematic Solver to kdl_kinematics_plugin/KDLKinematicsPlugin. Leave the other parameters at their default values. You can add elements to the group by specifying joints, links, or a kinematic chain. For the arm group, add a kinematic chain from base_link to grasping_frame.
Once created, the planning group will appear in the list (Figure 9.4, right).

Figure 9.4: MoveIt 2 planning group
Figure 9.4: MoveIt 2 planning group
- Robot poses: Here, you can define fixed poses for the robot, such as home or pick/place positions. These fixed poses, or group states, can be directly used in MoveIt APIs, simplifying tasks such as pick/place and grasping operations by allowing the robot to switch to these positions easily. Notice that inserting such poses could be not trivial since they must be specified by including the joint values.
- End Effectors: In this step, name the robot’s end effector and assign it to the end-effector group, parent link, and parent group. For our gripper used in pick and place operations, click Add End Effector, name it
eef, and set the planning group toeef, and the parent link tohand. - Passive joints: In this step, specify the passive joints in the robot. Passive joints are those without actuators and are used to connect different parts of the robot. The Panda robot doesn’t have passive joints.
- ros2_control and ROS 2 Controllers: This panel guides you to modify the URDF of the robot to integrate the robot controllers. However, we already discussed these steps in the previous section, so you can jump these steps.
- Author Information: The name and contact information of the developer configuring the robot are added in this tab. In this way, you can distribute your robot configuration package to the ROS 2 community.
- Perception: in this tab, we can configure the robot with sensor information to perceive the obstacles of the environment, such as depth sensors or point cloud data. We will discuss how to configure this panel later.
- Configuration files: In this final step, you will generate the configuration files needed for MoveIt, as shown in Figure 9.5. Click the Browse button to choose a folder where the configuration package will be saved. The files will be created in a folder named
panda_moveit_config. Click Generate Package to create a ROS 2 package containing the configuration files that will be placed in the selected folder. Once the process is complete, you can click Exit Setup Assistant to close the tool. Of course, it is important to have the package in the ROS 2 workspace, so export it directly to the correct location.
Figure 9.5: Generating a MoveIt configuration package
Figure 9.5: Generating a MoveIt configuration package
Now, we have everything needed to run MoveIt to plan and execute robot trajectories. First, we will test the generated file using RViz2 before implementing ROS 2 nodes using MoveIt 2 APIs.
Testing MoveIt 2 using Rviz2
Section titled “Testing MoveIt 2 using Rviz2”MoveIt 2 provides a plugin for RViz2, which can be used to monitor the robot’s state and the environment and allows users to easily make new planning requests and preview the planned motions. After generating the configuration files of the robot to interface it with MoveIt, we can use this plugin to test the robot’s motion. First, start the simulation to activate the controllers:
ros2 launch panda_description panda_gazebo.launch.pyThen, use the demo launch file contained in the panda_moveit_config package:
ros2 launch panda_moveit_config demo.launch.pySet the simulation time to true:
ros2 param set /move_group use_sim_time trueIf everything works fine, we will see the following screen of RViz2 being loaded with the MotionPlanning plugin provided by MoveIt 2, as shown in Figure 9.6. Here, you have a planning panel (bottom left) that can be used to set up the motion planning problem.

Figure 9.6: Generating a MoveIt configuration package
Figure 9.6: Generating a MoveIt configuration package
You can set the robot’s start and goal states in the Query panel. After setting these states, use the Plan button to calculate a path from the start to the goal. If planning is successful, you can execute the path. By default, execution occurs on emulated, fake controllers for visualization in RViz2. To adjust the start and goal positions of the robot’s end effector, use the interactive marker attached to the arm gripper. You can translate and rotate this marker. If a valid plan is found, the arm will be highlighted in orange. If the arm does not move or reach the marker’s position, it indicates that no inverse kinematics (IK) solution exists for that pose. This might be due to insufficient degrees of freedom (DOF) or a collision between links.
Moving the robot using RViz2 is useful to quickly test the MoveIt 2 configuration files. However, to implement an autonomous robotic program, we must incorporate MoveIt system calls into ROS 2 nodes, as discussed in the next section.
Motion planning using the move_group ROS 2 wrapper
Section titled “Motion planning using the move_group ROS 2 wrapper”In this section, we will see how to program the robot’s motion using the move_group wrapper implemented in C++. The first step is to create another ROS package that has the MoveIt packages as dependencies. You can get an existing panda_moveit_control package from the code provided with this book, or you can download it from the following repository: https://github.com/PacktPublishing/Mastering-ROS-2/tree/main/Chapter09.
To create the package from scratch instead, use the following command:
ros2 pkg create panda_moveit_control --dependencies moveit_ros_planning_interface rclcppIn the first example, we will use the move group wrapper to execute a motion in the joint space. This means the desired robot configuration is set, specifying the value of each single joint of the robot. This motion has the advantage of being simpler to implement and more computationally efficient because it directly plans in the robot’s joint space. However, it has the downside of not providing direct control over the robot’s path in Cartesian space, which can result in unexpected or inefficient movements.
To implement joint space motion control, the following steps must be taken.
Step 1 – Implementing the ROS 2 node
Section titled “Step 1 – Implementing the ROS 2 node”Let’s add new source code to the src folder of the panda_moveit_control package (joint_space_planning.cpp). The main code blocks contained in this node are explained in the following:
- Let’s start by including the header files. Here, we just include the interface with
move_group:#include <moveit/move_group_interface/move_group_interface.h> - In the
mainfunction, after initializing the ROS 2 library, a new ROS 2 node is declared:rclcpp::init(argc, argv);moveit::planning_interface::MoveGroupInterface::Plan my_plan;auto node = rclcpp::Node::make_shared("JointSpacePlanning"); - To control the robot, the planning module must be initialized, thanks to the
MoveGroupInterfaceobject. Then, we hardcode a set of desired values for the robot joints:moveit::planning_interface::MoveGroupInterface move_group(node, "arm");std::vector<double> des_joint_pos = {0.0, 0.0, 0.0, -0.35, 0.0, 1.57, 0.78}; - The plan structure is used to store the result of a
planningrequest:moveit::planning_interface::MoveGroupInterface::Plan my_plan; - Then, we will set the target of the joint using the desired one. After it’s set, we can also check whether the desired values violate the joint limits:
bool within_bounds = move_group.setJointValueTarget( des_joint_pos)
- Finally, we call the planner to compute the plan. Note that we are just planning, not asking
move_groupto move the robot. We can additionally check whether the planning phase has succeeded or not:bool success = (move_group.plan(my_plan) == moveit::core::MoveItErrorCode::SUCCESS); - After generating the plan, if the planning phase was completed successfully, we can move the robot by using the
movefunction. Note that this is a blocking function released only after the robot motion is completed:If (success) move_group.move();
Step 2 – Creating the launch file
Section titled “Step 2 – Creating the launch file”A common way to share the MoveIt configuration file with the ROS 2 node is by using launch files. Let’s do it to test the joint space planning program:
- Create a launch file, called
joint_space_planning.launch.py, place it into the launch directory of thepanda_moveit_controlnode, and add the following content to it. Here, themoveit_config_utilsmodule is imported to load the configuration file:from moveit_configs_utils import MoveItConfigsBuilder - The configuration files related to the Panda robot are stored in the
moveit_configvariable:def generate_launch_description():moveit_config = MoveItConfigsBuilder("panda").to_moveit_configs() - The definition of the
joint_space_planningnode is completed with some parameters: the ones related to themoveitconfiguration anduse_sim_time parameterset toTrue. This last parameter is fundamental to retrieving the state of the robot using the ROS 2 API:joint_planning_node = Node( package="panda_moveit_control", executable="joint_space_planning", output="screen",parameters=[ {"use_sim_time": True},moveit_config.robot_description,moveit_config.robot_description_semantic,moveit_config.robot_description_kinematics,])
Step 3 – Filling the CMakeFile.txt
Section titled “Step 3 – Filling the CMakeFile.txt”In this step, we must simply install the source and configuration files, as shown in the following:
add_executable( joint_space_planning src/joint_space_planning.cpp )ament_target_dependencies(joint_space_planning rclcpp std_msgs moveit_ros_planning_interface)install(DIRECTORY launch DESTINATION share/${PROJECT_NAME})install(TARGETS joint_space_planning RUNTIME DESTINATION lib/${PROJECT_NAME} )Step 4 – Compiling and executing the planning node
Section titled “Step 4 – Compiling and executing the planning node”A sequence of commands is used to compile and start the simulation and MoveIt 2. Optionally, you can also open Rviz2 to check the robot’s state:
- Let’s start by compiling the workspace:
$ colcon build --symlink-install$ source install/setup.bash
- Start the Gazebo simulation:
$ ros2 launch panda_description panda_gazebo.launch.py
- Start MoveIt 2:
$ ros2 launch panda_moveit_config move_group.launch.py
- Set the
use_sim_timevariable totruefor themove_groupnode. Without this, the MoveIt planning system will not be able to retrieve the information shared via the ROS 2 system:$ ros2 param set move_group use_sim_time true - Start the joint space planning node:
$ ros2 launch panda_moveit_control joint_space_planning.launch.py
After executing this command, the robot is actuated and reaches the configuration specified by the joint commands (as depicted in Figure 9.7). Let’s now discuss another example in which the motion trajectory is in the Cartesian space.
Cartesian space planning
Section titled “Cartesian space planning”Cartesian space planning provides precise control over a robot’s path, ensuring the end-effector follows a specific trajectory. This results in smoother motion for the robot end effector and easier obstacle avoidance. However, it is more complex and computationally demanding due to the need for inverse kinematics to convert Cartesian paths into joint movements. MoveIt 2’s move group wrapper can facilitate this type of motion.
Let’s discuss the main elements of the cartesian_space_planning.cpp code contained in the panda_moveit_control package:
- In this example, we perform the planning and execution phase in a class function, to additionally show the object-oriented formulation. Let’s define the main class. Apart from the class functions, a ROS 2 node pointer object is defined:
class CartesianPlanning : public rclcpp::Node {public:CartesianPlanning() : Node("cartesian_planning") {}void run();void plan();private:rclcpp::Node::SharedPtr _node;
- In the
runandmainfunctions, we set all the variables needed to start the planning function. The latter is started as a separate thread:void CartesianPlanning::run() {auto node = rclcpp::Node::make_shared("CartesianPlan");_node = node;std::thread cartesian_plan_t( &CartesianPlanning::plan, this);rclcpp::spin(node);}int main(int argc, char * argv[]) {rclcpp::init(argc, argv);CartesianPlanning cp;cp.run();return 0:} - The desired path will be a displacement from the current position: 20 cm down, 20 cm on the left, and 20 cm to the top, left, and back. For this reason, the first thing is to retrieve the current pose of the planning frame. We can use the
tfsystem to retrieve this information:bool tf_found = false;geometry_msgs::msg::TransformStamped t;auto tf_buffer {std::make_unique<tf2_ros::Buffer>(this->get_clock())};auto tf_listener { std::make_shared<tf2_ros::TransformListener>(*tf_buffer)}; - The planning interface is initialized and used to retrieve the information about the planning frame (the base frame of the robot) and the end effector frame of the robot that we want to control:
moveit::planning_interface::MoveGroupInterface move_group(_node, "arm");std::string fromFrameRel = move_group.getPlanningFrame();std::string toFrameRel = move_group.getEndEffectorLink();
- Then we search for the pose of the end effector frame with respect to the grasping frame. We iterate this process until the
tfhas been found:t = tf_buffer->lookupTransform(fromFrameRel, toFrameRel, tf2::TimePointZero);tf_found = true; - After retrieving the current pose, we save it into
Posedata. Then, we can add slight displacement to define the desired motion:geometry_msgs::msg::Pose target_pose;std::vector<geometry_msgs::msg::Pose> waypoints;target_pose.orientation.w = t.transform.rotation.w; target_pose.orientation.x = t.transform.rotation.x; target_pose.orientation.y = t.transform.rotation.y;target_pose.orientation.z = t.transform.rotation.z; target_pose.position.x = t.transform.translation.x; target_pose.position.y = t.transform.translation.y;target_pose.position.z = t.transform.translation.z;waypoints.push_back(target_pose);target_pose.position.z -= 0.2;waypoints.push_back(target_pose);target_pose.position.y -= 0.2;waypoints.push_back(target_pose);target_pose.position.z += 0.2;target_pose.position.y += 0.2;target_pose.position.x -= 0.2;waypoints.push_back(target_pose); - We can specify the interpolation of the generated Cartesian path. In this case, we chose 1 cm. In addition, we can specify the jump threshold, which limits the maximum distance or jump in joint positions between two consecutive trajectory points. In this example, we are disabling it by setting it to 0. Notice that disabling this parameter on the real system could be dangerous, since it could generate large, unpredictable motions for the redundant joints (redundant joints in robotics mean a robot has more joints than necessary for a task, offering extra flexibility for movement and obstacle avoidance). To plan the trajectory, the
computeCartesianPathfunction is used. This function returns a value between 0.0 and 1.0 to indicate the fraction of the path completed based on waypoints, or -1.0 if there’s an error:moveit_msgs::msg::RobotTrajectory traj;const double jump_th= 0.0;const double step = 0.01;double fraction = move_group.computeCartesianPath(waypoints, step, jump_th, traj); - Finally, we can execute the planned trajectory if the Cartesian path has been planned correctly. In particular, the
computeCartesianPathtrajectory returns three kinds of value:- 0.0 to 1.0 or -1: A value of 1.0 means the entire Cartesian path (all waypoints) was successfully planned.
- 0.0 to 1.0: A value between 0.0 and 1.0 indicates partial success (only a fraction of the waypoints were included in the trajectory).
- -1: Finally, a value of -1 indicates a failure to plan any part of the trajectory.
- 0.0 to 1.0 or -1: A value of 1.0 means the entire Cartesian path (all waypoints) was successfully planned.
In this example, we execute the planned trajectory at least for 80% of its path. You can look at the Gazebo simulation to see the resultant planned motion of the robot:
if( fraction > 0.8 )move_group.execute(traj);elseRCLCPP_ERROR(rclcpp::get_logger("moveit_executor"), "Trajectory calculation failed");After completing the source code of this node, you should edit CMakeLists.txt and create a convenient launch file, as already done in the previous example. Finally, to run this node, follow the same commands as shown in the Step 4 – Compiling and executing the planning node section. You can now compare the movements done in this example with respect to the joint space motion.

Figure 9.7: Final pose of the joint space planning motion
Figure 9.7: Final pose of the joint space planning motion
To start this demo, use the following commands:
ros2 launch panda_description panda_gazebo.launch.pyros2 launch panda_moveit_config move_group.launch.pyros2 param set move_group use_sim_time trueros2 launch panda_moveit_control cartesian_space_planning.launch.pyBuilding on the previous example, you can instruct the robot to reach new Cartesian points. However, in this case, MoveIt planned the path in an entirely obstacle-free environment. In the next section, we will discuss how to set up the environment to include obstacles.
Planning with obstacles
Section titled “Planning with obstacles”In the previous examples, the robot could move freely without considering obstacles, and the motion planner only needed to account for potential self-collisions. However, this is not realistic, as robots typically operate in environments containing objects that might collide with the robot. In this section, we’ll explore how to add objects to the planning scene that the robot must avoid or interact with. For instance, in a grasping application, once an object is grasped, it becomes part of the manipulator, requiring the planner to consider it in future trajectories.
Let’s discuss the content of the planning_with_obstacles.cpp source file contained in the panda_moveit_control package:
- In this source file, we include two additional headers to manage collision objects:
#include <moveit_msgs/msg/attached_collision_object.hpp>#include <moveit_msgs/msg/collision_object.hpp>
- Let’s now modify the previous example, adding some elements to the
CartesianPlanningclass. Rename this classPlanningWithObstacles, and add the method that is used to place two objects in the planning scene:void PlanningWithObstacles::setup_world() {moveit::planning_interface::PlanningSceneInterface planning_scene_interface; - To add an element in the scene, we must define a
CollisionObject. It has different proprieties, such as the shape, ID, name, and the position where it falls in the scene:moveit_msgs::msg::CollisionObject obstacle;obstacle.header.frame_id = _move_group->getPlanningFrame();obstacle.id = "table";shape_msgs::msg::SolidPrimitive primitive;primitive.type = primitive.BOX;primitive.dimensions.resize(3);primitive.dimensions[primitive.BOX_X] = 0.1;primitive.dimensions[primitive.BOX_Y] = 1.5;primitive.dimensions[primitive.BOX_Z] = 0.3;geometry_msgs::msg::Pose bp;bp.orientation.w = 1.0;bp.position.x = 0.48;bp.position.y = 0.0;bp.position.z = 0.25;obstacle.primitives.push_back(primitive);obstacle.primitive_poses.push_back(bp);obstacle.operation = obstacle.ADD; - The planning scene interface is used to put the object into the environment. This object is now recognized as an obstacle for each new trajectory planning task. However, we want to do something more: add an object to the robot end effector of the robot:
planning_scene_interface.applyCollisionObject (obstacle);
- Let’s define a new object that will be grasped by the robot. As in the previous case, we define a new object. However, after defining all its properties (check the full source code in the GitHub book repository), we place the object into the environment. Later, we use the
move_groupobject to attach the object to some frames of the robot:moveit_msgs::msg::CollisionObject grasping_object;planning_scene_interface.applyCollisionObject(grasping_object);std::vector<std::string> connection_links;connection_links.push_back("panda_rightfinger"); connection_links.push_back("panda_leftfinger"); _move_group->attachObject(grasping_object.id, "hand", connection_links); - Of course, these objects don’t react to any physical force, since they are not placed in the simulation but only in the planning scene. For this reason, it is not important where we place them – they can also float into the environment. After calling the
setup_worldfunction, we can continue to plan the trajectory, checking that the robot is able to avoid obstacles:std::string fromFrameRel = _move_group->getPlanningFrame().c_str();std::string toFrameRel = _move_group->getEndEffectorLink().c_str();setup_world();while ( !tf_found ) {//Get the Tf}geometry_msgs::msg::Pose target_pose;std::vector<geometry_msgs::msg::Pose> waypoints;target_pose.orientation.w = t.transform.rotation.w; target_pose.orientation.x = t.transform.rotation.x; target_pose.orientation.y = t.transform.rotation.y;target_pose.orientation.z = t.transform.rotation.z; target_pose.position.x = t.transform.translation.x; target_pose.position.y = t.transform.translation.y;target_pose.position.z = t.transform.translation.z;target_pose.position.x += 0.3;_move_group->setPoseTarget(target_pose);moveit::planning_interface::MoveGroupInterface::Plan my_plan;bool success = (_move_group->plan(my_plan) == moveit::core::MoveItErrorCode::SUCCESS);_move_group->move(); - One last modification applied to this class is that we add the
move_groupobjects to the class member of thePlanningWithObstaclesclass. This is declared as follows:moveit::planning_interface::MoveGroupInterface *_move_group;
It is initialized in the plan function:
_move_group = new moveit::planning_interface::MoveGroupInterface(_node, "arm");In this way, we can use this object in the different functions of our program, both in the plan function and in setup_world. As usual, prepare the package to install the executable and the launch file. Then you can start the node execution, monitoring what is happening from the MoveIt plugin for RViz2. The planning scene during the task execution is shown in Figure 9.8, where the robot is overcoming the obstacle, bringing with it the grasped object.

Figure 9.8: Panda robot avoiding obstacles with a grasped object
Figure 9.8: Panda robot avoiding obstacles with a grasped object
To start this demo, you must use the following commands. First, open RViz2 to visualize the scene and the robot. Add the MotionPlanning plugin using the Add button of the RViz2 user interface:
rviz2Then, start the simulator and MoveIt using the following commands on different terminals:
ros2 launch panda_description panda_gazebo.launch.pyros2 launch panda_moveit_config move_group.launch.pyros2 param set move_group use_sim_time trueros2 launch panda_moveit_control planning_with_obstacles.launch.pyWe have learned how to add obstacles with known sizes and specific positions. However, in real-world applications, obstacles are usually detected using the robot’s sensors, such as cameras or depth sensors. MoveIt 2 allows you to configure sensors that detect obstacles and create an obstacle map, enabling the robot to plan safe paths.
Now, let’s explore how to add new sensors to our MoveIt-enabled robot.
Detecting obstacles using a depth sensor
Section titled “Detecting obstacles using a depth sensor”Previously, we manually added obstacles to the virtual environment using the MoveIt 2 wrapper and planning scene. This works well when the robot’s workspace is predefined with a 3D mesh. However, in dynamic environments, sensors are needed to detect obstacles in real time. In this section, we’ll add a depth sensor to the robot model and configure MoveIt 2 to automatically create a 3D shape of the surroundings.
A depth sensor provides 3D point cloud data of the area around the robot. We’ll begin by modifying the panda_arm.xacro file to include this sensor:
- The sensor exists in the Gazebo simulator and is associated with a particular link – in our case, the first link of the robot. We are going to place the sensor at the base of the robot. The type of the sensor is
depth_camera:<gazebo reference="${prefix}${link0_name}"><sensor name='d435_depth' type='depth_camera'> - Some parameters can be added to the sensor, such as the field of view, the resolution, and similar:
<camera name='d435'>...</camera>
- To elaborate the data taken from the environment, a specific plugin is used – the
libgz-sim-sensors-system.soplugin:<plugin filename="libgz-sim-sensors-system.so" name="gz::sim::systems::Sensors"><render_engine>ogre</render_engine></plugin> - To also create the whole structure of the sensor, we use the
sensor_d435macro of therealsense2_descriptionpackage. For this reason, first include the file containing the macro and then instantiate the sensor macro:<xacro:include filename="$(find realsense2_description)/urdf/_d435.urdf.xacro" /><xacro:sensor_d435 parent="${prefix}${link0_name}" use_nominal_extrinsics="$(arg use_nominal_extrinsics)" add_plug="$(arg add_plug)" use_mesh="$(arg use_mesh)"><origin xyz="0.1 0.0 0.05" rpy="0 0.0 0" /></xacro:sensor_d435> - As usual, we must use the ROS-Gazebo bridge to share the point cloud data over the ROS 2 network. For this reason, in the
panda_gazebo_with_obstacles.launchfile, we add two additional nodes, one to map the point cloud from Gazebo to ROS 2 and another one to create a static TF to link the sensor to the kinematic robotic structure:depth_camera_bridge = Node(package='ros_gz_bridge', executable='parameter_bridge', name = 'depth_camera_bridge', output='screen',arguments =['/depth_camera' + '@sensor_msgs/msg/Image' + '[ignition.msgs.Image','/depth_camera/points' + '@sensor_msgs/msg/PointCloud2' + '[ignition.msgs.PointCloudPacked'],)depth_cam_data2cam_link_tf = Node(package='tf2_ros', executable='static_transform_publisher', name='cam3Tolink', output='log', arguments=['0.0', '0.0', '0.0', '0.0', '0.0', '0.0', 'camera_link', 'panda/link0/d435_depth'])
The following figure shows the panel of the MoveIt 2 Setup Assistant to set up the 3D vision.

Figure 9.9: Panda robot avoiding obstacles with a grasped object
Figure 9.9: Panda robot avoiding obstacles with a grasped object
- Now, even if the ROS 2 system streams data via topics, we must modify the MoveIt 2 configuration files to directly allow their integration into the planning scene. Launch the MoveIt Setup Assistant again with the following command:
$ ros2 launch moveit_setup_assistant setup_assistant.launch
- This time, you must choose just to edit an already configured MoveIt package, selecting the
panda_moveit_configpackage. After selecting the package, use the Load Files button to retrieve the robot configuration. - After the files are loaded, navigate to the Perception button and configure it as shown in Figure 9.9. Basically, here, you must select the type of data (point cloud), and information about the data to elaborate. For example, in this case, we selected the
/depth_camera/pointstopic (that is where the sensor streams the data) and other parameters to better elaborate the points. - To save the modifications and update the configuration file, navigate through the Configuration Files tab, to export the new version of the MoveIt 2 package (as shown in Figure 9.5). Now, everything is ready to detect the obstacles of the environment. Before testing our new perception system, we must add an obstacle to the simulation scene. To do this, a custom model world is placed in the world directory of the
panda_descriptionpackage (planning_world.sdf).- Here, a rectangular object is placed on the ground as shown in Figure 9.10. To load this world when the simulation starts, we can use the
panda_gazebo_with_obstacle.launch.pyfile. This file is the same as thepanda_gazebo.launch.pylaunch file except for the loading of a custom world file. First, we retrieve the path of the world file:sdf_file_path = os.path.join(FindPackageShare('panda_description').find('panda_description'), 'world', 'planning_world.sdf' )- Then, the Gazebo launch file is imported, passing the world path as an argument:
ignition_gazebo_node = IncludeLaunchDescription(PythonLaunchDescriptionSource( PathJoinSubstitution(FindPackageShare('ros_gz_sim'), 'launch', 'gz_sim.launch.py' ])),launch_arguments={'gz_args': f'-r -v 4 {sdf_file_path}'}.items())
- Here, a rectangular object is placed on the ground as shown in Figure 9.10. To load this world when the simulation starts, we can use the
- Now, start the simulation using the
panda_gazebo_with_obstacles.launch.pyfile. In RViz2 with the MoveIt plugin, you will see cubes forming around the obstacles (Figure 9.10). These cubes represent OctoMap, a 3D mapping framework that efficiently models occupied, free, and unknown spaces using an octree structure. OctoMap is widely used in robotics for environment modeling and obstacle avoidance, typically generated from point cloud data, which we will explore further in the next chapter.
Figure 9.10: OctoMap generated by MoveIt 2 using the point cloud data
Figure 9.10: OctoMap generated by MoveIt 2 using the point cloud data
Once the simulation and MoveIt 2’s move_group are running, you can begin testing how the robot avoids obstacles, such as how it handles virtual objects in the planning scene. Another method for obstacle avoidance in MoveIt involves processing point cloud data to generate collision objects and adding them to the planning scene. This approach can improve planning performance.
Summary
Section titled “Summary”In this chapter, we explored the different capabilities of MoveIt 2, a motion planning framework integrated with ROS 2 that allows developers to implement manipulation operations with industrial arms. MoveIt 2 already supports different models of popular robots, however, new robots can be configured to properly work with it thanks to an intuitive setup assistant that drives the user to create all the necessary configuration files to plan and execute desired motion trajectories.
We started the chapter by discussing the main concepts of MoveIt 2 and then showed how to configure a new simulated robot to properly work with it. Finally, we showed how to create C++ ROS 2 nodes to implement plans and execute obstacle-free motion trajectories, which is the main usage of industrial manipulators.
In the next chapter, we will move on to how to use ROS 2 to implement perception algorithms, implement image elaboration algorithms, and work with 3D point cloud data.