Alright so I figured it out, at least it works for me. This is assuming you have your class in separate .h and .cpp files but if you don't it still works but it's slightly different.
testPublish.h:
#ifndef TESTPUBLISH_H
#define TESTPUBLISH_H
#include <ros.h>
#include <std_msgs/Float32.h>
class testPublish {
public:
testPublish();
std_msgs::Float32 test;
ros::Publisher topicTestOut;
void publishFunction();
};
#endif
testPublish.cpp
#include "testPublish.h"
testPublish::testPublish() : topicTestOut("au_testOut", &test) {
test.data = 0;
}
void testPublish::publishFunction() {
test.data += 1;
topicTestOut.publish(&test);
}
Then in your sketch file you have to create an object with the class:
testPublish testClassPublish;
and advertise it from your nodeHandler:
nh.advertise(testClassPublish.topicTestOut);
Then just to get test data from my loop I called publishFunction:
testClassPublish.publishFunction();
Not a solution sorry, but the reason you're having difficulties is that the nodehandler is probably in your .ino file and is out of scope for your class. I have found it easier to have all of the publishes in the sketch file and just use getters to retrieve the data you need from the classes.
Hello Benh, thanks for the response. But nodehandler is taken as a global variable, and should be accessible from the class. And also I was able to create a subscriber within a class, and getting the problem with publisher only.
is your publisher object also global? If it is then I don't know why it wouldn't work.
Hello Benh, the publisher object is not global, and within the class itself. But the subscriber object was also not global, still it was working as in next comment:
class relay_control { ros::Subscriber<std_msgs::bool, relay_control=""> sub_; void relay_cb(const std_msgs::Bool& msg) { } public: relay_control(char* name_id) : sub_(name_id, &relay_control::relay_cb, this) { }