作者:一起回到我们的那个夏天 | 来源:互联网 | 2023-08-08 08:14
1.创建Publisher
Publisher的主要作用是针对制定话题发布特定数据类型的消息。我们用代码实现一个节点,并且在节点中创建一个Publisher并发布字符串“Hello World”,代码如下:
#include
#include "ros/ros.h"
#include "std_msgs/String.h"
int main(int argc, char **argv)
{
//ROS节点初始化
ros::init(argc,argv,"talker");
//创建节点句柄
ros::NodeHandle n;
//创建一个Publisher,发布名为chatter的topic,消息类型为std_msgs::String
ros::Publisher chatter_pub =n.advertise("chatter",1000);
//设置循环的频率
ros::Rate loop_rate(10);
int count = 0;
while (ros::ok())
{
// 初始化std_msgs::String类型的消息
std_msgs::String msg;
std::stringstream ss;
ss <<"hello world" <msg.data &#61; ss.str();
//发布消息
ROS_INFO("%s",msg.data.c_str());
chatter_pub.publish(msg);
//循环等待回调函数
ros::spinOnce();
//按照循环频率延时
loop_rate.sleep();
&#43;&#43;count;
}
return 0;
}
2.创建Subscriber
下面创建一个Subscriber以订阅Publisher节点发布的“Hello World”字符串&#xff0c;实现代码如下&#xff1a;
#include "ros/ros.h"
#include "std_msgs/String.h"
//接收到订阅的消息后&#xff0c;会进入消息回调函数
void chatterCallback(const std_msgs::String::ConstPtr& msg)
{
//将接收到的信息打印出来
ROS_INFO("I heard: [%s]",msg->data.c_str());
}
int main (int argc, char **argv)
{
//初始化ROS节点
ros::init(argc,argv,"listener");
//创建节点句柄
ros::NodeHandle n;
//创建一个Subscriber,订阅名为chatter的话题&#xff0c;注册回调函数chatterCallback
ros::Subscriber sub&#61;n.subscribe("chatter",1000,chatterCallback);
//循环等待回调函数
ros::spin();
return 0;
}
3.编译功能包
我们使用C&#43;&#43;语言来编写&#xff0c;所以需要使用CMaker编译器进行编译&#xff0c;编译规则通过功能包中的CMakerLists.txt文件设置&#xff0c;使用catkin命令创建&#xff0c;我们需要对部分内容进行更改&#xff1b;
打开功能包中的CMakerLists.txt文件&#xff0c;找到以下配置项&#xff0c;去掉注释并稍作修改&#xff1a;
## Specify additional locations of header files
## Your package locations should be listed before other locations
include_directories(
# include
${catkin_INCLUDE_DIRS}
)
##add_executable(hello ~/Alltest/catkin_ws/src/learning_communication/src/hello.cpp)
add_executable(talker src/talker.cpp)
target_link_libraries(talker ${catkin_LIBRARIES})
add_dependencies(talker ${PROJECT_NAME}_generate_messages_cpp)
add_executable(listener src/listener.cpp)
target_link_libraries(listener ${catkin_LIBRARIES})
add_dependencies(listener ${PROJECT_NAME}_generate_messages_cpp)
4.运行Publisher和Subscriber
在工作空间根目录设置环境变量并编译&#xff1a;
source devel/setup.bash
catkin_make
a.启动ROS Master
roscore
b.启动Publisher
source devel/setup.bash
rosrun learning_communication talker
c.启动Subscriber
source devel/setup.bash
rosrun learning_communication listener
这样就运行起来了&#xff0c;效果如下&#xff1a;