ROS

[学习笔记]ROS创建节点

2017-03-08  本文已影响643人  forrestsun
  1. 先上图片:


    代码注意事项
运行效果
节点信息
  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 <sstream>
int main(int argc,char **argv)
{
    //名称talker必须唯五
    ros::init(argc,argv,"talker1");
    ros::NodeHandle n;
    ros::Publisher chatter_pub=n.advertise<std_msgs::String>("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" <<count;
        msg.data=ss.str();

        ROS_INFO("%s",msg.data.c_str());

        chatter_pub.publish(msg);

        ros::spinOnce();

        loop_rate.sleep();
        ++count;
    }
    return 0;
}
//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 
上一篇下一篇

猜你喜欢

热点阅读