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


    创建工作环境

    创建文件夹,创建包

    mkdir -p ~/catkin_arduino_ros/src
    
    catkin_create_pkg test1_pub_sub std_msgs rospy roscpp
    

      

     

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

      

    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
    

      

  • 相关阅读:
    物理层的三种编码方式
    Mysql中eft join、right join、inner join的区别
    Linux常用命令
    Linux中文件颜色所代表的属性和颜色
    phpcms v9 中的数据库操作函数
    NetBeans无法使用编码GBK安全打开文件
    PHP中的一些常用正则表达式
    eureka强制下线上线
    perl(JSON) is needed by mysql-community-test-5.7.30-1.el7.x86_64
    利用TikZ 宏包在 LaTeX 中绘制流程图
  • 原文地址:https://www.cnblogs.com/kekeoutlook/p/7401159.html
Copyright © 2020-2023  润新知