1. 程式人生 > 其它 >ros(5)話題的自定義訊息

ros(5)話題的自定義訊息

1.首先建立msg檔案

在cd~//catkin_workspace/src/learning_topic/msg/新建person.msg

string name
uint8  age
uint8  sex
 
uint8 unknown = 0
uint8 male    = 1
uint8 female  = 2

修改package.xml

新增這兩句

 <build_depend>message_generation</build_depend>
  <exec_depend>message_runtime</exec_depend>

修改cmakelists.txt

find_package(catkin REQUIRED COMPONENTS
  geometry_msgs
  roscpp
  rospy
  std_msgs
  turtlesim
  message_generation ##查詢依賴包
)
 
##生成訊息
add_message_files(
  FILES
  Person.msg
)
 
generate_messages(
  DEPENDENCIES
  std_msgs
)
 
##新增依賴包
catkin_package(
#  INCLUDE_DIRS include
#  LIBRARIES learning_topic
   CATKIN_DEPENDS geometry_msgs roscpp rospy std_msgs turtlesim message_runtime
#  DEPENDS system_lib
)

編譯

catkin_make

會在/devel/include/<package_name>/person.h檔案

2.建立釋出者和訂閱程式

person_publisher.cpp

/**
 * 該例程將釋出/person_info話題,自定義訊息型別learning_topic::Person
 */
 
#include <ros/ros.h>
#include "learning_topic/Person.h"
 
int main(int argc, char **argv)
{
    // ROS節點初始化
    ros::init(argc, argv, "person_publisher
"); // 建立節點控制代碼 ros::NodeHandle n; // 建立一個Publisher,釋出名為/person_info的topic,訊息型別為learning_topic::Person,佇列長度10 ros::Publisher person_info_pub = n.advertise<learning_topic::Person>("/person_info", 10); // 設定迴圈的頻率 ros::Rate loop_rate(1); int count = 0; while (ros::ok()) { // 初始化learning_topic::Person型別的訊息 learning_topic::Person person_msg; person_msg.name = "Tom"; person_msg.age = 18; person_msg.sex = learning_topic::Person::male; // 釋出訊息 person_info_pub.publish(person_msg); ROS_INFO("Publish Person Info: name:%s age:%d sex:%d", person_msg.name.c_str(), person_msg.age, person_msg.sex); // 按照迴圈頻率延時 loop_rate.sleep(); } return 0; }

person_subscriber.cpp

/**
 * 該例程將訂閱/person_info話題,自定義訊息型別learning_topic::Person
 */
 
#include <ros/ros.h>
#include "learning_topic/Person.h"
 
// 接收到訂閱的訊息後,會進入訊息回撥函式
void personInfoCallback(const learning_topic::Person::ConstPtr& msg)
{
    // 將接收到的訊息打印出來
    ROS_INFO("Subcribe Person Info: name:%s  age:%d  sex:%d", 
             msg->name.c_str(), msg->age, msg->sex);
}
 
int main(int argc, char **argv)
{
    // 初始化ROS節點
    ros::init(argc, argv, "person_subscriber");
 
    // 建立節點控制代碼
    ros::NodeHandle n;
 
    // 建立一個Subscriber,訂閱名為/person_info的topic,註冊回撥函式personInfoCallback
    ros::Subscriber person_info_sub = n.subscribe("/person_info", 10, personInfoCallback);
 
    // 迴圈等待回撥函式
    ros::spin();
 
    return 0;
}

修改

cmakelists

add_executable(person_publisher src/person_publisher.cpp)
target_link_libraries(person_publisher ${catkin_LIBRARIES})
add_dependencies(person_publisher ${PROJECT_NAME}_generate_messages_cpp)
 
add_executable(person_subscriber src/person_subscriber.cpp)
target_link_libraries(person_subscriber ${catkin_LIBRARIES})
add_dependencies(person_subscriber ${PROJECT_NAME}_generate_messages_cpp)

編譯

catkin_make

執行

roscore

rosrun topic_publisher person_publisher

rosrun topic_publisher person_subscriber

截圖

實時傳送資訊