2022-05-27 ROS通信机制 话题通信 自定义msg C++篇

1.首先在工作空间下创建 msg 目录用来存储 person.msg 文件

string name
int16 age
float64 heihght 

2.修改 package.xml 和 CMakeLists.txt 文件:

在package.xml 文件中修改:

<build_depend>message_generation</build_depend>
<exec_depend>message_runtime</exec_depend>
Screenshot from 2022-05-27 16-38-01.png

在 CMakeLists.txt 文件中修改:

find_package(catkin REQUIRED COMPONENTS
  roscpp
  rospy
  std_msgs
  message_generation  //在此处添加message_generation
)

## Generate messages in the 'msg' folder  同时,放开下方add_message_files函数的注释
add_message_files(
  FILES
  Person.msg  //在此处添加创建的msg文件名
)

## Generate added messages and services with any dependencies listed here //同样放开此处的注释
generate_messages(
  DEPENDENCIES
  std_msgs
)

catkin_package(
#  INCLUDE_DIRS include
#  LIBRARIES ros_pub_sub
 CATKIN_DEPENDS roscpp rospy std_msgs message_runtime//放开该句的注释,同时在末尾添加 message_runtime
#  DEPENDS system_lib
)

3.修改 工作空间/.vscode/c_cpp_properties.json 文件

在 "includePath" 中添加msg文件的绝对路径

Screenshot from 2022-05-27 16-46-48.png

发布方实现:

#include "ros/ros.h"
#include "ros_pub_sub/Person.h"

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

  setlocale(LC_ALL,"");

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

  ros::NodeHandle nh;
  
  ros::Publisher pub = nh.advertise<ros_pub_sub::Person>("chatter",10);

  ros_pub_sub::Person person;

  person.name = "luckye";
  person.age = 1;
  person.height = 1.73;

  ros::Rate r(1);
  
  while(ros::ok())
  {
      pub.publish(person);

      ROS_INFO("发送的内容为: 姓名:%s ,年龄为:%d ,身高为:%.2f ",person.name.c_str(),person.age,person.height);
      
      person.age += 1;

      r.sleep();

      ros::spinOnce();


  }
  return 0;
}

订阅方实现:

#include "ros/ros.h"
#include "ros_pub_sub/Person.h"
void doPerson(const ros_pub_sub::Person::ConstPtr &person)
{

    ROS_INFO("接收到的内容为:姓名:%s ,年龄:%d ,身高:%.2f",person->name.c_str(),person->age,person->height);

}

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

    setlocale(LC_ALL,"");

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

    ros::NodeHandle nh;

    ros::Subscriber sub = nh.subscribe("chatter",10,doPerson);

    ros::spin();
  

}

修改 CMakeLists.txt 文件编译运行发布方和订阅方 cpp文件
在终端运行情况如下:


Screenshot from 2022-05-27 17-14-30.png
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容