编程方法
了解了话题的基本原理,接下来我们就要开始编写代码啦。
创建工作空间
请大家先按照这个流程创建工作空间、下载课程的例程代码,并进行编译。
$ mkdir –p dev_ws/src
$ cd /userdata/dev_ws/src
$ git clone https://gitee.com/guyuehome/togetherros_tutorials.git
$ cd /userdata/dev_ws/
$ colcon build
运行示例程序
编译成功后,我们尝试运行话题通信的Hello World例程,在这个例程中,我们会先创建一个发布者,发布话题“chatter”,周期发送“Hello World”这个字符串,消息类型是ROS中标准定义的String,再创建一个订阅者,订阅“chatter”这个话题,从而接收到“Hello World”这个字符串。
$ source /opt/tros/local_setup.bash
$ source install/local_setup.bash
$ ros2 run learning_topic_cpp talker
$ ros2 run learning_topic_cpp listener
这就是TogetherROS系统中话题通信的方法,依然沿用了ROS2中话题通信的完整流程。
代码解析
发布者的实现方法
publisher_member_function.cpp:
#include < chrono >
#include < functional >
#include < memory >
#include < string >
#include "rclcpp/rclcpp.hpp"
#include "std_msgs/msg/string.hpp"
using namespace std::chrono_literals;
/* This example creates a subclass of Node and uses std::bind() to register a
* member function as a callback from the timer. */
class MinimalPublisher : public rclcpp::Node
{
public:
MinimalPublisher()
: Node("minimal_publisher"), count_(0)
{
publisher_ = this- >create_publisher< std_msgs::msg::String >("topic", 10);
timer_ = this- >create_wall_timer(
500ms, std::bind(&MinimalPublisher::timer_callback, this));
}
private:
void timer_callback()
{
auto message = std_msgs::msg::String();
message.data = "Hello, world! " + std::to_string(count_++);
RCLCPP_INFO(this- >get_logger(), "Publishing: '%s'", message.data.c_str());
publisher_- >publish(message);
}
rclcpp::TimerBase::SharedPtr timer_;
rclcpp::Publisher< std_msgs::msg::String >::SharedPtr publisher_;
size_t count_;
};
int main(int argc, char * argv[])
{
rclcpp::init(argc, argv);
rclcpp::spin(std::make_shared< MinimalPublisher >());
rclcpp::shutdown();
return 0;
}
订阅者的实现方法
subscriber_member_function.cpp:
#include < memory >
#include "rclcpp/rclcpp.hpp"
#include "std_msgs/msg/string.hpp"
using std::placeholders::_1;
class MinimalSubscriber : public rclcpp::Node
{
public:
MinimalSubscriber()
: Node("minimal_subscriber")
{
subscription_ = this- >create_subscription< std_msgs::msg::String >(
"topic", 10, std::bind(&MinimalSubscriber::topic_callback, this, _1));
}
private:
void topic_callback(const std_msgs::msg::String::SharedPtr msg) const
{
RCLCPP_INFO(this- >get_logger(), "I heard: '%s'", msg- >data.c_str());
}
rclcpp::Subscription< std_msgs::msg::String >::SharedPtr subscription_;
};
int main(int argc, char * argv[])
{
rclcpp::init(argc, argv);
rclcpp::spin(std::make_shared< MinimalSubscriber >());
rclcpp::shutdown();
return 0;
}
全部0条评论
快来发表一下你的评论吧 !