Simple ROS topic communication example

Experimental phenomena

insert image description here

Experimental procedure

The author uses VSCode to write the code. I don’t write the process of VSCode integrating ROS by myself. You can take a look at this blogger’s blog. article)

After creating the workspace, right click on src and select Create Catkin Package, enter the package name, and import the dependent library:

roscpp rospy std_msgs

Create receiver and sender two files under src: publisher.cpp, subscriber.cpp, and then write code inside.

After writing, modify CMakeLists.txt and add the following lines:

 add_executable(publisher 
  src/publisher.cpp
 )
 add_executable(subscriber
  src/subscriber.cpp
 )
 target_link_libraries(publisher
   ${catkin_LIBRARIES}
 )
 target_link_libraries(subscriber
   ${catkin_LIBRARIES}
 )

After compiling, start roscore, open two terminals in the workspace, and enter the following two paragraphs respectively:

source ./devel/setup.sh
rosrun 你的包名 publisher
source ./devel/setup.sh
rosrun 你的包名 subscriber

You can see the realization phenomenon.

experimental code

Receiving end

#include "ros/ros.h"
#include "std_msgs/String.h"

//接收端回调函数,收到数据后在这里面处理
void callback(const std_msgs::String::ConstPtr& msg_p){
    ROS_INFO("接收到%s",msg_p->data.c_str());
}
//主函数
int main(int argc, char* argv[]){
	//防止中文乱码
    setlocale(LC_ALL,"");
    
    //初始化
    ros::init(argc,argv,"subscriber");
    ros::NodeHandle nh;
    
    //订阅话题,移交回调函数
    ros::Subscriber sb = nh.subscribe<std_msgs::String>("topic1",10,callback);
    
    //回旋使用回调函数
    ros::spin();
    return 0;
}

sender

#include "ros/ros.h"
#include "std_msgs/String.h"

int main(int argc, char* argv[]){
	//防止中文乱码
    setlocale(LC_ALL,"");
    ros::init(argc,argv,"publisher");
    ros::NodeHandle nh;
    
    //成为话题发布者,这个话题发送数据类型为std_msgs::String
    ros::Publisher pub = nh.advertise<std_msgs::String>("topic1",10);
    
    //发送速率为1Hz
    ros::Rate r(1);
    
    //发送的内容
    std_msgs::String msg ;
    msg.data = "发送数据\n";
    
    //按给定速率发送数据
    while(ros::ok){
        pub.publish(msg);
        r.sleep();
        ros::spinOnce();
    }
}

Summarize

This experiment conducted a simple communication on the topic of ROS, which gave me a deep understanding of this very frequently used communication method in ROS.

References

http://www.autolabor.com.cn/book/ROSTutorials

Guess you like

Origin blog.csdn.net/weixin_54435584/article/details/129623044