ROS入门21讲(古月居) 学习笔记

Linux系统基础操作

cd命令
语法:cd<目录路径>
功能:改变工作目录.若没有指定’目录路径’,则回到用户的主目录
pwd命令
语法:pwd
功能:此命令显示当前工作目录的绝对路径.
mkdir命令
语法:mkdir[选项]<目录名称>
功能:创建一个目录.
ls命令
语法:ls[选项]<目录名称>
功能:列出目录的内容
touch命令
语法:touch[选项]<目录名称>
功能:改变文件或目录时间.
mv命令
语法:mv[选项]<源文件或目录><目的文件或目录>
功能:为文件或目录改名或将文件由一个目录移入另一个目录中
cp命令
语法:cp[选项]<源文件名称或目录名称><目的文件名称或目录名称>
功能:把给出的一个文件或目录拷贝到另一文件目录中,或者把多个源文件复制到目标目录中.
rm命令
语法:rm[选项]<文件名称或目录名称…>
功能:该命令的功能为删除一个目录中的一个或者多个文件或目录,它也可以将某个目录及其下的所有文件及子目录均删除.对于链接文件,只是删除了链接,原有文件均保持不变.
sudo命令
语法:sudo[选项][指令]
功能:以其他身份来执行指令.

ROS安装

1.软件和更新>ubuntu软件>点选前四个>选择合适的源>应用并重新载入
2.安装源(Ubuntu20.04)
sudo sh -c '. /etc/lsb-release && echo "deb http://mirrors.tuna.tsinghua.edu.cn/ros/ubuntu/ `lsb_release -cs` main" > /etc/apt/sources.list.d/ros-latest.list'
3.添加keys
sudo apt-key adv --keyserver 'hkp://keyserver.ubuntu.com:80' --recv-key C1CF6E31E6BADE8868B172B4F42ED6FBAB17C654
4.更新软件源
sudo apt update
5.安装
sudo apt-get install ros-noetic-desktop-full
6.配置变量
source /opt/ros/noetic/setup.bash
7.环境配置
echo "source /opt/ros/noetic/setup.bash" >> ~/.bashrc
source ~/.bashrc

ROS核心概念

节点(Node) --执行单元
*执行具体任务的进程,独立运行的可执行文件;
*不同节点可使用不同的编程语言,可分布运行在不同的主机;
*节点在系统中的名称必须是唯一的.

节点管理器(ROS Master) --控制中心
*为节点提供命名和注册服务;
*跟踪和记录话题/服务通信,辅助节点互相查找,建立连接;
*提供参数服务器,节点使用此服务器存储和检索时的参数.

话题(Topic) --异步通信机制
*节点间用来传输数据的重要总线;
*使用发布/订阅模型,数据由发布者传输到订阅者,同一个话题的订阅者或发布者可以不唯一.

消息(Mwssage) --话题数据
*具有一定的类型和数据结构,包括ROS提供的标准类型和用户自定义类型;
*使用编程语言无关的.msg文件,编译过程中生成对应的代码文件.

服务(Service) --同步通信机制
*使用客户端/服务器(C/S)模型,客户端发送请求数据,服务器完成处理后返回问答数据;
*使用编程语言无关的.srv文件定义请求和应答数据结构,编译过程中生成对应的代码文件.

参数(Parameter) --全局共享字典
*可通过网络访问的共享,多变量字典;
*节点使用此服务器来储存和检索运行时的参数;
*适合存储静态,非二进制的配置参数,不适合存储动态配置的数据.

功能包(Package)
*ROS软件中的基本单元,包含节点源码,配置文件,数据定义等

功能包清单(Package manifest)
*记录功能包的基本信息,包含作者信息,许可信息,依赖选项.编译标志等

元功能包(Meta Packages)
*组织多个用于同一目的的功能包

ROS命令行工具的使用

启动ROS Master

roscore

启动小海龟仿真器

rosrun turtlesim turtlesim_node

启动海龟控制节点

rosrun turtlesim turtle_teleop_key

显示系统计算图

rqt_graph

显示系统节点相关信息

   rosnode
rosnode is a command-line tool for printing information about ROS Nodes.

