欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

ROS教程2 编写简单的消息发布器和订阅器 (C++ catkin)

程序员文章站 2022-06-04 15:41:38
...

创建工作环境

创建文件夹,创建包

mkdir -p ~/catkin_arduino_ros/src

catkin_create_pkg test1_pub_sub std_msgs rospy roscpp

  

 ROS教程2 编写简单的消息发布器和订阅器 (C++ catkin)

ROS教程2 编写简单的消息发布器和订阅器 (C++ catkin)

在桌面打开终端,添加工作路径

  

echo "source /home/dongdong/catkin_arduino_ros/devel/setup.bash" >> ~/.bashrc 
source ~/.bashrc

  

创建项目文件  

1创建src/talker.cpp文件

cd ~/catkin_arduino_ros/src
gedit talker.cpp

 复制代码

#include "ros/ros.h"
#include "std_msgs/String.h"

#include <sstream>


int main(int argc, char **argv)
{

  ros::init(argc, argv, "talker");


  ros::NodeHandle n;

 
  ros::Publisher chatter_pub = n.advertise<std_msgs::String>("chatter", 1000);

  ros::Rate loop_rate(10);

  
  int count = 0;
  while (ros::ok())
  {
  
    std_msgs::String msg;

    std::stringstream ss;
    ss << "hello world " << count;
    msg.data = ss.str();

    ROS_INFO("%s", msg.data.c_str());

   
    chatter_pub.publish(msg);

    ros::spinOnce();

    loop_rate.sleep();
    ++count;
  }


  return 0;
}

 保存

2创建src/listener.cpp文件

gedit listener.cpp

 复制源代码

#include "ros/ros.h"
#include "std_msgs/String.h"

void chatterCallback(const std_msgs::String::ConstPtr& msg)
{
  ROS_INFO("I heard: [%s]", msg->data.c_str());
}

int main(int argc, char **argv)
{
 
  ros::init(argc, argv, "listener");

 
  ros::NodeHandle n;

 
  ros::Subscriber sub = n.subscribe("chatter", 1000, chatterCallback);

  ros::spin();

  return 0;
}

编译节点

更改编译文件

在CMakeLists.txt文件末尾加入几条语句:

include_directories(include ${catkin_INCLUDE_DIRS})

add_executable(talker src/talker.cpp)
target_link_libraries(talker ${catkin_LIBRARIES})

add_executable(listener src/listener.cpp)
target_link_libraries(listener ${catkin_LIBRARIES})

  

  

编译

cd ~/catkin_arduino_ros/
catkin_make

  

运行节点

//分别打开三个窗口
roscore

rosrun test1_pub_sub talker

rosrun test1_pub_sub listener

  ROS教程2 编写简单的消息发布器和订阅器 (C++ catkin)