1.进入工作区间
cd catkin_ws/src/
8.新建一个工程包
catkin_create_pkg lesson4 std_msgs rospy roscpp
9.新建msg文件夹
cd lesson4
mkdir msg
cd msg
touch Person.msg
gedit Person.msg
粘贴以下代码:
string name
uint8 sex
uint8 age
uint8 woman =0
uint8 man =1
uint8 manplus =2
10.修package.xml
cd ~/catkin_ws/src/lesson4
gedit package.xml
粘贴以下代码:
<build_depend>message_generation</build_depend>
<exec_depend>message_runtime</exec_depend>
11.修改CMakeLists.txt
cd ~/catkin_ws/src/lesson4
gedit CMakeLists.txt
找到下面对应三个位置,改成如下图:
12.创建python文件夹,并在文件夹内创建两个py文件
person_subscriber.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#该例程将订阅/person_info话题,自定义消息类型lesson4::Person
import rospy
from lesson4.msg import Person
def personInfoCallback(msg):
rospy.loginfo("Subcribe Person Info: name:%s age:%d sex:%d",msg.name,msg.age,msg.sex)
def person_subscriber():
#ROS节点初始化
rospy.init_node('person_subscriber',anonymous=True)
#创建一个Subscriber,订阅名为/person_info的topic,注册回调函数personInfoCallback
rospy.Subscriber("/person_info",Person,personInfoCallback)
#循环等待回调函数
rospy.spin()
if __name__ == '__main__':
person_subscriber()
person_publisher.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#该例程发布/person_info话题,自定义消息类型lesson4::Person
import rospy
from lesson4.msg import Person
def velocity_publisher():
#ROS节点初始化
rospy.init_node('person_publisher',anonymous=True)
#创建一个publisher,发布名为/person_info的topic,消息类型为learning_tpic::Person,队列长度10
person_info_pub = rospy.Publisher('/person_info',Person,queue_size=10)
#设置循环的频率
rate = rospy.Rate(10)
while not rospy.is_shutdown():
#初始化learning_topic::Persion类型的消息
person_msg = Person()
person_msg.name = "Tom";
person_msg.age = 18;
person_msg.sex = Person.male;
#发布消息
person_info_pub.publish(person_msg)
rospy.loginfo("Publish person message[%s,%d,%d]",person_msg.name,person_msg.age,person_msg.sex)
#按照循环频率延时
rate.sleep()
if __name__ == '__main__':
try:
velocity_publisher()
except rospy.ROSInterruptException:
pass
13.回到工作区间,编译
cd ~/catkin_ws
catkin_make
运行三个终端
roscore
cd catkin_ws/
source ./devel/setup.bash
rosrun lesson4 person_subscriber.py
cd catkin_ws/
source ./devel/setup.bash
rosrun lesson4 person_publisher.py
参考链接:https://blog.csdn.net/qq_42451251/article/details/105029825