编程语言
首页 > 编程语言> > ROS学习笔记(一)------话题编程(一)

ROS学习笔记(一)------话题编程(一)

作者:互联网

目录

一、基础知识

二、工作空间与功能包

三、发布者的编程实现

四、订阅者的编程实现


一、基础知识

二、工作空间与功能包

工作空间:

1.创建工作空间

$mkdir -p ~/catkin_ws/src
$cd ~/catkin/src
$catkin_init_workspace

2.编译工作空间

$cd ~/catkin_ws/
$catkin_make

//在生成install安装空间
$catkin_make install

3.设置环境变量

$source devel/setup.bash

4.检查环境变量

$echo $ROS_PACKAGE_PATH

功能包:

注意:功能包是放置源码的最小单元,不能直接将源码放置src中。

1.创建功能包

$cd ~/catkin_ws/src
$catkin_create_pkg test_pkg std_msgs rospy roscpp

2.编译功能包

$cd ~/catkin_ws
$catkin_make
$source ~/catkin_ws/devel/setup.bash

三、发布者的编程实现

 1、创建功能包

$cd ~/catkin_ws/src
$catkin_create_pkg learning_topic rosscpp rospy std_msgs geometry_msgs turtlesim

2、创建发布者

将编写好的发布者的源码放置在~/catkin_ws/src/learning_topic/src

 velocity_publisher.cpp

#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
#########
##build##
#########

add_executable(velocity_publisher src/velocity_publisher.cpp)
target_link_libraries(velocity_publisher ${catkin_LIBRARIES})

编译并运行发布者

$cd ~/catkin_ws
$catkin_make
//执行程序前一定要设置环境变量
$source devel/setup.bash
$roscore
$rosrun turtlesim turtlesim_node
$rosrun learning_topic velocity_publisher

四、订阅者的编程实现

 1、实现订阅者

pose_subscriber.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
#########
##build##
#########

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
$rosrun turtlesim turtlesim_node
$rosrun learning_topic pose_subscriber

 

标签:ros,catkin,pose,编程,------,vel,ROS,turtlesim
来源: https://blog.csdn.net/Jwfaikeyan/article/details/121372994