编译:
colcon build --packages-select tesk_package_zp
运行:
ros2 run tesk_package_zp communication_test
ros2 interface package sensor_msgs
如果需要使用ros2 run 来跑代码,则需要加入如下所示的install命令
install(TARGETS
communication_test
DESTINATION lib/${PROJECT_NAME})
cmake_minimum_required(VERSION 3.8)
project(tesk_package_zp)
if(CMAKE_COMPILER_IS_GNUCXX OR CMAKE_CXX_COMPILER_ID MATCHES "Clang")
add_compile_options(-Wall -Wextra -Wpedantic)
endif()
# find dependencies
find_package(ament_cmake REQUIRED)
find_package(rclcpp REQUIRED)
find_package(std_msgs REQUIRED)
find_package(sensor_msgs REQUIRED)
if(BUILD_TESTING)
find_package(ament_lint_auto REQUIRED)
# the following line skips the linter which checks for copyrights
# comment the line when a copyright and license is added to all source files
set(ament_cmake_copyright_FOUND TRUE)
# the following line skips cpplint (only works in a git repo)
# comment the line when this package is in a git repo and when
# a copyright and license is added to all source files
set(ament_cmake_cpplint_FOUND TRUE)
ament_lint_auto_find_test_dependencies()
endif()
#add_executable(communication_test src/main.cpp)
#add_executable(communication_test src/pub_test.cpp)
add_executable(communication_test src/ads_communication_test.cpp)
ament_target_dependencies(communication_test rclcpp std_msgs sensor_msgs)
install(TARGETS
communication_test
DESTINATION lib/${PROJECT_NAME})
ament_package()
publisher 调试代码
#include "rclcpp/rclcpp.hpp"
#include "std_msgs/msg/string.hpp"
//#include "std_msgs/Float64MultiArray.h"
//#include "sensor_msgs/msg/JointState.hpp"
#include "std_msgs/msg/UInt32.hpp"
using namespace std::chrono_literals;
int main(int argc, char * argv[])
{
rclcpp::init(argc, argv);
auto node = rclcpp::Node::make_shared("communication_test_node");
auto pub = node->create_publisher<std_msgs::msg::String>("/pub_sub", 10);
std_msgs::msg::String myMessage;
size_t counter{0};
rclcpp::WallRate loop_rate(500ms);
while (rclcpp::ok())
{
myMessage.data = "zp Hello, ros2 world! " + std::to_string(counter++);
RCLCPP_INFO(node->get_logger(), "Publishing: '%s'", myMessage.data.c_str());
try
{
pub->publish(myMessage);
rclcpp::spin_some(node);
} catch (const rclcpp::exceptions::RCLError & e)
{
RCLCPP_ERROR(node->get_logger(), "Errore type : %s", e.what());
}
loop_rate.sleep();
}
rclcpp::shutdown();
return 0;
}