定义Person话题
定义Person发布者
# include <ros/ros.h>
# include <test_topic/Person.h>
int main ( int argc, char * * argv)
{ ros:: init ( argc, argv, "person_publisher" ) ; ros:: NodeHandle n; ros:: Publisher person_info_pub = n. advertise< test_topic:: Person> ( "/person_info" , 10 ) ; ros:: Rate loop_rate ( 1 ) ; int count = 0 ; while ( ros:: ok ( ) ) { test_topic:: Person person_msg; person_msg. name = "vodka" ; person_msg. age = 22 ; person_msg. gender = test_topic:: Person:: male; person_info_pub. publish ( person_msg) ; ROS_INFO ( "Publish Person Info, name:%s\n age:%d\n gender:%d " , person_msg. name. c_str ( ) , person_msg. age, person_msg. gender) ; loop_rate. sleep ( ) ; } return 0 ;
}
定义订阅者
# include <ros/ros.h>
# include "test_topic/Person.h"
void PersonInfoCallback ( const test_topic:: Person:: ConstPtr& msg) { ROS_INFO ( "Subscribe Person Info: name:%s\n age:%d\n gender:%d" , msg-> name. c_str ( ) , msg-> age, msg-> gender) ;
} int main ( int argc , char * * argv) { ros:: init ( argc, argv, "person_subscriber" ) ; ros:: NodeHandle n; ros:: Subscriber person_info_sub = n. subscribe ( "/person_info" , 10 , PersonInfoCallback) ; ros:: spin ( ) ; return 0 ;
}
添加相关依赖(generate_messages:某些代码功能需要动态生成,添加依赖信息)
person_publisher 和 person_subscriber 通过节点管理器建立了ROStcp之后,节点管理器关闭也不会影响两者正常运行