ROS Noetic getting started notes simple Publisher and Suscriber written in Python

Posted by ukphoto on Thu, 23 Dec 2021 23:03:08 +0100

1. Create Publisher

(1) Create the scripts directory under the feature pack

  • Jump to begin using roscd_ Tutorials Feature Pack directory
$ roscd beginner_tutorials
  • Use the mkdir command to create a scripts directory for our Python scripts
$ mkdir scripts
$ cd scripts

(2) talker.py

  • Download the sample Python script talker Py to the scripts folder and use the chmod command to make it executable. Of course, you can also create a new talker yourself Py file, manually type in the code or copy the code directly
$ wget https://raw.github.com/ros/ros_tutorials/kinetic-devel/rospy_tutorials/001_talker_listener/talker.py
$ chmod +x talker.py

If you are prompted with no sun package / stack 'begin_ 'tutorials', please set the environment variable source first
If you cannot connect to raw github. COM is mostly due to network problems. Please improve the network or create your own py file, and then paste the code manually

  • Don't run in a hurry. You can use the following commands to view and edit it
$ rosed beginner_tutorials talker.py
#!/usr/bin/env python
# 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

(3) talker.py code interpretation

#!/usr/bin/env python

Every ROS node program written in Python will have this declaration at the top. This line tells the operating system to automatically use the Python interpreter to run your script

import rospy
from std_msgs.msg import String

Import rospy module and STD_ String message type in msgs

pub = rospy.Publisher('chatter', String, queue_size=10)
rospy.init_node('talker', anonymous=True)

Define Publisher, publish topic as chatter, message type as String, queue_size is the maximum number of queued messages that can be reserved when the subscriber does not receive messages fast enough
Initialize a node named talker. When the anonymous parameter is True, a string of random numbers will be automatically added after the node name to ensure the uniqueness of the node name

rate = rospy.Rate(10) # 10hz

Set call rate Wait time when sleep(), call rate During sleep(), the ROS node will sleep for the corresponding time according to the frequency set here. Here, we set it to 10Hz, that is, the delay is 100ms

while not rospy.is_shutdown():
    hello_str = "hello world %s" % rospy.get_time()
    rospy.loginfo(hello_str)
    pub.publish(hello_str)
    rate.sleep()

Circular query rospy is_ The shutdown () flag determines whether to exit (for example, pressing Ctrl+C), defines the string hello_str, publishes the string message to the chatter topic, sleeps for a certain time (100ms is set here), and then starts the next cycle. rospy.loginfo has three functions: printing logs to the screen, writing node log files, and writing rosout.

try:
    talker()
except rospy.ROSInterruptException:
    pass

Run the program. When you press Ctrl+C or the node is closed for other reasons, rospy Sleep () and rospy Rate. The sleep () method throws rospy Rosinteruptexception exception

2. Create Listener

(1) Jump to begin using roscd_ Tutorials / scripts / path

$ roscd beginner_tutorials/scripts/

(2) listener.py

Download the sample Python script listener Py to the scripts folder and use the chmod command to make it executable. Of course, you can also create a listener yourself Py file, manually type in the code or copy the code directly

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


#!/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()

(3) listener.py code interpretation

Here we omit the above in talker The part already mentioned in PY

rospy.init_node('listener', anonymous=True)

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

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

Initialize the Subscriber and subscribe to the chatter topic. The received message type is String. When a new message is received, the callback function will be called
rospy.spin() ensures the normal operation of the node and does not exit until the node is closed. Unlike C + +, rospy. In python Spin () does not affect callback functions because they have separate threads

3. Compile function package

Edit cmakelists Txt file

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

After modification, return to the root directory of the workspace and start compiling

$ cd ~/catkin_ws
$ catkin_make

Previous: Introduction notes to ROS Noetic (VI) write simple Publisher and Suscriber in C + +

Topics: Python Ubuntu ROS