官术网_书友最值得收藏!

Hello_world_subscriber.py

The subscriber code is as follows:

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

The following code is a callback function that is executed when a message reaches the hello_pub topic. The data variable contains the message from the topic, and it will print using rospy.loginfo():

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

The following steps will start the node with a hello_world_subscriber name and start subscribing to the /hello_pub topic:

  1. The data type of the message is String, and when a message arrives on this topic, a method called callback will be called:
    def listener(): 
       rospy.init_node('hello_world_subscriber', 
anonymous=True) rospy.Subscriber("hello_pub", String, callback)
  1. The following code will keep your node from exiting until the node is shut down:
       rospy.spin() 
  1. The following is the main section of the Python code. The main section will call the listener() method, which will subscribe to the /hello_pub topic:
if __name__ == '__main__': 
    listener() 
  1. After saving two Python nodes, you need to change the permission to executable using the chmod commands:
    chmod +x hello_world_publisher.py
    chmod +x hello_world_subscriber.py
  1. After changing the file permission, build the package using the catkin_make command:
    cd ~/catkin_ws
    catkin_make
  1. The following command adds the current ROS workspace path in all terminals so that we can access the ROS packages inside this workspace:
    echo "source ~/catkin_ws/devel/setup.bash" >> ~/.bashrc
    source ~/.bashrc  

The following is the output of the subscriber and publisher nodes:

Output of the hello world node

  1. First, we need to run roscore before starting the nodes. The roscore command or ROS master is needed to communicate between nodes. So, the first command is as follows:
    $ roscore
  1. After executing roscore, run each node using the following commands:
    • The following command will run the publisher:
    $ rosrun hello_world hello_world_publisher.py  
    • The following command will run the subscriber node. This node subscribes to the hello_pub topic, as shown in the following code:
    $ rosrun hello_world hello_world_subscriber.py  

We have covered some of the basics of ROS. Now, we will see what Gazebo is and how we can work with Gazebo using ROS.

主站蜘蛛池模板: 胶州市| 环江| 石棉县| 乐亭县| 谷城县| 商南县| 天柱县| 大宁县| 徐水县| 华安县| 新源县| 霍山县| 洛阳市| 察雅县| 白水县| 天气| 禹州市| 固原市| 象山县| 南昌县| 额敏县| 靖宇县| 彰化县| 中山市| 醴陵市| 兰西县| 怀柔区| 岳普湖县| 海丰县| 阿克苏市| 汕头市| 扶沟县| 长春市| 广汉市| 怀来县| 临澧县| 安西县| 湖南省| 东宁县| 田林县| 江孜县|