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

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.

主站蜘蛛池模板: 义乌市| 镇康县| 门源| 温泉县| 林周县| 苍山县| 安西县| 泗洪县| 定州市| 新丰县| 福贡县| 修文县| 舟曲县| 五河县| 监利县| 壤塘县| 昌宁县| 聂拉木县| 彩票| 定襄县| 固始县| 太谷县| 奈曼旗| 田阳县| 凤阳县| 齐河县| 靖西县| 南汇区| 古丈县| 克山县| 衡南县| 四平市| 东乡| 双峰县| 二连浩特市| 嘉禾县| 平邑县| 沁源县| 诸城市| 宜阳县| 双桥区|