Trying to have publisher and subscriber in same node.
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.
Asked by Subss0811 on 2019-08-12 04:14:18 UTC
Answers
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
Asked by krl101 on 2019-08-13 07:40:11 UTC
Comments