Commands:
	rosnode ping	test connectivity to node
	rosnode list	list active nodes
	rosnode info	print information about node
	rosnode machine	list nodes running on a particular machine or list machines
	rosnode kill	kill a running node
	rosnode cleanup	purge registration information of unreachable nodes

显示系统话题相关信息

rostopic
rostopic is a command-line tool for printing information about ROS Topics.

Commands:
	rostopic bw	    display bandwidth used by topic
	rostopic delay	display delay of topic from timestamp in header
	rostopic echo	print messages to screen
	rostopic find	find topics by type
	rostopic hz	    display publishing rate of topic    
	rostopic info	print information about active topic
	rostopic list	list active topics
	rostopic pub	publish data to topic
	rostopic type	print topic or field type

显示系统消息相关信息

rosmsg
rosmsg is a command-line tool for displaying information about ROS Message types.

Commands:
	rosmsg show	    Show message description
	rosmsg info	    Alias for rosmsg show
	rosmsg list	    List all messages
	rosmsg md5	    Display message md5sum
	rosmsg package	List messages in a package
	rosmsg packages	List packages that contain messages

显示系统服务相关信息

rosservice 
Commands:
	rosservice args	print service arguments
	rosservice call	call the service with the provided args
	rosservice find	find services by service type
	rosservice info	print information about service
	rosservice list	list active services
	rosservice type	print service type
	rosservice uri	print service ROSRPC uri

数据记录.复现

rosbag
Usage: rosbag <subcommand> [options] [args]

A bag is a file format in ROS for storing ROS message data. The rosbag command can record, replay and manipulate bags.

Available subcommands:
   check  	    Determine whether a bag is playable in the current system, or if it can be migrated.
   compress  	Compress one or more bag files.
   decompress  	Decompress one or more bag files.
   decrypt  	Decrypt one or more bag files.
   encrypt  	Encrypt one or more bag files.
   filter  	    Filter the contents of the bag.
   fix  	    Repair the messages in a bag file so that it can be played in the current system.
   help  
   info  	    Summarize the contents of one or more bag files.
   play  	    Play back the contents of one or more bag files in a time-synchronized fashion.
   record  	    Record a bag file with the contents of specified topics.
   reindex  	Reindexes one or more bag files.

创作工作空间与功能包

工作空间(workspace)是一个存放工程开发相关文件的文件夹.
*src:代码空间(Source Space)
*build:编译空间(Build Space)
*devel:开发空间(Development Space)
*instll:安装空间(Install Space)
创建工作空间

mkdir catkin_ws
cd catkin_ws/
mkdir src
cd src/
catkin_init_workspace

编译工作空间

cd ..
catkin_make
catkin_make install

创建功能包

#语法
#catkin_create_pkg<package_name>[depend1][depend2][depend3]
cd src/
catkin_create_pkg test_pkg std_msgs rospy roscpp

编译功能包

cd ..
catkin_make

设置环境变量

source devel/setup.bash

检查环境变量

echo $ROS_PACKAGE_PATH

备注
同一个工作空间下,不允许存在同名功能包;
不同工作空间下,允许存在同名功能包.

发布者Publisher的编程实现

创建功能包

cd ~/catkin_ws/src
catkin_creat_pkg learning_topic roscpp rospy std_msgs geometry_msgs turtlesim

创建发布者代码(C++)
如何实现一个发布者
*初始化ROS节点
*向ROS Master注册节点信息,包括发布的话题名和话题中的消息类型
*创建消息数据
*按照一定频率循环发布消息

//创建cpp文件
cd learning_topic/src/
touch velocity_publisher.cpp
//代码
/**
 * 该例程将发布turtle1/cmd_vel话题,消息类型geometry_msgs::Twist
 */
 
#include <ros/ros.h>
#include <geometry_msgs/Twist.h>

