This document explains how to create custom message and service interfaces in ROS2. It provides step-by-step instructions for creating .msg and .srv files, adding them to a new package, and generating language-specific code using rosidl_default_generators. The document also includes instructions for adding dependencies to CMakeLists.txt and package.xml, and building the package.

1. Instructions

While creating your packages, it may be necessary to have a custom message type to contain all the necessary data to transfer between nodes. When this is the case, creating your own custom interface (message and srv) is needed.

For this tutorial, you will be creating custom .msg and .srv files in their own package, and then utilizing them in a separate package. Both packages should be in the same workspace.

Since we will use the pub/sub and service/client packages created in earlier tutorials, make sure you are in the same workspace as those packages (humble_ws/src), and then run the following command to create a new package:

ros2 pkg create --build-type ament_cmake basic_interfaces

basic_interfaces is the name of the new package. Note that it is, and can only be a CMake package, but this doesn’t restrict which type of packages you can use for your messages and services. You can create your own custom interfaces in a CMake package, and then use it in a C++ or Python node, which will be covered in the last section.

The .msg and .srv files are required to be placed in directories called msg and srv respectively. Create the directories in humble_ws/src/basic_interfaces:

mkdir msg srv

customer interface1.mp4

2. Creating custom definitions

a. msg definition

customer interface2.mp4

In the basic_interfaces/msg directory you created, make a new file called Num.msg with one line of code declaring its data structure:

int64 num

This is a custom message that transfers a single 64-bit integer called num.

Also in the basic_interfaces/msg directory you just created, make a new file called Sphere.msg with the following content:

geometry_msgs/Point center
float64 radius

<aside> 💡 This custom message uses a message from another message package (geometry_msgs/Point in this case).

</aside>

b. srv definition