Study notes: ROS usage experience (creating function packages)

To write a node in ROS using C++, you need to follow the following steps:

1. Create a ROS workspace (skip this step if you already have one). Open a terminal and execute the following command:

mkdir -p ~/catkin_ws/src
cd ~/catkin_ws/
catkin_make

2. Enter the directory of the ROS workspace srcand create a new package. Execute the following command:

cd ~/catkin_ws/src
catkin_create_pkg my_package_name roscpp std_msgs

This will create a my_package_namenew package called , with roscppand added std_msgsas dependencies.

3. Go into the package's directory and create a my_node.cppnew file called. Execute the following command:

cd ~/catkin_ws/src/my_package_name
touch my_node.cpp

4. Open the file using a text editor (such as vimor ) and write your node code. Here's a simple example:nanomy_node.cpp

#include <ros/ros.h>
#include <std_msgs/String.h>

void messageCallback(const std_msgs::String::ConstPtr& msg)
{
    ROS_INFO("Received message: %s", msg->data.c_str());
}

int main(int argc, char** argv)
{
    ros::init(argc, argv, "my_node");
    ros::NodeHandle nh;

    ros::Subscriber sub = nh.subscribe("my_topic", 10, messageCallback);

    ros::spin();

    return 0;
}

In this example, we include the ROS and std_msgs libraries, define a callback function messageCallbackto handle the received message, and in mainthe function initialize the node, create a subscriber and start the node's loop.

5. Edit CMakeLists.txtthe file to add the node to the build system. Open a terminal, go to the package's directory, and execute the following command:

cd ~/catkin_ws/src/my_package_name
nano CMakeLists.txt

6. Find add_executablethe line and add the following below it:

add_executable(my_node src/my_node.cpp)  # 替换成你的节点文件名
target_link_libraries(my_node ${catkin_LIBRARIES})

7. Return to the root directory of the ROS workspace and execute the compilation command:

cd ~/catkin_ws
catkin_make

8. Run your node. Execute the following command in the terminal:

rosrun my_package_name my_node

This will start your node and start receiving and processing messages.

Modify and extend according to your own needs. Also, make sure to follow ROS's specifications and best practices when writing code.

Guess you like

Origin blog.csdn.net/weixin_56337147/article/details/132554307