文章目录
- 自定义msg
- 1. 定义msg文件
- 2. 修改 package.xml
- 3. 修改 CMakeLists.txt
- 4. message_publisher.py
- 5. message_subscriber.py
- 6. 运行 `catkin build`
- 测试
自定义msg
ros 版本:kinetic
自定义test
包的文件结构如下
|-- test
| |-- CMakeLists.txt
| |-- msg
| | `-- Complex.msg
| |-- package.xml
| |-- scripts
| | |-- message_publisher.py
| | `-- message_subscriber.py
1. 定义msg文件
Complex.msg
#通常大写字母开头
float32 real
float32 imaginary
2. 修改 package.xml
向其中添加如下信息,首先是<build_depend>message_generation</build_depend>
和<exec_depend>message_runtime</exec_depend>
;其次,需要使用那些包就添加进去,例如 std_msgs
,roscpp
。
<buildtool_depend>catkin</buildtool_depend><build_depend>rospy</build_depend><build_export_depend>rospy</build_export_depend><build_depend>message_generation</build_depend><build_depend>std_msgs</build_depend><build_depend>roscpp</build_depend><exec_depend>roscpp</exec_depend><exec_depend>rospy</exec_depend><exec_depend>message_runtime</exec_depend><exec_depend>std_msgs</exec_depend>
3. 修改 CMakeLists.txt
find_package(catkin REQUIRED COMPONENTSrospyroscppstd_msgsmessage_generation
)
添加自定义的msg文件
add_message_files(FILESComplex.msg
)
## Generate added messages and services with any dependencies listed here
generate_messages(DEPENDENCIESstd_msgs # Or other packages containing msgs
)
catkin_package(
# INCLUDE_DIRS include
# LIBRARIES testCATKIN_DEPENDS rospy message_runtime std_msgs roscpp
# DEPENDS system_lib
)
## Mark executable scripts (Python etc.) for installation
## in contrast to setup.py, you can choose the destination
catkin_install_python(PROGRAMSscripts/message_publisher.pyscripts/message_subscriber.pyDESTINATION ${CATKIN_PACKAGE_BIN_DESTINATION}
)
4. message_publisher.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-import rospy
from test.msg import Complex
from random import randomrospy.init_node("message_publisher")
pub = rospy.Publisher("complex", Complex)rate = rospy.Rate(2)while not rospy.is_shutdown():msg = Complex()msg.real = random()msg.imaginary = random()pub.publish(msg)rate.sleep()
5. message_subscriber.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-import rospy
from test.msg import Complexdef callback(msg):print("real:", msg.real)print("imaginary:", msg.imaginary)print("\n") rospy.init_node("message_subscriber")
sub = rospy.Subscriber("complex", Complex, callback)rospy.spin()
6. 运行 catkin build
测试
roscore
rosrun test message_publisher.py
rosrun test message_subscriber.py
rqt_graph #看一下 ros 节点图