创建自定义消息
mkdir ~/workspace/src/more_interfaces/msg -p
在workspace/src目录中:
ros2 pkg create --build-type amen_cmake more_interfaces
cd more_interfaces
rm -rf src include
touch KeyBoardValue.msg //文件名首字母必须大写
在KeyBoardValue.msg中添加以下消息字段:
uint8 axle_x
uint8 axle_y
uint8 axle_z
变量名必须小写
编辑CmakeList.txt同下:
cmake_minimum_required(VERSION 3.8)
project(more_interfaces)
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)
# uncomment the following section in order to fill in
# further dependencies manually.
# find_package(<dependency> REQUIRED)
find_package(rosidl_default_generators REQUIRED)
set(msg_files
"msg/KeyBoardValue.msg"
)
rosidl_generate_interfaces(${PROJECT_NAME}
${msg_files}
)
ament_export_dependencies(rosidl_default_runtime)
ament_package()
在package.xml中添加以下内容:
<buildtool_depend>rosidl_default_generators</buildtool_depend>
<exec_depend>rosidl_default_runtime</exec_depend>
<member_of_group>rosidl_interface_packages</member_of_group>
cd ~/workspace
colcon build --packages-select more_interfaces
编译成功后,在~/workspace/install/more_interfaces/include/more_interfaces/more_interfaces/msg/下产生头文件,此头文件名称后续应用新创建的节点
创建新的节点
cd ~/workspace
ros2 pkg create --build-type ament_cmake --node-name NodeKeyBoardCtrl PkgKeyBoardCtrl
在 ~/workspace/src/PkgKeyBoardCtrl/src/NodeKeyBoardCtrl.cpp中添加:#include "more_interfaces/msg/key_board_value.hpp"
~/workspace/src/PkgKeyBoardCtrl/CmakeList.txt内容如下:
cmake_minimum_required(VERSION 3.8)
project(PkgKeyBoardCtrl)
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)
# uncomment the following section in order to fill in
# further dependencies manually.
# find_package(<dependency> REQUIRED)
find_package(rclcpp REQUIRED)
find_package(more_interfaces REQUIRED)
add_executable(NodeKeyBoardCtrl src/NodeKeyBoardCtrl.cpp)
ament_target_dependencies(NodeKeyBoardCtrl rclcpp more_interfaces)
target_include_directories(NodeKeyBoardCtrl PUBLIC
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
$<INSTALL_INTERFACE:include>)
target_compile_features(NodeKeyBoardCtrl PUBLIC c_std_99 cxx_std_17) # Require C99 and C++17
install(TARGETS NodeKeyBoardCtrl
DESTINATION lib/${PROJECT_NAME})
# rosidl_get_typesupport_target(cpp_typesupport_target ${PROJECT_NAME} rosidl_typesupport_cpp)
# target_link_libraries(publish_address_book "${cpp_typesupport_target}")
ament_package()
~/workspace/src/PkgKeyBoardCtrl/package.xml 添加如下内容:
<depend>rclcpp</depend>
<depend>more_interfaces</depend>
vscode会显示找不到头文件,配置vscode头文件包含路径如下:
"includePath": [
"${workspaceFolder}/**",
"/opt/ros/humble/include/**",
"~/workspace/install/more_interfaces/include/more_interfaces"
],
colcon build --packages-select PkgKeyBoardCtrl