ROS第 5 课 编写简单的发布器 Publisher

文章目录

  • 第 5 课 编写简单的发布器 Publisher

第 5 课 编写简单的发布器 Publisher

本节以创建一个velocity_publisher.py的(发布者)节点为例进行讲解。

  1. 输入指令“roscd beginner_hiwonder”,回车。进入beginner_hiwonder软件包。
  • roscd:移动到指定的 ROS 功能包目录
    在这里插入图片描述
  1. 输入指令“mkdir scripts”,回车。新建一个scripts目录存放Python脚本。
    在这里插入图片描述
  2. 输入指令“cd scripts/”,回车。
    在这里插入图片描述
  3. 输入指令“vi velocity_publisher.py”编辑程序,复制下面程序。如需修改,再按下“i”即可修改。修改完成,按下“Esc”,输入“:wq”保存并退出。
    在这里插入图片描述
#!/usr/bin/env python
# -*- coding: utf-8 -*-

# 这是一个在ROS(机器人操作系统)环境中的Python脚本,用于发布控制指令来移动名为'turtle1'的仿真乌龟。

import rospy  # 导入rospy模块,这是一个Python库,用于与ROS通信
from geometry_msgs.msg import Twist  # 从geometry_msgs包导入Twist消息类型,用于设置速度

# 定义velocity_publisher函数:这是主要的发布者函数
def velocity_publisher():
    # 初始化ROS节点,节点名为'velocity_publisher',anonymous=True可以确保你的节点有一个唯一的名字,防止节点名字冲突
    rospy.init_node('velocity_publisher', anonymous=True)
    
    # 创建一个Publisher对象,这个对象可以发布到'/turtle1/cmd_vel'话题,消息类型为Twist,队列长度设置为10
    turtle_vel_pub = rospy.Publisher('/turtle1/cmd_vel', Twist, queue_size=10)

    # 设置循环频率为10Hz
    rate = rospy.Rate(10)
    
    # 在ROS没有被关闭的情况下,循环执行以下操作
    while not rospy.is_shutdown():
        # 创建一个Twist类型的消息对象vel_msg
        vel_msg = Twist()
        
        # 设置vel_msg的线速度为0.5米/秒,角速度为0.2弧度/秒
        vel_msg.linear.x = 0.5
        vel_msg.angular.z = 0.2
        
        # 发布刚刚设置的速度消息,这会告诉乌龟开始移动
        turtle_vel_pub.publish(vel_msg)

        # 打印日志信息,显示当前发布的线速度和角速度
        rospy.loginfo("Publish turtle velocity command[%0.2f m/s, %0.2f rad/s]", 
                      vel_msg.linear.x, vel_msg.angular.z)
        
        # 根据上面设置的循环频率进行睡眠,确保有一致的发布速率
        rate.sleep()

# Python的标准模板,当这个脚本被执行而不是被导入为模块时,下面的代码将会运行
if __name__ == '__main__':
    try:
        # 尝试执行velocity_publisher函数
        velocity_publisher()
    except rospy.ROSInterruptException:
        # 如果捕获到ROSInterruptException异常,就忽略它(通常这意味着程序在rospy.signal_shutdown时被关闭)
        pass

ROS第 5 课 编写简单的发布器 Publisher_第1张图片
5) 输入指令“chmod +x velocity_publisher.py”回车,为保存的velocity_publisher.py赋予可执行权限。
在这里插入图片描述
6) 输入指令“roscore”回车,运行python文件之前,我们需要先打开节点管理器

  • roscore:启动 ROS Master 节点管理器

ROS第 5 课 编写简单的发布器 Publisher_第2张图片
7) 输入指令“rosrun beginner_hiwonder velocity_publisher.py”回车,运行python文件,也可以使用python指令去运行

  • rosrun:启动 ROS 节点

ROS第 5 课 编写简单的发布器 Publisher_第3张图片
8) 输入指令“rostopic list”回车,查看现在发布的有哪些话题

  • rostopic:确认 ROS 话题信息

在这里插入图片描述
9) 输入指令“rostopic echo /turtle1/cmd_vel”回车,查看话题信息
ROS第 5 课 编写简单的发布器 Publisher_第4张图片

到此,发布器编辑完成。

你可能感兴趣的:(ROS,机器人,ros操作系统)