ROS Workspace and Sample Codes

From RobotForAll
Jump to: navigation, search

create a catkin workspace

$mkdir -p ~/catkin_ws/src
$cd ~/catkin_ws/
$catkin_make
$source devel/setup.bash

for easy use you can write the following line in bashrc

$ source /home/usrname/catkin_ws/devel/setup.bash
$ source /opt/ros/kinetic/setup.bash

using ROS publish and subscribe a topic

after create a catkin workspace your can following the steps list in create a pacaage to create your ROS package

$ catkin_create_pkg pkg_name roscpp rospy std_msgs
$ cd ~/catkin_ws/src/pkg_name/src
$ touch talker.py
$ chmod +x talker.py
$ rosed talker.py 

Then copy this script in your talker.py

#!/usr/bin/env python
import rospy
from std_msgs.msg import String
def talker():
    # define a  publisher with topic name my_pub with massage type String 
    pub=rospy.Publisher('my_pub',String, queue_size=10)
    #initial a ros node with name takler anonymous=True means each node has its own name
    rospy.init_node('talker',anonymous=True)
    # set rate 10HZ
    rate=rospy.Rate(10) 
    # check wheather ros is shuttdown
    while not rospy.is_shutdown():
        # message 
        my_str="send msg at time %s" % rospy.get_time()
        # show log in screen
        rospy.loginfo(my_str)
        # publish your msg
        pub.publish(my_str)
        #sleep for a duration
        rate.sleep()
if __name__ == '__main__':
   try :
       talker()
   except rospy.ROSInterruptException:
       pass

the same way you also need a listen.py, and then copy the script in your listen.py

#!/usr/bin/env python
import rospy
from std_msgs.msg import String
# define a callback function when listen a msg then run the function
def callback(data):
    rospy.loginfo(rospy.get_caller_id()+'  '+ data.data)
def listener():
    rospy.Subscriber('my_pub', String, callback)
    # 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)
    #spin() simply keeps python from exiting until this node is stopped
    rospy.spin()
if __name__=='__main__': 
    try:
        listener()
    except rospy.ROSInterruptException:
        pass

After this, you need to opena new ternimal input like this

$ rosrun pkg_name talker.py
$ rosrun pkg_name listener.py

you can see the message published by talker and subscribed by listener in your terminal