跳转至

topic通信publisher

1. 创建package

catkin_create_pkg demo_topic roscpp rospy std_msgs

2. 编写publisher节点代码

demo_topic目录的demo_topic下创建scripts文件夹,文件夹下创建publisher.py文件,代码如下

#!/usr/bin/env python3

import rospy
from std_msgs.msg import String

if __name__ == '__main__':
    rospy.init_node('publisher')
    pub = rospy.Publisher('chatter',String,queue_size=10)
    rate = rospy.Rate(10)
    # 不断发送消息
    while not rospy.is_shutdown():
        hello_str = "hello world中 %s" % rospy.get_time()
        rospy.loginfo(hello_str)
        pub.publish(hello_str)
        rate.sleep()

3. 配置工程

CMakeLists.txt文件中做如下修改:

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

3. 构建工程

在工程目录下执行如下命令

catkin_make