Advertisement
Guest User

mavros_offboard

a guest
Jun 17th, 2018
235
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.63 KB | None | 0 0
  1. /**
  2. * @file offb_node.cpp
  3. * @brief Offboard control example node, written with MAVROS version 0.19.x, PX4 Pro Flight
  4. * Stack and tested in Gazebo SITL
  5. */
  6.  
  7. #include <ros/ros.h>
  8. #include <geometry_msgs/PoseStamped.h>
  9. #include <mavros_msgs/CommandBool.h>
  10. #include <mavros_msgs/SetMode.h>
  11. #include <mavros_msgs/State.h>
  12.  
  13. mavros_msgs::State current_state;
  14. void state_cb(const mavros_msgs::State::ConstPtr& msg){
  15. current_state = *msg;
  16. std::cout<<"good"<<std::endl;
  17. }
  18.  
  19. int main(int argc, char **argv)
  20. {
  21. ros::init(argc, argv, "offb_node");
  22. ros::NodeHandle nh;
  23.  
  24. ros::Subscriber state_sub = nh.subscribe<mavros_msgs::State>
  25. ("mavros/state", 10, state_cb);
  26. ros::Publisher local_pos_pub = nh.advertise<geometry_msgs::PoseStamped>
  27. ("mavros/setpoint_position/local", 10);
  28. ros::ServiceClient arming_client = nh.serviceClient<mavros_msgs::CommandBool>
  29. ("mavros/cmd/arming");
  30. ros::ServiceClient set_mode_client = nh.serviceClient<mavros_msgs::SetMode>
  31. ("mavros/set_mode");
  32.  
  33. //the setpoint publishing rate MUST be faster than 2Hz
  34. ros::Rate rate(20.0);
  35.  
  36. // wait for FCU connection
  37. while(ros::ok() && !current_state.connected){
  38. ros::spinOnce();
  39. rate.sleep();
  40. }
  41.  
  42. geometry_msgs::PoseStamped pose;
  43. pose.pose.position.x = 0;
  44. pose.pose.position.y = 0;
  45. pose.pose.position.z = 2;
  46.  
  47. //send a few setpoints before starting
  48. for(int i = 100; ros::ok() && i > 0; --i){
  49. local_pos_pub.publish(pose);
  50. ros::spinOnce();
  51. rate.sleep();
  52. }
  53.  
  54. mavros_msgs::SetMode offb_set_mode;
  55. offb_set_mode.request.custom_mode = "OFFBOARD";
  56.  
  57. mavros_msgs::CommandBool arm_cmd;
  58. arm_cmd.request.value = true;
  59.  
  60. ros::Time last_request = ros::Time::now();
  61.  
  62. while(ros::ok()){
  63. if( current_state.mode != "OFFBOARD" &&
  64. (ros::Time::now() - last_request > ros::Duration(5.0))){
  65. if( set_mode_client.call(offb_set_mode) &&
  66. offb_set_mode.response.mode_sent){
  67. ROS_INFO("Offboard enabled");
  68. }
  69. last_request = ros::Time::now();
  70. } else {
  71. if( !current_state.armed &&
  72. (ros::Time::now() - last_request > ros::Duration(5.0))){
  73. if( arming_client.call(arm_cmd) &&
  74. arm_cmd.response.success){
  75. ROS_INFO("Vehicle armed");
  76. }
  77. last_request = ros::Time::now();
  78. }
  79. }
  80.  
  81. local_pos_pub.publish(pose);
  82.  
  83. ros::spinOnce();
  84. rate.sleep();
  85. }
  86.  
  87. return 0;
  88. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement