Ch1. 用Python写一个ROS Publisher

0. 准备

熟悉一下编写 publisher 的代码,之后我们会用到:

#! /usr/bin/env python3
import rospy  

if __name__ == '__main__':
    rospy.init_node("test_node")

    rospy.loginfo("Test node has been started")

    rate = rospy.Rate(10)

    while not rospy.is_shutdown():
        rospy.loginfo("Hello")
        rate.sleep()

1. 查看Topic

运行turtlesim:

rosrun turtlesim  turtlesim_node 

此时我们用rostopic list观察下topic的状态:

在这里插入图片描述
观察到多了一个/turtel1/cmd_vel:
在这里插入图片描述
rostopic info /turtle1/cmd_vel看下topic的内容:
在这里插入图片描述
topic中有等待接受msg的订阅方(/turtlesim)却没有发布方(None)。
此处我们还可以看到topic中所要传输的信息格式geometry_msgs/Twist
在这里插入图片描述
再用rosmsg show geometry_msgs/Twist看看该类型的信息包含哪些数据
在这里插入图片描述
观察到其中包含linearangular两类数据

2. 编写Publisher

进入src文件夹中创建代码文件

cd ~/catkin_ws/src/ros_practice/src/scripts
touch draw_circle.py
chmod +x draw_circle.py

进入代码编辑页面

cd ../..
code .

键入以下代码:

#!/usr/bin/env python3  #必须要写
import rospy
from geometry_msgs.msg import Twist   #键入刚刚我们在rostopic中查看到的数据类型,必须要和rostopic中的类型保持一致

if __name__ == '__main__':
    rospy.init_node("draw_circle")             #设置node名
    rospy.loginfo("Node has been started.")    #输出信息

    pub = rospy.Publisher("/turtle1/cmd_vel", Twist, queue_size=10) #一定要在对应topic下定义publisher。设置最大信息数=10。

    rate = rospy.Rate(2)                       #设置频率

    while not rospy.is_shutdown():             #本文刚开始的发包程序段
        msg = Twist()                          #定义对象
        msg.linear.x = 2.0                     #设置线性前进速度
        msg.angular.z = 1.0                    #2D平面只需要考虑绕Z轴旋转
        pub.publish(msg)                       #让publisher发送数据,数据就是msg
        rate.sleep()                           #循环

在与src同级的package.xml中加上我们用的包geometry_msgs:
在这里插入图片描述

ctrl+s 保存后退出,这里有几点需要注意

  1. from geometry_msgs.msg import Twist
    一定要与我们在rostopic info查看到的信息类型一致
  2. pub = rospy.Publisher(“/turtle1/cmd_vel”, Twist, queue_size=10)
    注意topic名称和对应的数据类型
  3. rospy.init_node和程序开始的#!/usr/bin/env python3一定要写
  4. 记得在package.xml中添加dependence

3. 运行Publisher查看状态

运行node:

rosrun ros_practice draw_circle.py

效果如下:
在这里插入图片描述
rostopic info 查看状态
在这里插入图片描述
看到 publisher 正常运行,用rqt_graph查看topic的拓扑结构:
在这里插入图片描述
观察到我们编写的/draw_circle作为 publisher 正常发送 topic,该 topic 名称为/turtle1/cmd_vel,而 listener 为/turtlesim

运行成功,我们下期再见!

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值