当前位置:网站首页>Ros2 preliminary: basic communication with topic
Ros2 preliminary: basic communication with topic
2022-07-26 05:41:00 【Mr anhydrous】
One 、 summary
For topic communication , I've learned a little ROS Knowledge is not strange , However , Turn it into ROS2 Realization , You need to walk again honestly , This is because ROS2 Mechanism and ROS1 The difference is too big ;ROS2 The level of our development team is higher ,ROS2 Our code is more abstract , Therefore, we need to pay more energy to practice . For never learned ROS1 Of , I suggest you directly from ROS2 Learn the , This saves a lot of energy . Study ROS2 The more practical reason is , Many navigation models are ROS2 The establishment of a , Don't understand, ROS2 It will be difficult to understand . good , This article will demonstrate how to generate a Topic Publisher , And a receiver's development process .
Two 、 Scenario setting
2.1 Online chess machine
( If used ros2 Play chess , that , The first step requires digestion topic signal communication )
3、 ... and 、 Realization
3.1 New workspace
mkdir -p mytry_ws/src
cd mytry_ws/src
mkdir -p: Create directory recursively , Even if the parent directory does not exist , The directory is automatically created at the directory level
3.2 Create work package
cd mytry_ws/src
ros2 pkg create mytopic --build-type ament_cmake --dependencies rclcpp std_msgsPay attention to the grammar :
ros2 pkg create mytopic --build-type ament_cmake--dependencies rclcpp std_msgs
There are three substantive parameters above :
- mytopic: Package name
- --build-type ament_cmake: The compiler is ament_cmake
- --dependencies rclcpp std_msgs: The dependent package is specified as rclcpp、std_msgs;
stay
ros2_ws/src/mytopic/srcCreate lambda.cppand sublambda.cpp
3.3 lambda.cpp Node creation
#include <chrono>
#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 a fancy C++11 lambda
* function to shorten the callback syntax, at the expense of making the
* code somewhat more difficult to understand at first glance. */
class MinimalPublisher : public rclcpp::Node
{
public:
MinimalPublisher()
: Node("minimal_publisher"), count_(0)
{
publisher_ = this->create_publisher<std_msgs::msg::String>("topic", 10);
auto timer_callback =
[this]() -> void {
auto message = std_msgs::msg::String();
message.data = "Hello, world! " + std::to_string(this->count_++);
RCLCPP_INFO(this->get_logger(), "Publishing: '%s'", message.data.c_str());
this->publisher_->publish(message);
};
timer_ = this->create_wall_timer(500ms, timer_callback);
}
private:
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;
}
- Time operator
These operators are in the namespace std::literals::chrono_literals In a statement , The text and chrono_literals Are all inline namespaces . You can use the namespace std::literals、 using namespace std std::chrono_literals And use namespaces std::literals::chrono_literals To access these operators .
Besides , In namespace std::chrono in , Instructions using namespace literals::chrono_literals; Provided by the standard library , So if programmers use using namespace std::chrono; In order to visit chrono Classes in the library , The corresponding literal operators also become visible .
- Your class inherits Node Then it becomes a formal node
class MinimalPublisher : public rclcpp::NodeIn the constructor , Directly define the node name with the parent class ; And other attributes : Counter
MinimalPublisher()
: Node("minimal_publisher"), count_(0)- Define the publisher that sends the string , The maximum length of the string is 10;
3.4 sublambda.cpp Node creation
#include <memory>
#include "rclcpp/rclcpp.hpp"
#include "std_msgs/msg/string.hpp"
class MinimalSubscriber : public rclcpp::Node
{
public:
MinimalSubscriber()
: Node("minimal_subscriber")
{
subscription_ = this->create_subscription<std_msgs::msg::String>(
"topic",
10,
[this](std_msgs::msg::String::UniquePtr msg) {
RCLCPP_INFO(this->get_logger(), "I heard: '%s'", msg->data.c_str());
});
}
private:
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;
}3.5 modify Cmakelist.txt
1) Dependency append
If... Is not added when creating a new function package --dependencies rclcpp std_msgs Other function packages , You need to manually add : ( It can be anywhere )
- find_package(rclcpp REQUIRED)
- find_package(std_msgs REQUIRED)
2) Executable section definition
- add_executable()
Let the compiler compile Customer.cpp and KFC.cpp These two documents . And generate executable Customer_node and KFC_node
- ament_target_dependencies
Add compiled dependencies
add_executable(publisher_lambda lambda.cpp)
ament_target_dependencies(publisher_lambda rclcpp std_msgs)
add_executable(subscriber_lambda sublambda.cpp)
ament_target_dependencies(subscriber_lambda rclcpp std_msgs)3) Install the compiled file to the correct path
install(TARGETS
publisher_lambda
subscriber_lambda
DESTINATION lib/${PROJECT_NAME}
)3.6 modify package.xml
similarly , When you create a new function package, you don't add --dependencies rclcpp std_msgs Other function packages , You need to manually add , Placed in <package> Under the label
<depend>rclcpp</depend>
<depend>std_msgs</depend>
You can also modify the following statements , It has nothing to do with the implementation function , But it's best to write it all
<version>0.0.0</version>
<description>TODO: Package description</description>
<maintainer email="[email protected]">fanziqi</maintainer>
<license>TODO: License declaration</license>
3.7 compile
- Be careful : Compile in packages , Specify which package , Just compile which .
--packages-select Specify compile customer_and_kfc Function pack
- colcon build --packages-select mytopic
win10 Access terminal :

