ROS

ROS_Study: Writing a Simple Publisher and Subscriber(Python)

우기빌리 2023. 11. 22. 21:06

시작단계:

$ roscd beginner_tutorials
$ mkdir scripts
$ cd scripts

 

1. Publisher Node 작성하기

 1) scripts 폴더내에 python 파일 작성

#!/usr/bin/env python3
# license removed for brevity
import rospy
from std_msgs.msg import String

def talker():
    pub = rospy.Publisher('chatter', String, queue_size=10)
    rospy.init_node('talker', anonymous=True)
    rate = rospy.Rate(10) # 10hz
    while not rospy.is_shutdown():
        hello_str = "hello world %s" % rospy.get_time()
        rospy.loginfo(hello_str)
        pub.publish(hello_str)
        rate.sleep()

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

*파이썬 버전에 따라 첫 번째 줄 수정

 

 2) CMakeLists.txt 수정

catkin_install_python(PROGRAMS scripts/talker.py
  DESTINATION ${CATKIN_PACKAGE_BIN_DESTINATION}
)

 

2. Subscriber Node 작성하기

 1) scripts 폴더내에 python 파일 작성

#!/usr/bin/env python
import rospy
from std_msgs.msg import String

def callback(data):
    rospy.loginfo(rospy.get_caller_id() + "I heard %s", data.data)
    
def listener():

    # In ROS, nodes are uniquely named. If two nodes with the same
    # name are launched, the previous one is kicked off. The
    # anonymous=True flag means that rospy will choose a unique
    # name for our 'listener' node so that multiple listeners can
    # run simultaneously.
    rospy.init_node('listener', anonymous=True)

    rospy.Subscriber("chatter", String, callback)

    # spin() simply keeps python from exiting until this node is stopped
    rospy.spin()

if __name__ == '__main__':
    listener()

 

 2) CMakeList.txt 수정

catkin_install_python(PROGRAMS scripts/talker.py scripts/listener.py
  DESTINATION ${CATKIN_PACKAGE_BIN_DESTINATION}
)

 

 

모두 끝나면 마지막에 catkin workspace에서 catkin_make 하는거 잊지않기~.~

 

결과:

rosrun <pkg_name> <node_name>

rosrun beginner_tutorials talker.py

 

talker.py

rosrun beginner_tutorials listener.py

listener.py