1. 코드 작성 & 빌드 & 실행 - PYTHON


1.1 코드 작성

wget 명령어를 통해 ros_tutorial에서 제공하는 talker.py와 listener.py를 다운로드 합니다.

$ cd ~/catkin_ws/src/topic_test/src
$ wget <https://raw.github.com/ros/ros_tutorials/kinetic-devel/rospy_tutorials/001_talker_listener/talker.py>
$ chmod +x talker.py

# listener code install
$ wget <https://raw.github.com/ros/ros_tutorials/kinetic-devel/rospy_tutorials/001_talker_listener/listener.py>
$ chmod +x listener.py

chmod +x 는 실행 권한을 부여하는 것 입니다.

노드를 만들고, hello world와 시간이 담겨있는 토픽을 생성하여 pub하는 코드 입니다.

#!/usr/bin/env python # 파이썬을 쓴다면 달아주기.
#-*- coding:uft-8 -*- # 한글 주석을 달기 위해 사용

import rospy # ROS 라이브러리 
from std_msgs.msg import String # std_msgs.msg 메세지 파일

def talker():
    pub = rospy.Publisher('chatter', String, queue_size=10) # 메세지 토픽 이름, 메시지 타입, queue size 설정
    rospy.init_node('talker', anonymous=True) # 노드 이름 설정. 
		
		# 10hz 마다 반복.
    rate = rospy.Rate(10) # 10hz
		
		# 중단되거나 강제종료(ctrl+C) 전까지 계속 실행
    while not rospy.is_shutdown():
        hello_str = "hello world %s" % rospy.get_time() # 시간이 담긴 문장 생성
        rospy.loginfo(hello_str) # 터미널에 출력
        pub.publish(hello_str) # 문장 퍼블리시
        rate.sleep() # 정해둔 주기(hz) 만큼 일시중단

if __name__ == '__main__':
    try:
        talker()
    except rospy.ROSInterruptException:
        pass

토픽 이름 지정하기.

pub = rospy.Publisher('chatter', String, queue_size=10)

노드 생성하기. rospy.init_node('talker', anonymous=True)

talker라는 이름의 노드를 생성합니다.

여기서 anonymous는 노드 이름을 겹치지 않게 해주는 옵션입니다.