ROS編程示例---完整輸出烏龜位姿

運行roscore,turtlesim

//訂閱turtle位姿並輸出到屏幕
#include <ros/ros.h>
#include <iomanip>
#include <turtlesim/Pose.h>//使用了turtlesim下的話題pose
#include <ros/console.h>//使用判斷輸出語句_COND

//回調函數
void poseMessageReceived(const turtlesim::Pose& msg)
{
  bool Safe;
  int x=(int)msg.x;
  int y=(int)msg.y;
  if(x > 0 && y > 0 && x < 11 && y < 11)Safe=true;
  else Safe=false;
  if(Safe)
  {
    //正常消息通知
    ROS_INFO_STREAM(std::setprecision(2)<<std::fixed<<"position =("<<msg.x<<","<<msg.y<<")"<<" *direction ="<<msg.theta);
  }
  else
  {
    //警示的內容包括四個角和四條邊
    //設置輸出格式
    std::setprecision(2);
    std::fixed;
    //左下角警示
    ROS_WARN_STREAM_COND(x==0&&y==0,"Oh, no! x = "<<msg.x<<",y = "<<msg.y<<", This is bad");
    //右上角警示
    ROS_WARN_STREAM_COND(x==11&&y==11,"Oh, no! x = "<<msg.x<<",y = "<<msg.y<<", This is bad");
    //左上角警示
    ROS_WARN_STREAM_COND(x==0&&y==11,"Oh, no! x = "<<msg.x<<",y = "<<msg.y<<", This is bad");
    //右下角警示
    ROS_WARN_STREAM_COND(x==11&&y==0,"Oh, no! x = "<<msg.x<<",y = "<<msg.y<<", This is bad");
    //右牆警示
    ROS_WARN_STREAM_COND(x==11&&y!=0&&y!=11,"Oh, no! x = "<<msg.x<<", This is bad");
    //左牆警示
    ROS_WARN_STREAM_COND(x==0&&y!=11&&y!=0,"Oh, no! x = "<<msg.x<<", This is bad");
    //下牆警示
    ROS_WARN_STREAM_COND(y==0&&x!=11&&x!=0,"Oh, no! y = "<<msg.y<<", This is bad");
    //上牆警示
    ROS_WARN_STREAM_COND(y==11&&x!=11&&x!=0,"Oh, no! y = "<<msg.y<<", This is bad");

  }
}
int main(int argc,char **argv)
{
  ros::init(argc,argv,"subscribe_to_pose");//創建節點

  ros::NodeHandle n;//創建節點句柄

  //創建訂閱對象
  ros::Subscriber sub = n.subscribe("turtle1/pose",1000,&poseMessageReceived);

  //spin函數用於程序下面沒有任何操作,要是有操作的話,最好選擇spinOnece();
  ros::spin();
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章