Main Content

Call ROS 2 Service in Simulink

This example shows how to call a service on the ROS 2 network in Simulink® using the Call Service block and receive a response.

Set Up ROS 2 Network and Service Server

Create a sample ROS 2 network with one node.

node_1 = ros2node(exampleHelperCreateRandomNodeName);

Create a service that adds two integers using the existing service type example_interfaces/AddTwoInts. Specify the callback function to be exampleHelperROS2SumCallback which performs the addition of numbers in the a and b fields of the service request message.

sumserver = ros2svcserver(node_1,"/sum","example_interfaces/AddTwoInts",@exampleHelperROS2SumCallback);

Call Service Server from Simulink

Open the Simulink model with the Call Service block. Use the Blank Message block to output a request message with the example_interfaces/AddTwoIntsRequest message type. Populate the bus with two values to sum together. You can ignore warnings about converting data types.

Add Two Ints ROS 2 Service Model

open_system("AddTwoIntsROS2ServiceExampleModel.slx")

Run the model. The service call should return -2 from the Resp output port, as part of the sum field in the response message. An error code of 0 indicates that the service call was successful.

sim("AddTwoIntsROS2ServiceExampleModel.slx");