start-up ROS2 Environmental settings :
call C:\opt\ros\foxy\x64\local_setup.bat
colcon build
3.8 Refresh the environment
- stay ubuntu Next :
[echo "source /ros2_ws/install/setup.zsh" >> ~/.bashrc ]
source ~/.bashrc
- stay Window10 Next :
cd mytry_ws
call install/setup.bat
3.9 function
Create a new terminal window , Run the publishing node
ros2 run mytopic publisher_lambdaCreate another terminal , Run the listening node
ros2 run mytopic subscriber_lambda You should be able to see :

3.10 Relevant tool testing
- rqt_graph
Use rqt_graph This tool can visually display the connection between nodes and topics .
Another terminal , Input
rqt_graph
Upper figure It shows ROS Calculate the network form of the graph , You can clearly see what the input and output of a node are .
- View all topics in the system
ros2 topic listC:\Windows\System32>ros2 topic list
/parameter_events
/rosout
/topic
I want to check the data type transmitted by each topic , Then add -t
- ros2 topic list -t
C:\Windows\System32>ros2 topic list -t
/parameter_events [rcl_interfaces/msg/ParameterEvent]
/rosout [rcl_interfaces/msg/Log]
/topic [std_msgs/msg/String]
Output real-time topic content
- ros2 topic echo /topic
View topic information
- ros2 topic info /hamburger
C:\Windows\System32>ros2 topic info /topic
Type: std_msgs/msg/String
Publisher count: 1
Subscription count: 1
View the specific data structure of this data type through the following instructions
- ros2 interface show std_msgs/msg/String
You can see , std_msgs/msg/String It contains string data
Post a topic message
- ros2 topic pub /topic std_msgs/String"data: Hello ROS Developers"

Be careful : This sentence is difficult , Need more attention , Such as turtle's release statement :
ros2 topic pub --rate 1 /turtle1/cmd_vel geometry_msgs/msg/Twist "{linear: {x: 2.0, y: 0.0, z: 0.0}, angular: {x: 0.0, y: 0.0, z: 1.8}}"
Check the release frequency of a topic
- ros2 topic hz /topic

References :
ROS2 Introductory tutorial ——14. establish ROS2 Function pack - Ancient Moon House (guyuehome.com)
边栏推荐
- The refurbishment and counterfeiting of chips have made people feel numb
- How can red star Macalline design cloud upgrade the traditional home furnishing industry in ten minutes to produce film and television level interior design effects
- Recommended reading: how can testers get familiar with new businesses quickly?
- Mongodb tutorial Chapter 08 comparison operators
- C language - Advanced pointer
- Why can't lpddr completely replace DDR?
- Development projects get twice the result with half the effort, a large collection of open source STM32 driver Libraries
- Unity Profiler
- 秋招-准备计划
- 数仓搭建-DIM层
猜你喜欢

Efficient, reliable and safe open source solution for serial communication

How can red star Macalline design cloud upgrade the traditional home furnishing industry in ten minutes to produce film and television level interior design effects

Redis transaction

这种项目,最好别接!

Redis master-slave replication

YOLOV3预备工作

Redis持久化-AOF

IVR在voip电话系统的应用与价值

Knowledge points of Polymer Physics

DOM操作--操作节点
随机推荐
动态内存管理及柔性数组
How can red star Macalline design cloud upgrade the traditional home furnishing industry in ten minutes to produce film and television level interior design effects
《MongoDB入门教程》第08篇 比较运算符
It's enough for newcomers to learn how to do functional tests
LAMP架构
TZC 1283: simple sort Bubble Sort
Use latex to typeset multiple-choice test paper
How to name the project version number? Looks like cow b
Data warehouse construction -dim floor
DOM operation -- operation node
MongonDB API使用
高手是怎样炼成的?
调试利器!一款轻量级日志库 log.c
三本毕业,三年嵌入式软件的心路历程
Benji Banas launched the second season of earn while playing bonus activities, supporting the use of multiple Benji passes!
C language explanation series - understanding of functions (4) declaration and definition of functions, simple exercises
TZC 1283: simple sorting - function method
Hack the box -sql injection fundamentals module detailed Chinese tutorial
Usage and common problems of SIP softphone registered with SIP account
DOM操作--操作节点