文章目录
前言
Ubuntu18.04
ROS Melodic
一、新建一个ROS工作空间并创建功能包
mkdir -p catkin_ws/src
cd ~/catkin_ws/src/
catkin_init_workspace
cd ~/catkin_ws/
catkin_make
echo "source ~/catkin_ws/devel/setup.bash">>~/.bashrc
source ~/.bashrc
cd ~/catkin_ws/src/
catkin_create_pkg topic roscpp rospy std_msgs
执行完毕后建立了工作空间catkin_ws,并创建了功能包topic。
二、创建一个msg消息
在topic包的目录下创建msg文件夹并在msg文件中添加消息成员
cd /home/mobot/catkin_ws/src/topic
mkdir msg
cd msg
gedit example.msg
填入以下内容:
std_msgs/Header header
float32 test1
int32 test2
header
是消息头,包含了序列号,时间戳,frame_id,一般每个消息都有这个成员,其他的成员可以根据需要随便取。
编辑package.xml文件
gedit /home/mobot/catkin_ws/src/topic/package.xml
确保它包含以下两行且没有被注释。如果没有,添加进去:
<build_depend>message_generation</build_depend>
<exec_depend>message_runtime</exec_depend>
修改topic包下面的CMakeLists.txt文件:
gedit /home/mobot/catkin_ws/src/topic/CMakeLists.txt
将message_generation
添加到COMPONENTS列表中
添加运行时依赖关系CATKIN_DEPENDS message_runtime
添加msg文件
add_message_files(
FILES
example.msg
)
确保generate_messages()函数被调用
generate_messages(
DEPENDENCIES
std_msgs
)
添加完后无需编译使用rosmsg show example
即可查看是否添加成功
三、发布话题
进入catkin_ws/src/topic/src中新建节点程序
cd ~/catkin_ws/src/topic/src
gedit pub.cpp
一个简单的发布节点程序如下,可以直接复制到pub.cpp中
int main(int argc, char **argv)
{
ros::init(argc, argv,"pub");
ros::NodeHandle nd;
ros::Publisher publish = nd.advertise<topic::example>("/topic/example", 10);
ros::Rate loop_rate(10);
while (ros::ok())
{
topic::example example;
example.test1 = 1.5;
example.test2 = 2;
publish.publish(example);
loop_rate.sleep();
}
return 0;
}
修改topic包下面的CMakeLists.txt文件:
gedit /home/mobot/catkin_ws/src/topic/CMakeLists.txt
在文件的最后加上:
add_executable(pub src/pub.cpp)
target_link_libraries(pub ${catkin_LIBRARIES})
然后编译
cd ~/catkin_ws
catkin_make
. ~/catkin_ws/devel/setup.bash
运行:
roscore
rosrun topic pub
然后执行:
rostopic echo /topic/example
出现下面的信息说明发布成功
四、订阅话题
进入catkin_ws/src/topic/src中新建节点程序
cd ~/catkin_ws/src/topic/src
gedit sub.cpp
一个简单的发布节点程序如下,可以直接复制到sub.cpp中
void subscriberCallback(const topic::example::ConstPtr& msg)
{
printf("test1=%f,test2=%d\n",msg->test1,msg->test2);
}
int main(int argc, char **argv)
{
ros::Subscriber subscriber;
ros::init(argc, argv,"sub");
ros::NodeHandle nd;
subscriber = nd.subscribe("topic/example", 5, &subscriberCallback);
ros::Rate loop_rate(10);
while (ros::ok())
{
loop_rate.sleep();
ros::spinOnce();
}
return 0;
}
修改topic包下面的CMakeLists.txt文件:
gedit /home/mobot/catkin_ws/src/topic/CMakeLists.txt
在文件的最后加上:
add_executable(sub src/sub.cpp)
target_link_libraries(sub ${catkin_LIBRARIES})
然后编译
cd ~/catkin_ws
catkin_make
. ~/catkin_ws/devel/setup.bash
运行:
rosrun sub sub
可以看到打印出了订阅到的话题
运行rqt_graph
结果如下:
代码地址:
git@gitee.com:Mbot/ros-topic-template.git