ros 话题订阅
环境搭建就跳过了,假设你已经学会了编译运行了
1.发布端代码
#include "ros/ros.h"
#include "std_msgs/String.h"
#include "sstream"
int main(int argc, char *argv[])
{
/* code */
//set code use chinese
setlocale(LC_ALL,"");
//ros init
ros::init(argc,argv,"gRos1");
//
ros::NodeHandle handle1;
//3.实例化 ROS 句柄
ros::NodeHandle ghd;//该类封装了 ROS 中的一些常用功能
//4.实例化 发布者 对象
//泛型: 发布的消息类型
//参数1: 要发布到的话题
//参数2: 队列中最大保存的消息数,超出此阀值时,先进的先销毁(时间早的先销毁)
ros::Publisher pub = ghd.advertise<std_msgs::String>("connect1",10);
//5.组织被发布的数据,并编写逻辑发布数据
//数据(动态组织)
std_msgs::String msg;
//set time 10times/1s
ros::Rate tim(10);
int cout;
//delay to ensure set the connect
ros::Duration(3.0).sleep();
//ensure the ros is available
while(ros::ok())
{
//set the send msg
std::stringstream sendStr;
cout++;
sendStr<<"sendStr num->"<<cout;
msg.data=sendStr.str();
//send msg
pub.publish(msg);
//send the debug info
ROS_INFO("send text and num=%d\n",cout);
//ros-sleep
tim.sleep();
//change mission
ros::spinOnce();
}
return 0;
}
2.接收端测试
在这里我们先不写接收端代码
使用命令测试
rostopic echo connectName
其中connectName是你建立的通道名字
临时测试效果:
3.接收端代码
#include "ros/ros.h"
#include "std_msgs/String.h"
void reCallFun(const std_msgs::String::ConstPtr& msgPtr)
{
ROS_INFO("recStr:%s",msgPtr->data.c_str());
}
int main(int argc, char *argv[])
{
/* code */
//set code use chinese
setlocale(LC_ALL,"");
//ros init
ros::init(argc,argv,"gRos2");
//
ros::NodeHandle handle1;
//实例化 订阅者 对象
ros::Subscriber sub = handle1.subscribe<std_msgs::String>("connect1",10,reCallFun);
//循环读取接收的数据,并调用回调函数处理
ros::spin();
return 0;
}
4.全部改完记得修改CMakeLists.txt
add_executable(${PROJECT_NAME}_node src/demo01_node.cpp)
add_executable(demo01_rec
src/demo01_rec.cpp
)
target_link_libraries(${PROJECT_NAME}_node
${catkin_LIBRARIES}
)
target_link_libraries(demo01_rec
${catkin_LIBRARIES}
)