5.ROS编程学习:自定义话题消息与python调用

1.准备操作

用vscode开发需要进行准备操作,防止在调用自定义话题信息时误报。

settings.json 

5.ROS编程学习:自定义话题消息与python调用_第1张图片

{
    "python.autoComplete.extraPaths": [
        "/opt/ros/melodic/lib/python2.7/dist-packages",
        "/home/rosmelodic/catkin_ws/devel/lib/python2.7/dist-packages"
    ],
    "python.analysis.extraPaths": [
        "/opt/ros/melodic/lib/python2.7/dist-packages"
    ]
}

通过pwd命令显示路径。在settings.json 加入路径。

 2.发布者实现

#! /usr/bin/env python3
# -*- coding: UTF-8 -*-

import rospy
from sub_pub.msg import Person

if __name__ == "__main__":
    rospy.init_node("pub_person")
    pub = rospy.Publisher(name="person_msgg", data_class=Person, queue_size=10)
    p = Person()
    p.name = "郭"
    p.age = 8
    p.height = 1.85
    rate = rospy.Rate(1)
    while not rospy.is_shutdown():
        pub.publish(p)
        rospy.loginfo("发布的消息%s,%d,%2f",p.name,p.age,p.height)
        rate.sleep()

 通过import调用新建的消息类型(库),消息类型的路径为sub_pub/msg

from sub_pub.msg import Person

3.订阅者实现

#! /usr/bin/env python3
# -*- coding: UTF-8 -*-

import rospy
from sub_pub.msg import Person

def huidiao(p):
    rospy.loginfo("接收到的人的信息:%s, %d, %.2f",p.name, p.age, p.height)

if __name__ == "__main__":
    rospy.init_node("sub_person")
    sub = rospy.Subscriber(name="person_msgg", data_class=Person, callback=huidiao, queue_size=10)
    rospy.spin()

4.CMakeList.txt配置

catkin_install_python(PROGRAMS
  scripts/pub_p_person.py
  DESTINATION ${CATKIN_PACKAGE_BIN_DESTINATION}
)
catkin_install_python(PROGRAMS
  scripts/sub_p_person.py
  DESTINATION ${CATKIN_PACKAGE_BIN_DESTINATION}
)

5.添加可执行权限

5.ROS编程学习:自定义话题消息与python调用_第2张图片

 将要添加权限的路径用终端打开。

chmod -x *.py

6.分别启动发布者和订阅者

roscore
rosrun sub_pub pub_p_person.py 
rosrun sub_pub sub_p_person.py 

5.ROS编程学习:自定义话题消息与python调用_第3张图片

5.ROS编程学习:自定义话题消息与python调用_第4张图片

7.计算图、

rqt_graph

5.ROS编程学习:自定义话题消息与python调用_第5张图片

你可能感兴趣的:(ROS编程,ros)