ROS-1 example code

Let's consider the traditional publish-subscribe code, that is, the talker-listener code written in Python. I'm assuming that you're familiar with package creation in ROS-1 by now using the catkin_create_pkg command.

Let's create a simple package and run our ROS-1 node from that:

  1. Open a fresh Terminal and use the following commands:
$ initros1
$ mkdir -p ros1_example_ws/src
$ cd ~/ros1_example_ws/src
$ catkin_init_workspace
$ catkin_create_pkg ros1_talker rospy
$ cd ros1_talker/src/
$ gedit talker.py
  1. Now, copy the following code into the text editor and save the file:
#!/usr/bin/env python

import rospy
from std_msgs.msg import String
from time import sleep

def talker_main():
rospy.init_node('ros1_talker_node')
pub = rospy.Publisher('/chatter', String)
msg = String()
i = 0
while not rospy.is_shutdown():
msg.data = "Hello World: %d" % i
i+=1
rospy.loginfo(msg.data)
pub.publish(msg)
sleep(0.5)

if __name__ == '__main__':
talker_main()
  1. After you've saved the file, close the file and give permissions to the file:
$ chmod +x talker.py
  1. Now, go back to the workspace and compile the package:
$ cd ~/ros1_example_ws
$ catkin_make
  1. To run the node, source the workspace and run the node using the following commands:
$ source devel/setup.bash
$ rosrun ros1_talker talker.py
Ensure you have roscore running in another Terminal to check the preceding node. Do that by calling $ initros1 and then $ roscore.

You should now see the node publishing information. Let's see how this is done for ROS-2.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.191.22