ROS ํ™˜๊ฒฝ์—์„œ C++ ๊ธฐ๋ฐ˜ Subscriber๋ฅผ ์ž‘์„ฑํ•ด๋ณด์ž

์ž‘์—… ๊ฒฝ๋กœ ๋ฐ ํŒจํ‚ค์ง€ ์ƒ์„ฑ

์ด์ „ publisher ๋งŒ๋“œ๋Š” ํŒจํ‚ค์ง€์™€ ์ด์–ด์ง€๋Š” ๊ฒƒ์ด๋ฏ€๋กœ ์ž‘์—… ๊ฒฝ๋กœ ๋ฐ ํŒจํ‚ค์ง€ ์ƒ์„ฑ์€ ์•„๋ž˜ ๊ฒฝ๋กœ๋ฅผ ์ฐธ๊ณ ํ•˜์ž

โ€œ[ROS] C++ publisher ์ž‘์„ฑํ•˜๊ธฐโ€


Subscriber ์ฝ”๋“œ ์ž‘์„ฑ

src ํด๋” ์•ˆ์—์„œ sub.cpp ํŒŒ์ผ์„ ๋งŒ๋“ค์–ด์ฃผ์ž

$ cd src
$ gedit sub.cpp

์ „์ฒด ์ฝ”๋“œ

#include <ros/ros.h>
#include <std_msgs/String.h>

void stringCallback(const std_msgs::String::Ptr& msg)
{
  ROS_INFO("I got a message: %s", msg->data.c_str());
}

int main(int argc, char** argv)
{
  ros::init(argc, argv, "sub_node");
  ros::NodeHandle nh;

  ros::Subscriber sub = nh.subscribe("message", 10, stringCallback);

  ros::spin();

  return 0;
}

์ฝ”๋“œ๊ฐ€ ์ดํ•ด๋˜์ง€ ์•Š์œผ๋ฉด ์งˆ๋ฌธ ๋‚จ๊ฒจ์ฃผ์‹œ๋ฉด ๊ฐ์‚ฌํ•˜๊ฒ ์Šต๋‹ˆ๋‹ค :)


CMakeLists.txt ์ˆ˜์ •

์•„๊นŒ ros_simple_tutorial ํŒจํ‚ค์ง€ ๊ฒฝ๋กœ์— ๊ฐ€์„œ CMakeLists.txt๋ฅผ ์ˆ˜์ •ํ•ด์ฃผ์ž

$ gedit CMakeLists.txt


์›๋ž˜ ์žˆ๋˜ ๊ฒƒ์„ ์‚ญ์ œํ•˜๊ณ  ์•„๋ž˜๋ฅผ ๋ณต์‚ฌ ๋ถ™์—ฌ๋„ฃ๊ธฐ ํ•œ๋‹ค
๊ฐ„ํ˜น ์ œ์ผ ์ฒซ ๋ฒˆ์งธ ์ค„์ธ cmake_minimum_required ์ด ์—๋Ÿฌ ๋‚˜๋Š” ๊ฒฝ์šฐ๊ฐ€ ์žˆ๋Š”๋ฐ ์ด๋Ÿด ๋•Œ๋Š” ํ„ฐ๋ฏธ๋„ ์ฐฝ์— $ cmake --version์„ ์ž…๋ ฅํ•˜์—ฌ ์ž์‹ ์˜ cmake ๋ฒ„์ „์„ ์ž…๋ ฅํ•ด์ค€๋‹ค

cmake_minimum_required(VERSION 3.0.9)
project(ros_simple_tutorial)

# add_compile_options(-std=c++11)

find_package(catkin REQUIRED COMPONENTS
  roscpp
  std_msgs
)

catkin_package(
#  INCLUDE_DIRS include
#  LIBRARIES ros_simple_tutorial
#  CATKIN_DEPENDS roscpp std_msgs
#  DEPENDS system_lib
)

include_directories(
# include
  ${catkin_INCLUDE_DIRS}
)

add_executable(pub src/pub.cpp)
target_link_libraries(pub
  ${catkin_LIBRARIES}
)

add_executable(sub src/sub.cpp)
target_link_libraries(sub
  ${catkin_LIBRARIES}
)

์‹คํ–‰ํ•˜๊ธฐ

$ roscore
$ source ~/ros_ws/devel/setup.bash
$ rosrun ros_simple_tutorial pub
$ rosrun ros_simple_tutorial sub

Leave a comment