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

Publishing to a topic from Arduino in a class

asked 2018-10-19 07:20:03 -0500

saurabh gravatar image

Hello All,

I have to publish status messages (boolean) from an Arduino board using rosserial. I am able to do it when I make them independently, but facing problem, when I am putting the publisher in a class.

Can somebody please give a reference of publishing on a topic in a class from Arduino.


edit retag flag offensive close merge delete


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.

benh gravatar image benh  ( 2018-10-19 11:38:40 -0500 )edit

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.

saurabh gravatar image saurabh  ( 2018-10-19 12:50:53 -0500 )edit

is your publisher object also global? If it is then I don't know why it wouldn't work.

benh gravatar image benh  ( 2018-10-19 13:38:50 -0500 )edit

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:

saurabh gravatar image saurabh  ( 2018-10-20 09:42:04 -0500 )edit

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) { }

saurabh gravatar image saurabh  ( 2018-10-20 09:47:10 -0500 )edit

1 Answer

Sort by ยป oldest newest most voted

answered 2018-10-22 16:02:44 -0500

benh gravatar image

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.



#include <ros.h>
#include <std_msgs/Float32.h>

class testPublish {

    std_msgs::Float32 test;
    ros::Publisher topicTestOut;
    void publishFunction();



#include "testPublish.h"

testPublish::testPublish() : topicTestOut("au_testOut", &test) { = 0;
void testPublish::publishFunction() { += 1;

Then in your sketch file you have to create an object with the class:

testPublish testClassPublish;

and advertise it from your nodeHandler:


Then just to get test data from my loop I called publishFunction:

edit flag offensive delete link more

Question Tools

1 follower


Asked: 2018-10-19 07:20:03 -0500

Seen: 642 times

Last updated: Oct 22 '18