int main(int argc, char **argv)
{
   
    // ROS节点初始化
    ros::init(argc, argv, "velocity_publisher");

    // 创建节点句柄
    ros::NodeHandle n;

    // 创建一个Publisher,发布名为/turtle1/cmd_vel的topic,消息类型为geometry_msgs::Twist,队列长度10
    ros::Publisher turtle_vel_pub = n.advertise<geometry_msgs::Twist>("/turtle1/cmd_vel", 10);

    // 设置循环的频率
    ros::Rate loop_rate(10);

    int count = 0;
    while (ros::ok())
    {
   
        // 初始化geometry_msgs::Twist类型的消息
        geometry_msgs::Twist vel_msg;
        vel_msg.linear.x = 0.5;
        vel_msg.angular.z = 0.2;

        // 发布消息
        turtle_vel_pub.publish(vel_msg);
        ROS_INFO("Publsh turtle velocity command[%0.2f m/s, %0.2f rad/s]", 
                vel_msg.linear.x, vel_msg.angular.z);

        // 按照循环频率延时
        loop_rate.sleep();
    }

    return 0;
}

配置发布者代码编译规则
如何配置CMakeLists.txt中的编译规则
*设置需要编译的代码和生成的可执行文件
*设置链接库.

//添加到# Install ##正上方
add_executable(velocity_publisher src/velocity_publisher.cpp)
target_link_libraries(velocity_publisher ${
   catkin_LIBRARIES})

编译并运行发布者

//编译
cd ~/catkin_ws
catkin_make
//打开home文件夹,ctrl+H显示隐藏文件,找到.bashrc文件
//打开.bashrc,并在文件的最后添加以下这段话
//source /home/tfb/catkin_ws/devel/setup.bash
//再重启终端即可。这样每次编译(catkin_make)之后就不需要再写source devel/setup.bash了
source devel/setup.bash
roscore
//新开一个终端,开启turtlesim
rosrun turtlesim turtlesim_node
//新开一个终端,运行发布者cpp程序
rosrun learning_topic velocity_publisher
//编译cpp生成的文件在home/catkin_ws/devel/lib/learning_topic下面

备注
错误:[rospack] Error: package ‘learning_service’ not found
解决方案:
手动配置环境变量,具体操作如下
//打开home文件夹,ctrl+H显示隐藏文件,找到.bashrc文件
//打开.bashrc,并在文件的最后添加以下这段话
//source /home/tfb/catkin_ws/devel/setup.bash
//再重启终端即可。这样每次编译(catkin_make)之后就不需要再写source devel/setup.bash了
python语言实现

#为了与cpp文件存放的地方——src文件夹区分。在/home/catkin_ws/src/learning_topic/下新建一个scripts文件夹,用来存放py文件
#创建py文件
touch velocity_publisher.py
#代码
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# 该例程将发布turtle1/cmd_vel话题,消息类型geometry_msgs::Twist

import rospy
from geometry_msgs.msg import Twist

def velocity_publisher():
    # ROS节点初始化
    rospy.init_node('velocity_publisher', anonymous=True)

    # 创建一个Publisher,发布名为/turtle1/cmd_vel的topic,消息类型为geometry_msgs::Twist,队列长度10
    turtle_vel_pub = rospy.Publisher('/turtle1/cmd_vel', Twist, queue_size=10)

    #设置循环的频率
    rate = rospy.Rate(10) 

    while not rospy.is_shutdown():
        # 初始化geometry_msgs::Twist类型的消息
        vel_msg = Twist()
        vel_msg.linear.x = 0.5
        vel_msg.angular.z = 0.2

        # 发布消息
        turtle_vel_pub.publish(vel_msg)
        rospy.loginfo("Publsh turtle velocity command[%0.2f m/s, %0.2f rad/s]", 
                vel_msg.linear.x, vel_msg.angular.z)

        # 按照循环频率延时
        rate.sleep()

if __name__ == '__main__':
    try:
        velocity_publisher()
    except rospy.ROSInterruptException:
        pass

#在ros下运行python文件一定要注意待执行的python文件有可执行权限
#python不要配置代码编译规则
#其余步骤参考上述cpp文件流程

