huskycat1202
02. ROS 1.7의 C++ Code 분해하기 (중복 코드 생략) 본문
1. talker.cpp (publisher node)
#include "ros/ros.h"
#include "std_msgs/String.h"
#include <sstream>
ROS 사용에 필요한 헤더파일
sstream: C++ 프로그래밍 언어 표준 라이브러리의 일부
int main(int argc, char **argv)
argc: main에 전달된 인자의 개수
argv: 가변적인 개수의 문자열
ros::init(argc, argv, "talker");
ros::NodeHandle n;
ros::Publisher chatter_pub = n.advertise<std_msgs::String>("chatter", 1000);
ros::Rate loop_rate(10);
노드 초기화, 기본 이름=talker
노드 핸들 설정
publisher 선언, 토픽이름, 메세지타입 = chatter, std_msgs/String
루프 주기 설정. (10Hz=0.1초 간격 반복)
while (ros::ok())
roscore가 실행되는 동안
std_msgs::String msg;
std::stringstream ss;
ss << "hello world " << count;
msg.data = ss.str();
ss에 string 입력, msg.data에 대입
ROS_INFO("%s", msg.data.c_str());
chatter_pub.publish(msg);
ROS_INFO로 화면에 data 출력
msg publish
ros::spinOnce();
subscribe의 callback 호출 위해 사용. 이벤트 처리 후 즉시 반환
loop_rate.sleep();
주기만큼 sleep. 루프 내부의 작업시간을 10Hz로 설정.
2. listener.cpp (subscriber node)
void chatterCallback(const std_msgs::String::ConstPtr& msg){
ROS_INFO("I heard: [%s]", msg->data.c_str());
}
ROS_INFO로 화면에 수신된 데이터 "I heard: (msg.data)" 출력
ros::init(argc, argv, "listener");
ros::NodeHandle n;
ros::Subscriber sub = n.subscribe("chatter", 1000, chatterCallback);
ros::spin();
spin(): 데이터 수신 체크(callback)반복
3. talker2.cpp
hello_ros::MyMessage msg;
msg.message = "Hello! World";
msg.count = count;
msg의 내용 설정
ROS_INFO("%s %ld", msg.message.c_str(), msg.count);
ROS_INFO로 화면에 message, count 출력
my_message_pub.publish(msg);
msg publish
4. listener2.cpp
void chatterCallback(const hello_ros::MyMessage::ConstPtr& msg){
ROS_INFO("I heard: [%s] / Count: [%ld]", msg->message.c_str(),msg->count);
}
ROS_INFO로 화면에 수신된 데이터 "I heard: (msg.message) / Count: (count)" 출력
5. add_two_ints_server.cpp
bool add(hello_ros::AddTwoInts::Request &req, hello_ros::AddTwoInts::Response &res){
res.sum = req.a + req.b;
ROS_INFO("request: x=%ld, y=%ld", (long int)req.a, (long int)req.b);
ROS_INFO("sending back response: [%ld]", (long int)res.sum);
return true;
}
res.sum=a+b
ROS_INFO로 출력
ros::ServiceServer service = n.advertiseService("add_two_ints", add);
서비스 서버 생성
6. add_two_ints_client.cpp
annie@annie-VirtualBox:~/catkin_ws/src/hello_ros/src$ rosrun hello_ros add_two_ints_server
[ INFO] [1610380424.267799248]: Ready to add two ints.
[ INFO] [1610380433.761438724]: request: x=1, y=2
[ INFO] [1610380433.761478452]: sending back response: [3]
annie@annie-VirtualBox:~/catkin_ws/src/hello_ros/src$ rosrun hello_ros add_two_ints_client 1 2
[ INFO] [1610380433.761831418]: Sum: 3
server와 코드가 완전히 같지만, client에서 int값을 입력하면 client와 server에 결과가 도출된다.
7. 완성 코드의 예상 형태..? (전체적인 코드 구조)
#include "ros/ros.h"
#include "추가 헤더파일.h"
함수(){
ROS_INFO(출력 데이터)
}
main(){
초기값 설정
함수
}
참고
https://m.blog.naver.com/nimtedd41/221663473549
https://robertchoi.gitbook.io/ros/build
'ROS' 카테고리의 다른 글
03. Image Publish & Subscribe (0) | 2021.01.12 |
---|---|
01. CMake (0) | 2021.01.12 |