Change publisher and subscriber to send an integer instead of a hello word

asked 2022-09-07 10:44:39 -0600

jaafar gravatar image

updated 2022-09-07 22:58:41 -0600

ravijoshi gravatar image

I have these two codes for publisher and subscriber. They send each other a string with a hello word and a counter. How can I make them send an integer?

Below is the publisher code:

#include "ros/ros.h"
#include "std_msgs/String.h"
#include <sstream>
int main(int argc, char **argv)
{
  ros::init(argc, argv, "talker"); 
  ros::NodeHandle n; 
  ros::Publisher chatter_pub = n.advertise<std_msgs::String>("chatter", 1000);
  ros::Rate loop_rate(10); 
  int count = 0;
  while (ros::ok())
  {
    std_msgs::String msg;
    std::stringstream ss;
    ss << "hello world " << count;
    msg.data = ss.str();
    ROS_INFO("%s", msg.data.c_str());    
    chatter_pub.publish(msg);
    ros::spinOnce();
    loop_rate.sleep();
    ++count;
  }
  return 0;
}

Below is the subscriber code:

#include "ros/ros.h"
#include "std_msgs/String.h"
void chatterCallback(const std_msgs::String::ConstPtr& 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", 1000, chatterCallback);
  ros::spin();
  return 0;
}
edit retag flag offensive close merge delete

Comments

You did a good job skipping the tutorials and copying the sample codes in the question.

Is someone stopping you from understanding the ROS simply by putting effort into going through the ROS Tutorials?

Please spend some time learning the basic yet essential concepts of ROS.

ravijoshi gravatar image ravijoshi  ( 2022-09-07 23:01:36 -0600 )edit
1

@ravijoshi: let's try to be a little more welcoming.

I agree with you this looks like a copy-paste of the example code, and that @jaafar could perhaps have spent a little more time on trying to figure this out by him/herself, but we can't know whether (s)he hasn't already done that.

So @jaafar: please:

  • describe what you've already tried
  • where you found that
  • what you expected to happen
  • what actually happened (if it didn't work), and
  • what you believe the problem could be

Then we can help you.

ROS Answers is not a place where we expect other people to just do your work for you. We help you trying to get your work done, but we have to see a little effort on your side first.

gvdhoorn gravatar image gvdhoorn  ( 2022-09-08 02:19:59 -0600 )edit