您的位置:首页 > Web前端 > Node.js

ROS_Node

2020-02-02 20:16 816 查看

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"

转载于:https://my.oschina.net/meczhang/blog/1602517

  • 点赞
  • 收藏
  • 分享
  • 文章举报
站内首发文章 chuniao1992 发布了0 篇原创文章 · 获赞 0 · 访问量 358 私信 关注
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: