ROS_Node

1. Create nodes

create two nodes,one to send data,else to receive data.

//example1_a.cpp
#include "ros/ros.h"            //node essential
#include "std_msgs/String.h"    //message type
#include <sstream>

int main(int argc, char **argv)
{
    ros::init(argc, argv, "example1_a");
                                //Start node and set its name,its name is unique.
    ros::NodeHandle n;          //Set handle of node process.
    ros::Publisher pub = n.advertise<std_msgs::String>("message", 1000);
                                //Set it to be publisher
    ros::Rate loop_rate(10);    //the rate of send data.
    while (ros::ok())
    {
        std_msgs::String msg;
        std::stringstream ss;
        ss << " I am the example1_a node ";
        msg.data = ss.str();        //Created a message variable
        //ROS_INFO("%s", msg.data.c_str());
        pub.publish(msg);           //Message was published
        ros::spinOnce();        
                 //If there is a subscriber appears,ROS will update and read all topics.                        
        loop_rate.sleep();         //hand at the rate of 10Hz
    }
    return 0;
}

another

#include "ros/ros.h"
#include "std_msgs/String.h"

void messageCallback(const std_msgs::String::ConstPtr& msg)
{
    ROS_INFO("I heard: [%s]", msg->data.c_str());
            //The node will transfer this function once only it receive a message.
}

int main(int argc, char **argv)
{
    ros::init(argc, argv, "example1_b");
    ros::NodeHandle n;
    ros::Subscriber sub = n.subscribe("message", 1000, messageCallback);
            //Create a subsriber.
    ros::spin();
    return 0;
}


2. Build nodes

rosed chapter2_tutorials CMakeLists.txt

Add these commands

include_directories(
    include
    ${catkin_INCLUDE_DIRS}$
)

add_executable(chap2_example1_a src/example1_a.cpp)
add_executable(chap2_example1_b src/example1_b.cpp)

add_dependencies(chap2_example1_a chapter2_tutorials_generate_messages_cpp)
add_dependencies(chap2_example1_b chapter2_tutorials_generate_messages_cpp)

target_link_libraries(chap2_example1_a ${catkin_LIBRARIES}$
target_link_libraries(chap2_example1_b ${catkin_LIBRARIES}$

Build all packages

cd ~/dev/catkin_ws
catkin_make 


3. Start up it

roscore
rosrun chapter2_tutorials chap2_example1_a
rosrun chapter2_tutorials chap2_example1_b
//Warning: the book is wrong as "example1_a" and "example1_b"
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值