ROS实践04 发布方实现Python
运行环境:
ubuntu20.04 noetic
宏基暗影骑士笔记本
思路:
创建功能包
在功能包scripts下新建.py文件
修改CMakLists
运行节点
1.1 Python代码实现
1)工作空间创建和编译
mkdir -p demo01_ws/src
cd demo01_ws
catkin_make
code .
2)功能包创建和添加依赖
在工作空间scripts目录下创建功能包
demo02_pub_py
roscpp rospy std_msgs
3)新建.py文件
在功能包scripts目录下新建demo02_pub.py文件
#!/usr/bin/env python
import rospy
from std_msgs.msg import Stringdef publisher_node():# 初始化 ROS 节点rospy.init_node('publisher_node', anonymous=True)# 创建一个名为“message”的话题,消息类型为 std_msgs/Stringpub = rospy.Publisher('message', String, queue_size=10)# 设置发布频率rate = rospy.Rate(10)while not rospy.is_shutdown():# 创建一个 String 类型的消息message = "Hello, world!"# 发布消息pub.publish(message)# 打印发布的消息内容rospy.loginfo("Publish message: %s", message)# 等待一段时间rate.sleep()if __name__ == '__main__':try:publisher_node()except rospy.ROSInterruptException:pass
if name == “main”: 表示当前脚本作为主程序被执行时才会调用publisher_node() 函数
try-except 处理异常
rospy.ROSInterruptException 表示按下 Ctrl-C 发生异常,执行下面代码块 pass(跳过异常)
4)修改CMakeList
catkin_install_python(PROGRAMSscripts/demo02_pub.pyDESTINATION ${CATKIN_PACKAGE_BIN_DESTINATION}
)
5)运行节点
ctrl+shift+B
roscore
source ./devel/setup.bash# rosrun 包名 + 可执行文件名
rosrun demo02_pub_py demo02_pub.py
# 显示节点和话题关系
rqt_graph
⭐⭐⭐嘟嘟崽 ⭐⭐⭐ ⭐⭐⭐祝你成功 ⭐⭐⭐