前面一篇文章介绍ROS的安装以及一个简单的hello world程序;
参考链接:https://blog.csdn.net/qq_43433255/article/details/88806006
这一次,介绍关于ROS的两个程序:talker.cpp与listener.cpp,也是一个关于hello world的程序,但是交互式的;
首先,打开终端:
cd catkin_ws
在beginner_tutorials/src目录下创建talker.cpp:
cd ~/catkin_ws/src/beginner_tutorials/src
sudo gedit talker.cpp
taiker.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>("chatter",1000);
ros::Rate loop_rate(10);
int count=0;
while(ros::ok())
{
std_msgs::String msg;
std::stringstream ss;
ss<<"Hello world"<<count;
msg.data==ss.str();
ROS_INFO("%S",msg.data.c_str());
chatter_pub.publish(msg);
ros::spinOnce();
loop_rate.sleep();
++count;
}
return 0;
}
在beginner_tutorials/src目录下创建listener.cpp:
cd ~/catkin_ws/src/beginner_tutorials/src
sudo gedit listener.cpp
listener.cpp的代码:
#include<ros/ros.h>
#include<std_msgs/String.h>
/**
* This tutorial demonstrates simple receipt of messages over the ROS system.
*/
void chatterCallback(const std_msgs::String::ConstPtr& msg)
{
ROS_INFO("I heard: [%s]", msg->data.c_str());
}
int main(int argc, char **argv)
{
/**
* The ros::init() function needs to see argc and argv so that it can perform
* any ROS arguments and name remapping that were provided at the command line. For programmatic
* remappings you can use a different version of init() which takes remappings
* directly, but for most command-line programs, passing argc and argv is the easiest
* way to do it. The third argument to init() is the name of the node.
*
* You must call one of the versions of ros::init() before using any other
* part of the ROS system.
*/
ros::init(argc, argv, "listener");
/**
* NodeHandle is the main access point to communications with the ROS system.
* The first NodeHandle constructed will fully init