This example shows you how to generate and build a standalone ROS 2 node from a Simulink® model. You configure a model to generate C++ code for a standalone ROS 2 node. Then, build and run the ROS 2 node on your host computer.
This example requires Simulink Coder™ and Embedded Coder™.
See Virtual Machine with ROS 2 Bouncy and Gazebo for instructions on setting up a simulated robot.
Review the Feedback Control of a ROS-enabled Robot over ROS 2 example.
See ROS 2 Model Build Failure in ROS Simulink Support and Limitations.
Configure a model to generate C++ code for a standalone ROS 2 node. The model is the proportional controller introduced in the Feedback Control of a ROS-enabled Robot over ROS 2 example.
Open the robot feedback control model configured for ROS 2. Alternatively, call
Under Robot tab, click Hardware settings. In the Hardware implementation pane, Hardware board settings section contains settings specific to the generated ROS 2 package, such as information to be included in the
package.xml file. Change Maintainer name to
ROS 2 Example User.
The model requires variable-sized arrays. To enable this option, check variable-size signals under Code Generation > Interface > Software environment.
In the Solver pane, ensure that Solver Type is set to Fixed-step, and set Fixed-step size to
0.05. In generated code, the Fixed-step size defines the actual time step, in seconds, that is used for the model update loop (see Execution of Code Generated from a Model (Simulink Coder)). It can be made smaller (e.g., 0.001 or 0.0001) but for current purposes 0.05 is sufficient.
In this task, you generate code for a standalone ROS 2 node, and automatically build, and run it on the host computer.
In MATLAB®, change the current folder to a location where you have write permission.
Under the Simulation tab, in Prepare, select ROS Toolbox > ROS Network.
Set the Domain ID (ROS 2) of ROS 2 network. This example uses Domain ID as 25.
In Robot tab, from the Deploy section dropdown, click Build & Run. If you get any errors about bus type mismatch, close the model, clear all variables from the base MATLAB workspace, and re-open the model. Click on the View Diagnostics link at the bottom of the model toolbar to see the output of the build process.
Once the code generation completes, the ROS 2 node builds in the present working folder starts to run automatically. When running in Windows®, a Command window opens. Do not close the window, but use Ctrl+C to shutdown the ROS 2 node.
ros2 node to list all running nodes is the ROS 2 network.
robotControllerROS2 should be in the displayed list of nodes.
Verify that the deployed node publishes data on the ROS 2 topic,
/cmd_vel, to control the motion of simulated robot.