ROS course 3: Simple Subcribe/Publish
1. Environment
This post is tested under the following Environment:
Item | Value |
---|---|
CPU | AMD Ryzen 5 2600 |
Ubuntu | 18.04 |
ROS | Melodic |
For installation, see 02 Install. The source code of all parts is upload of github, see 11 git for more detail.
Summary
Our example has the following structure. talker send message to chatter topic. listener read message from chatter topic and display into console.
Source code is as follow :
src/basic_lecture/
├── launch
├── msg
└── src
├── basic_simple_talker.cpp
├── basic_simple_listener.cpp
├── package.xml
├── CMakeLists.txt
Procedure
Create ros package
mkdir -p ~/catkin_ws/src
mkdir ros_lecture
cd ~/catkin_ws/src/ros_lecture
# catkin_create_pkg [package] [dependency 1] [dependency 2] ...
# create package basic_lecture with msgs, roscpp, rospy as dependencies
catkin_create_pkg basic_lecture std_msgs rospy roscpp
cd ~/catkin_ws/src/ros_lecture/basic_lecture/src
touch basic_simple_talker.cpp
touch basic_simple_listener.cpp
Code of Publisher
#include "ros/ros.h"
#include "std_msgs/String.h"
int main(int argc, char **argv){
ros::init(argc, argv, "simple_talker");
ros::NodeHandle n;
ros::Publisher chatter_pub = n.advertise<std_msgs::String>("chatter", 10);
ros::Rate loop_rate(10);
while (ros::ok()){
std_msgs::String msg;
msg.data = "hello world!";
ROS_INFO("%s", msg.data.c_str());
chatter_pub.publish(msg);
ros::spinOnce();
loop_rate.sleep();
}
return 0;
}
Code of Subcriber
#include "ros/ros.h"
#include "std_msgs/String.h"
void chatterCallback(const std_msgs::String& msg){
ROS_INFO("I heard: [%s]", msg.data.c_str());
}
int main(int argc, char **argv){
ros::init(argc, argv, "listener");
ros::NodeHandle n;
ros::Subscriber sub = n.subscribe("chatter", 10, chatterCallback);
ros::Rate loop_rate(10);
ros::spin();
return 0;
}
Edit build file
ROS use catkin as build tool. Catkin is based on CMake. in this example, we want to build basic_simple_talker.cpp and basic_simple_listener.cpp. We add the following 4 lines to CMakeList.txt
add_executable(basic_simple_talker src/basic_simple_talker.cpp)
add_executable(basic_simple_listener src/basic_simple_listener.cpp)
target_link_libraries(basic_simple_talker ${catkin_LIBRARIES})
target_link_libraries(basic_simple_listener ${catkin_LIBRARIES})
Build
cd ~/catkin_ws
catkin_make
Execution
# in 1st terminal
roscore
# in 2nd terminal
rosrun basic_lecture basic_simple_talker
# in 3rd terminal
rosrun basic_lecture basic_simple_listener
Leave a comment