备注:
错误:import-im6.q16: not authorized `rospy’ @ error/constitute.c/WriteImage/1037.
解决方案:
在py文件前面添加#!/usr/bin/env python
#!/usr/bin/env python这种用法是为了防止操作系统用户没有将python装在默认的/usr/bin路径里。 当系统看到这一行的时候,首先会到env设置(环境变量)里查找python的安装路径,再调用对应路径下的解释器程序完成操作。

订阅者Subscriber的编程实现

创建订阅者代码(C++)
如何实现一个订阅者
*初始化ROS节点;
*订阅需要的话题;
*循环等待话题消息,接受到消息后进入回调函数;
*在回调函数中完成消息处理.

//创建cpp文件
cd learning_topic/src/
touch velocity_publisher.cpp
//代码
/**
 * 该例程将订阅/turtle1/pose话题,消息类型turtlesim::Pose
 */
 
#include <ros/ros.h>
#include "turtlesim/Pose.h"

// 接收到订阅的消息后,会进入消息回调函数
void poseCallback(const turtlesim::Pose::ConstPtr& msg)
{
   
    // 将接收到的消息打印出来
    ROS_INFO("Turtle pose: x:%0.6f, y:%0.6f", msg->x, msg->y);
}

int main(int argc, char **argv)
{
   
    // 初始化ROS节点
    ros::init(argc, argv, "pose_subscriber");

    // 创建节点句柄
    ros::NodeHandle n;

    // 创建一个Subscriber,订阅名为/turtle1/pose的topic,注册回调函数poseCallback
    ros::Subscriber pose_sub = n.subscribe("/turtle1/pose", 10, poseCallback);

    // 循环等待回调函数
    ros::spin();

    return 0;
}

编译并运行订阅者

//配置CMakeLists.txt
add_executable(pose_subscriber src/pose_subscriber.cpp)
target_link_libraries(pose_subscriber ${
   catkin_LIBRARIES})
//编译并运行
cd ~/catkin_ws
catkin_make
source devel/setup.bash
roscore
//新开一个终端,开启turtlesim
rosrun turtlesim turtlesim_node
//新开一个终端,运行发布者cpp程序
rosrun learning_topic pose_subscriber
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# 该例程将订阅/turtle1/pose话题,消息类型turtlesim::Pose

import rospy
from turtlesim.msg import Pose

def poseCallback(msg):
    rospy.loginfo("Turtle pose: x:%0.6f, y:%0.6f", msg.x, msg.y)

def pose_subscriber():
    # ROS节点初始化
    rospy.init_node('pose_subscriber', anonymous=True)

    # 创建一个Subscriber,订阅名为/turtle1/pose的topic,注册回调函数poseCallback
    rospy.Subscriber("/turtle1/pose", Pose, poseCallback)

    # 循环等待回调函数
    rospy.spin()

if __name__ == '__main__':
    pose_subscriber()

话题消息的定义与使用

定义msg文件

//在文件夹learning_topic中新建一个命名为msg的文件夹,存放消息类文件,方便管理
//创建.msg文件 touch Person.msg
//打开该文件,输入以下信息后保存
string name
uint8 sex
uint8 age

uint8 unknown = 0
uint8 male = 1
uint8 female = 2
//这里写的并不是cpp,也不是python。但他在编译过程中会由ros自动编译成cpp或python

在package.xml中添加功能包依赖

//打开文件夹learning_topic,打开package.xml
//gedit package.xml
//保存到最下方/<build_depend>类中
<build_depend>message_generation</build_depend>
<exec_depend>message_runtime</exec_depend>
//<build_depend>用于添加编译依赖,这里添加message_generation功能包
//<exec_depend<用于添加执行依赖,这里添加message_runtime功能包

在CMakeLists.txt添加编译选项

//打开文件夹learning_topic,打开CMakeLists.txt。
//在最上方的find_package中添加以下语句
message_generation
//找到Declare ROS dynamic reconfigure parameters的位置,在上方添加以下语句
add_message_files(FILES Person.msg)
generate_messages(DEPENDENCIES std_msgs)
//第一句,告诉编译器Person.msg是我们定义的消息接口
//第二句,告诉编译器在编译Person.msg文件的时候,需要依赖ROS哪些已有的库或者包。
//找到catkin specific configuration(即Build上方),添加以下语句
CATKIN_DEPENDS geometry_msgs roscpp rospy std_msgs turtlesim message_runtime

编译生成语言相关文件

//回到工作空间的根目录catkin_ws下,打开命令行,尝试进行编译。输入指令
catkin_make

创建publisher和subscriber

//person_publisher.cpp
/**
 * 该例程将发布/person_info话题,自定义消息类型learning_topic::Person
 */
 
#include <ros/ros.h>
//!!!!!关键!!!!!
#include "learning_topic/
  • 46
    点赞
  • 307
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值