其他分享
首页 > 其他分享> > ROS-常用snippet

ROS-常用snippet

作者:互联网

publisher

ros::Publisher chatter_pub = n.advertise<std_msgs::String>("chatter", 1000);// 定义一个话题发布器
std_msgs::String str;
str.data = "hello world";
chatter_pub.publish(msg);  // 调用.publish()发布消息

消息msg的定义既可以使用普通形式可以使用指针的形式

ros::Publisher pub = nh.advertise<std_msgs::String>("topic_name", 5);// 定义一个话题发布器
std_msgs::StringPtr str(new std_msgs::String);
str->data = "hello world";
pub.publish(msg);  // 调用.publish()发布消息

Subscriber

ros::Subscriber sub = n.subscribe("chatter", 1000, chatterCallback);
void chatterCallback(const std_msgs::String::ConstPtr& msg)
{  
ROS_INFO("I heard: [%s]", msg->data.c_str());
}

callback回调函数

void callback(const boost::shared_ptr<Message const>&);
void callback(const std_msgs::StringConstPtr&);
void callback(const std_msgs::String::ConstPtr&);

对于每一种消息,都由共享指针的typedef方式,所以std_msgs::StringConstPtr和std_msgs::StringPtr都是可以使用的;

关联callback函数的时候,选择的类型

  1. callback: 普通函数
void callback(const std_msgs::StringConstPtr& str){...}
ros::Subscriber sub = nh.subscribe("my_topic", 1, callback);
  1. callback: class method 类方法形式
void Foo::callback(const std_msgs::StringConstPtr& message){}
Foo foo_object;
ros::Subscriber sub = nh.subscribe("my_topic", 1, &Foo::callback, &foo_object);
  1. callback: functor object 【不常用】 (A functor object is a class that declares operator())
class Foo{
public:
    void operator()(const std_msgs::StringConstPtr& message){}
};
ros::Subscriber sub = nh.subscribe<std_msgs::String>("my_topic", 1, Foo());

boost::bind()绑定callback函数

  1. callback函数
// 回调函数的定义中,有三个形参
void callback02(const turtlesim::PoseConstPtr& msg, int x, int y){}  
// subscriber
ros::Subscriber pose_sub = n.subscribe<turtlesim::Pose>("/turtle1/pose", 2, boost::bind(&callback02, _1, input_x, input_y)); 

ROS package CMakeLists.txt

cmake_minimum_required(VERSION 2.8.3)
project(beginner_tutorials)
## Find catkin and any catkin packages
find_package(catkin REQUIRED COMPONENTS roscpp rospy std_msgs genmsg)
## Declare ROS messages and services
add_message_files(DIRECTORY msg FILES Num.msg)
add_service_files(DIRECTORY srv FILES AddTwoInts.srv)
## Generate added messages and services
generate_messages(DEPENDENCIES std_msgs)
## Declare a catkin package
catkin_package()
## 可执行文件添加
add_executable(talker src/talker.cpp)
target_link_libraries(talker ${catkin_LIBRARIES})
add_dependencies(talker beginner_tutorials_generate_messages_cpp)

add_executable(listener src/listener.cpp)
target_link_libraries(listener ${catkin_LIBRARIES})
add_dependencies(listener beginner_tutorials_generate_messages_cpp)

标签:std,常用,const,msgs,void,snippet,callback,msg,ROS
来源: https://www.cnblogs.com/leaver/p/16456943.html