ROS Workspace and Sample Codes

From RobotForAll
Jump to: navigation, search

create a catkin workspace

$mkdir -p ~/catkin_ws/src
$cd ~/catkin_ws/
$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
$ chmod +x
$ rosed 

Then copy this script in your

#!/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
    # set rate 10HZ
    # 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
        # publish your msg
        #sleep for a duration
if __name__ == '__main__':
   try :
   except rospy.ROSInterruptException:

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

#!/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()+'  '+
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
if __name__=='__main__': 
    except rospy.ROSInterruptException:

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

$ rosrun pkg_name
$ rosrun pkg_name

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