ROS教程1--建立節點
阿新 • • 發佈:2019-02-09
- 編寫cpp檔案
//example1_a.cpp
#include "ros/ros.h"
#include "std_msgs/String.h"
#include <sstream>
int main(int argc, char **argv)
{
ros::init(argc, argv, "example1_a");
ros::NodeHandle n;
ros::Publisher pub = n.advertise<std_msgs::String>("message", 1000);
ros::Rate loop_rate(10);
while (ros::ok())
{
std_msgs::String msg;
std::stringstream ss;
ss << " I am the example1_a node ";
msg.data = ss.str();
//ROS_INFO("%s", msg.data.c_str());
pub.publish(msg);
ros::spinOnce();
loop_rate.sleep();
}
return 0;
}
//
//example1_b.cpp
#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());
}
int main(int argc, char **argv)
{
ros::init(argc, argv, "example1_b");
ros::NodeHandle n;
ros::Subscriber sub = n.subscribe("message", 1000, messageCallback);
ros::spin ();
return 0;
}
- 編譯節點
rosed chapter2_tutorials CMakeLists.txt
新增如下內容至檔案末尾
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})
- 執行
roscore //在三個新終端中執行
rosrun chapter2_tutorials chap2_example1_a
rosrun chapter2_tutorials chap2_example1_b
- 注意事項
在新的命令列下可能會出現無法找到新建的包的情況,需要更新一下
在 ~/dev/catkin_ws/src 目錄下,輸入命令
source devel/setup.bash
或許也需要重新編譯一下,輸入命令如下
catkin_make //在 ~/dev/catkin_ws/ 目錄下
//或者
catkin_make chapter2_tutorials