How to create a simple subscriber
# include <ros/ros.h>
# include <geometry_msgs/Pose.h>
void poseCallback(const turtlesim::Pose::ConstPtr& msg) // turtlesim::Pose is the message type, ConstPtr is the message pointer type
{
// callback function must be quick, otherwise it will block the thread
ROS_INFO("Turtle pose: x: %0.6f, y: %0.6f", msg->x, msg->y);
}
int main(){
// initialize the ros node: ros::init(argc, argv, "my_node_name");
ros::init(argc, argv, "pose_subscriber");
// create a node handle: ros::NodeHandle n;
ros::NodeHandle n;
// create a subscriber, subscribe the topic "/turtle1/pose", and call the callback function "poseCallback" when receiving a message, 10 is the queue size for the message
ros::Subscriber pose_sub = n.subscribe("/turtle1/pose", 10, poseCallback);
// ros::spin() will enter a loop, pumping callbacks. With this version, all callbacks will be called from within this thread (the main one). ros::spin() will exit when Ctrl-C is pressed, or the node is shutdown by the master.
ros::spin();
return 0;
}
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# First line: Shebang line used to specify the interpreter to be used to run the script. Here is python interpreter, which is located at /usr/bin/env.
# Second line: The encoding declaration. It is used to declare the encoding used in the script.
import rospy
from turtlesim.msg import Pose
def poseCallback(msg):
rospy.loginfo("Turtle pose: x: %0.6f, y: %0.6f", msg.x, msg.y)
def pose_subscriber():
rospy.init_node('pose_subscriber', anonymous=True)
rospy.Subscriber("/turtle1/pose", Pose, poseCallback)
rospy.spin()
if __name__ == '__main__':
pose_subscriber()
add_executable(pose_subscriber src/pose_subscriber.cpp)
target_link_libraries(pose_subscriber ${catkin_LIBRARIES})
cd ~/rosleaning
catkin_make
source devel/setup.bash
roscore
rosrun turtlesim turtlesim_node
rosrun topic_learning pose_subscriber
work_space/src/topic_name/scripts
folder cd ~/rosleaning
roscore
rosrun turtlesim turtlesim_node
rosrun topic_learning pose_subscriber.py # no need to compile, but must make py file executable