ROS发布多边形话题PolygonStamped数据并在rviz中显示

ROS发布多边形话题PolygonStamped数据并在rviz中显示

wiki:rvizDisplayTypesPolygon
实验环境Ubuntu20.04 ROS(noetic)
1.新建工程

mkdir -p catkin_ws/src
cd catkin_ws/src
catkin_create_pkg polygon_demo roscpp geometry_msgs 
cd ..
catkin_make 

2.编辑主函数
路径:polygon_demo/src/publisher.cpp
topic名字为polygonpublisher
frame_id为map

#include  
#include 
#include 

int main (int argc, char **argv) 
{ 
    // 初始化ROS节点 节点名字
	ros::init (argc, argv, "polygonpublisher"); 
	
    // 节点句柄
	ros::NodeHandle nh; 

    // 发布消息 话题名字 队列大小
	ros::Publisher pub = nh.advertise<geometry_msgs::PolygonStamped>("polygonpublisher", 1);

    // 定义多边形对象
    geometry_msgs::PolygonStamped myPolygon;

    // 多边形数据 
    geometry_msgs::Point32 point;
    for(int i = 0; i < 10 ; i++)
    {
        point.x = i;
        point.y = 0;
        point.z = 0;
        myPolygon.polygon.points.push_back(point);
    }
    for(int i = 0; i < 10 ; i++)
    {
        point.x = 0;
        point.y = i;
        point.z = 0;
        myPolygon.polygon.points.push_back(point);
    }
    for(int i = 0; i < 10 ; i++)
    {
        point.x = 9;
        point.y = i;
        point.z = 0;
        myPolygon.polygon.points.push_back(point);
    }
    for(int i = 0; i < 10 ; i++)
    {
        point.x = i;
        point.y = 9;
        point.z = 0;
        myPolygon.polygon.points.push_back(point);
    }

    // frame id
    myPolygon.header.frame_id = "map";

    // 消息发布频率
    ros::Rate loop_rate(1);

	while (ros::ok()) 
	{ 
        // 广播
		pub.publish(myPolygon);
	    ros::spinOnce(); 
		loop_rate.sleep(); 
	 } 
	return 0; 
}

3.编辑CMakeLists.txt
路径:polygon_demo/CMakeLists.txt

cmake_minimum_required(VERSION 3.0.2)
project(polygon_demo)

find_package(catkin REQUIRED COMPONENTS
  geometry_msgs
  roscpp
)

catkin_package(
)
include_directories(
# include
  ${catkin_INCLUDE_DIRS}
)

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

4.编译

cd ~/catkin_ws 
catkin_make 

5.刷新环境

source ~/catkin_ws/devel/setup.bash

6.在终端运行roscore

roscore

7.运行polygonpublisher节点

rosrun polygon_demo polygonpublisher

8.运行rviz

rviz

9.在rviz中界面操作
Add -> By topic -> /polygonpublisher/Polygon -> OK
ROS发布多边形话题PolygonStamped数据并在rviz中显示_第1张图片10.运行结果
ROS发布多边形话题PolygonStamped数据并在rviz中显示_第2张图片

你可能感兴趣的:(C++,linux,ROS,c++)