[学习笔记]ROS创建节点

  1. 先上图片:


    [学习笔记]ROS创建节点_第1张图片
    代码注意事项
[学习笔记]ROS创建节点_第2张图片
运行效果

[学习笔记]ROS创建节点_第3张图片
节点信息
  1. 编码
$cd ~/catkin_ws/
$catkin_create_pkg beginner_tutorials std_msgs rospy roscpp
$cd  beginner_tutorials
$mkdir src
$cd src

创建 talker.cpp / listenner.cpp两个源码文件

//talker.cpp
#include "ros/ros.h"
#include "std_msgs/String.h"
#include 
int main(int argc,char **argv)
{
    //名称talker必须唯五
    ros::init(argc,argv,"talker1");
    ros::NodeHandle n;
    ros::Publisher chatter_pub=n.advertise("message1",1000);

    ros::Rate loop_rate(10); //loop_rate 发送数据频率10Hz
    int count=0;
    while(ros::ok())
    {
        std_msgs::String msg;
        std::stringstream ss;
        ss<< "helo world" <
//listenner.cpp
 #include "ros/ros.h"
#include "std_msgs/String.h"
void chatterCallback(const std_msgs::String::ConstPtr& msg)
{
    ROS_INFO("I heard:[%s]",msg->data.c_str());
}
int main(int argc,char **argv)
{
    //名称初始化时要求唯一
    ros::init(argc,argv,"listenner1");
    ros::NodeHandle n;

    //这里订阅的chatter必须与发布者一致
    ros::Subscriber sub=n.subscribe("message1",1000,chatterCallback);

    //spin()是节点读取数据的消息响应循环
    ros::spin();
    return 0;
}

目录下的CMakelists.txt尾部追加信息

include_directories(include ${catkin_INCLUDE_DIRS})
add_executable(talker src/talker.cpp)
target_link_libraries(talker ${catkin_LIBRARIES})
add_dependencies(talker rospubsub_demo_generate_messages_cpp)
add_executable(listener src/listener.cpp)
target_link_libraries(listener ${catkin_LIBRARIES})
add_dependencies(listener rospubsub_demo_generate_messages_cpp)
  1. 运行
$source ~/catkin_ws/devel/setup.bash

运行tmux开三个窗口后分别运行下面的程序

$roscore
$rosrun beginner_tutorials talker
$rosrun beginner_tutorials listenner
  1. 通过rqt_graph看节点状态
$rosrun rqt_graph rqt_graph 

你可能感兴趣的:([学习笔记]ROS创建节点)