01-ROS入门-07 ROS新建订阅/发布程序
1. 新建发布程序
cd ~/workspace/src/package_name
mkdir -p ~/workspace/src/package_name/src
vim ~/workspace/src/package_name/src/talker.cpp
<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>("message",1000);
ros::Rate loop_rate(1);
int i=0;
while(ros::ok())
{
i++;
std_msgs::String msg;
ROS_INFO("\n%d",i);
std::stringstream ss;
ss << "hello rosworld!";
msg.data = ss.str();
chatter_pub.publish(msg);
ros::spinOnce();
loop_rate.sleep();
}
return 0;
}
2.新建订阅程序
cd ~/workspace/src/package_name
mkdir -p ~/workspace/src/package_name/src
vim ~/workspace/src/package_name/src/listener.cpp
<listener.cpp>
#include "ros/ros.h"
#include "std_msgs/String.h"
void chatterCallback(const std_msgs::String::ConstPtr& msg)
{
ROS_INFO("\nI 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("message",1000,chatterCallback);
ros::spin();
return 0;
}
3. 更改CMakelist
vim ~/workplace/src/package_name/CMakelist.txt
find_package(catkin REQUIRED COMPONENTS roscpp rospy std_msgs genmsg)
add_message_files(FILES num.msg)
add_service_files(FILES sum.srv)
generate_messages(DEPENDENCIES std_msgs)
catkin_package()
include_directories(include ${catkin_INCLUDE_DIRS})
add_executable(talker src/talker.cpp)
add_executable(listener src/listener.cpp)
target_link_libraries(talker ${catkin_LIBRARIES})
target_link_libraries(listener ${catkin_LIBRARIES})
add_dependencies(talker package_name_generate_messages_cpp)
add_dependencies(listener package_name_generate_messages_cpp)
4.编译程序
cd ~/workspace
catkin_make
5.运行程序
source ~/workspace/devel/setup.bash
roscore
rosrun package_name talker
rosrun package_name listener