工程中由于自定义的msg或srv比较多,通常会单独把自定义的内容放入一个pkg。本节我们新建一个叫public_pkg的pkg。
mkdir -p catkin_ws1/src
cd catkin_ws1/src
catkin_init_workspace
cd ~/catkin_ws1
catkin_make
catkin_make install
cd ~/catkin_ws1/src
catkin_create_pkg public_pkg std_msgs roscpp
cd public_pkg
mkdir msg
cd msg
touch CustomMsg.msg
gedit CustomMsg.msg
CustomMsg.msg内容如下:
string name
string gender
uint8 age
float64 hight
确保以下几项与本文相同
find_package(catkin REQUIRED COMPONENTS
roscpp
std_msgs
message_generation
)
add_message_files(
FILES
CustomMsg.msg
)
generate_messages(
DEPENDENCIES
std_msgs
)
catkin_package(
# INCLUDE_DIRS include
# LIBRARIES public_pkg
CATKIN_DEPENDS roscpp std_msgs message_runtime
# DEPENDS system_lib
)
新增以下两行
<build_depend>message_generation</build_depend>
<exec_depend>message_runtime</exec_depend>
cd ~/catkin_ws1
catkin_make
编译完成后,devel目录下会生成include/public_pkg/CustomMsg.h, 此文件就是我们将要使用的真正的类型文件
自然我们是在另一个pkg中使用刚刚定义的CustomMsg, 为此,新增一个pkg是必要的,取名custom_msg_publisher, 从名字可以看出,我们将发布一个CustomMsg类型的Topic。
cd ~/catkin_ws1/src
catkin_create_pkg custom_msg_publisher std_msgs roscpp public_pkg
依赖public_pkg
package.xml新增:
<build_depend>public_pkgbuild_depend>
<build_export_depend>public_pkgbuild_export_depend>
<exec_depend>public_pkgexec_depend>
在custom_msg_publisher/src下新建custom_msg_publisher_node.cpp
touch custom_msg_publisher_node.cpp
gedit custom_msg_publisher_node.cpp
custom_msg_publisher_node.cpp
#include "ros/ros.h"
#include "public_pkg/CustomMsg.h"
int main(int argc, char **argv)
{
ros::init(argc, argv, "custom_topic");
ros::NodeHandle n;
ros::Publisher custom_pub = n.advertise<public_pkg::CustomMsg>("custom_topic", 100);
ros::Rate loop_rate(1);
while (ros::ok())
{
public_pkg::CustomMsg msg;
msg.name="chaoren";
msg.gender="male";
msg.age = 100;
msg.hight=999.999;
ROS_INFO("%s %s %s %s %s %d %s %f", "student information: name:", msg.name.c_str(),"gender:",msg.gender.c_str(),"age:",msg.age,"hight:",msg.hight);
custom_pub.publish(msg);
ros::spinOnce();
loop_rate.sleep();
}
return 0;
}
其实就是反注释以下3句,我在文件命名的时候就以默认的规范,就不需要再对命名进行修改了。
add_executable(${
PROJECT_NAME}_node src/custom_msg_publisher_node.cpp)
add_dependencies(${
PROJECT_NAME}_node ${
${
PROJECT_NAME}_EXPORTED_TARGETS} ${
catkin_EXPORTED_TARGETS})
target_link_libraries(${
PROJECT_NAME}_node
${
catkin_LIBRARIES}
)
cd ~/catkin_ws1
catkin_make
roscore
cd catkin_ws1
source devel/setup.bash
rosrun custom_msg_publisher custom_msg_publisher_node