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

Trying to have publisher and subscriber in same node.

asked 2019-08-12 04:14:18 -0500

Subss0811 gravatar image

I am quite new to ROS, hence my doubt. My project is as follows:

Arduino sends ultrasonic sensor data to my laptop. My laptop checks if the data is less than a value say 15.0. I want my laptop to send 1 (Bool) if it is less than 15 and 0 if it is more than 15 to the Arduino. The first half works, i.e. I can send data from Arduino to the laptop. But at the callback() function in my laptop_node, I am not able to publish a message to the Arduino. My Arduino also has a subscriber. What would be your approach to this problem? Could someone please send a sample code if possible?

Thanks.

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2019-08-13 07:40:11 -0500

krl101 gravatar image

So you are basically locking for a publisher & subscriber in one single node for your PC. Actually is is a mixture of the Writing Publisher Subscriber Tutorial.

#include "ros/ros.h"
#include "std_msgs/UInt8.h"
#include "std_msgs/Bool.h"

ros::Publisher chatter_pub;


void chatterCallback(const std_msgs::UInt8::ConstPtr& msg)
{
  ROS_INFO("I heard: [%d]", msg->data);

  std_msgs::Bool msgOut;
  msgOut.data = false;
  if (msg->data > 15)
     msgOut.data = true;

  chatter_pub.publish(msgOut);

}

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

  ros::NodeHandle nh;

  ros::Subscriber sub = nh.subscribe("active_listener", 1, chatterCallback);
  chatter_pub = nh.advertise<std_msgs::Bool>("chatter_within_subscriber", 1);

  ros::spin();

  return 0;
}

Hope it helps and is helpful enough despite the removed comments. Greetings, krl

edit flag offensive delete link more

Question Tools

2 followers

Stats

Asked: 2019-08-12 04:14:18 -0500

Seen: 434 times

Last updated: Aug 13 '19