使用新定义的消息类型
创建功能包
cd catkin_ws/src
catkin_create_pkg client_pkg king_msgs roscpp rospy std_msgs
catkin_create_pkg room_money_pkg king_msgs roscpp rospy std_msgs
创建消息文件
~/catkin_ws/src/room_money_pkg/src
room_money_node.cpp
#include <ros/ros.h>
#include <std_msgs/String.h>
#include <king_msgs/King.h>
int main(int argc,char **argv)
{
setlocale(LC_ALL,"zh_CN.UTF-8");
ros::init(argc,argv,"room_money_node");
ros::NodeHandle n;
ros::Publisher pub = n.advertise<king_msgs::King>("make_money",10);
ros::Rate loop_rate(10);
while(ros::ok())
{
ROS_INFO("欢迎光临!\n");
king_msgs::King msg;
msg.room = "我是革神,请入座!";
msg.money = 100;
msg.data = "这是给你的100万拿去花";
pub.publish(msg);
loop_rate.sleep();
}
return 0;
}
~/catkin_ws/src/client_pkg/src
client_node.cpp
#include <ros/ros.h>
#include <std_msgs/String.h>
#include <king_msgs/King.h>
void clientCallback(king_msgs::King msg)
{
ROS_WARN(msg.room.c_str());
ROS_WARN("%d RMB",msg.money);
ROS_INFO(msg.data.c_str());
}
int main(int argc, char *argv[])
{
setlocale(LC_ALL,"zh_CN.UTF-8");
ros::init(argc,argv,"client_node");
ros::NodeHandle n;
ros::Subscriber sub = n.subscribe("make_money",10,clientCallback);
while(ros::ok())
{
ros::spinOnce();
}
//ros::spin();
return 0;
}
创建编译规则
~/catkin_ws/src/room_money_pkg
CMakeLists.txt
文件中加入
add_executable(room_money_node src/room_money_node.cpp)
add_dependencies(room_money_node ${${PROJECT_NAME}_EXPORTED_TARGETS} ${catkin_EXPORTED_TARGETS})
#add_dependencies(room_money_node king_msgs_generate_messages_cpp)
target_link_libraries(room_money_node
${catkin_LIBRARIES}
)
~/catkin_ws/src/client_pkg
CMakeLists.txt
文件中加入
add_executable(client_node src/client_node.cpp)
#add_dependencies(client_node king_msgs_generate_messages_cpp)
add_dependencies(client_node ${${PROJECT_NAME}_EXPORTED_TARGETS} ${catkin_EXPORTED_TARGETS})
target_link_libraries(client_node
${catkin_LIBRARIES}
)
展示效果
roscore
rosrun room_money_pkg room_money_node
rosrun client_pkg client_node