ROS Resources: Documentation | Support | Discussion Forum | Index | Service Status | ros @ Robotics Stack Exchange
Ask Your Question

Revision history [back]

I've created a custom msg (msg/mycustom.msg) in my package called mypkg, created a publisher and 2 subscribers, one in python, another in cpp. You can see below:

my_subscriber.py

#!/usr/bin/env python
import rospy
from mypkg.msg import mycustom

def callback(data):
    rospy.loginfo("direction x: [" + str(data.direction.x) + "]")
    rospy.loginfo("direction y: [" + str(data.direction.y) + "]")
    rospy.loginfo("direction z: [" + str(data.direction.z) + "]")

def listener():

    rospy.init_node('listener', anonymous=True)

    rospy.Subscriber("my_topic", mycustom, callback)

    rospy.spin()

if __name__ == '__main__':
    listener()

cpp_subscriber.cpp

#include "ros/ros.h"
#include "mypkg/mycustom.h"

void chatterCallback(const mypkg::mycustom::ConstPtr& msg)
{
  ROS_INFO("direction x: [%.2f]", msg->direction.x);
  ROS_INFO("direction y: [%.2f]", msg->direction.y);
  ROS_INFO("direction z: [%.2f]", msg->direction.z);
}

int main(int argc, char **argv)
{
  ros::init(argc, argv, "cpp_subscriber");

  ros::NodeHandle n;

  ros::Subscriber sub = n.subscribe("my_topic", 1000, chatterCallback);

  ros::spin();

  return 0;
}

I've created a custom msg (msg/mycustom.msg) in my package called mypkg, created a publisher and 2 subscribers, one in python, another in cpp. You can see below:

my_subscriber.py

#!/usr/bin/env python
import rospy
from mypkg.msg import mycustom

def callback(data):
    rospy.loginfo("direction x: [" + str(data.direction.x) + "]")
    rospy.loginfo("direction y: [" + str(data.direction.y) + "]")
    rospy.loginfo("direction z: [" + str(data.direction.z) + "]")

def listener():

    rospy.init_node('listener', anonymous=True)

    rospy.Subscriber("my_topic", mycustom, callback)

    rospy.spin()

if __name__ == '__main__':
    listener()

cpp_subscriber.cpp

#include "ros/ros.h"
#include "mypkg/mycustom.h"

void chatterCallback(const mypkg::mycustom::ConstPtr& msg)
{
  ROS_INFO("direction x: [%.2f]", msg->direction.x);
  ROS_INFO("direction y: [%.2f]", msg->direction.y);
  ROS_INFO("direction z: [%.2f]", msg->direction.z);
}

int main(int argc, char **argv)
{
  ros::init(argc, argv, "cpp_subscriber");

  ros::NodeHandle n;

  ros::Subscriber sub = n.subscribe("my_topic", 1000, chatterCallback);

  ros::spin();

  return 0;
}

There's a video step-by-step showing how I did it: https://www.youtube.com/watch?v=aLfJZf9py0g