Hello World Publisher
创建工作区
mkdir -p ~/catkin_ws/src
cd ~/catkin_ws/src
catkin_init_workspace
构建你的工作区
cd ~/catkin_ws/
catkin_make
来源你的设置文件
source devel/setup.bash
创建一个名为 hello_world 的新包,其中包含一些基本依赖项
catkin_create_pkg hello_world std_msgs rospy roscpp
导航到你的 src 目录并创建一个名为 talker.cpp 的新文件
cd hello_world/src
touch talker.cpp
编辑新文件并粘贴此代码以发布 hello world
消息
#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;
}
返回包目录的根目录
cd ..
将这些行添加/取消注释到你的 CMakeLists.txt
catkin_package(
INCLUDE_DIRS include
LIBRARIES hello_world
# CATKIN_DEPENDS roscpp rospy std_msgs
# DEPENDS system_lib
)
include_directories(include ${catkin_INCLUDE_DIRS})
add_executable(talker src/talker.cpp)
target_link_libraries(talker ${catkin_LIBRARIES})
add_dependencies(talker hello_world_generate_messages_cpp)
返回工作区的根目录
cd ..
建立新的发布者
catkin_make
再次获取你的安装文件,以便拥有新的包和发布者
source devel/setup.bash
启动 ROS
roscore
让 roscore 保持运行并在新的终端选项卡/窗口中启动你的发布者
rosrun hello_world talker
让发布者继续运行,并在另一个新的终端选项卡/窗口中,回显输出
rostopic echo /chatter