Subscribe/Publish a topic X amount of times.

asked 2020-04-14 20:29:52 -0600

rubbun gravatar image

I have an LDR connected to an Arduino UNO and I want to read ONLY a certain amount of values from it, for example, 100 values, and then dump them all into a file so I can mess with the result. I want the publish to either stop dumping values or end right after it's dropped the last value. I was thinking of something like this, but I'm stuck and need input.

#include "ros/ros.h"
#include "std_msgs/UInt16.h"

void adcCallback(const std_msgs::Int8::ConstPtr& value){
    ROS_INFO("I heard: [%d]", value->data());

int main(int argc, char **argv){

    ros::init(argc, argv, "sensorValue");
    ros::NodeHandle n;

    ros::Publisher pub = n.advertise<std_msgs::UInt16>("adc", 1000);
    ros::Subscriber sub = n.subscribe("adc", 1000, adsCallback);

    int count = 0;
    ///is this possible? Or do I always need to use "while(ros::ok)?
    ///if it's possible, is there a way to set a variable that I can input in arduino, or does it need to be a pre-determined value set before running the node? 
    while (count < )

        std_msgs::UInt16 sensorValue;
        ///not sure how to obtain the sensor value here = 
        ///also not exactly sure how to publish the sensor value

    return 0;

Would much appreciate some help, even if it's a reference to some site where I can learn how to create my own node. Thanks.

edit retag flag offensive close merge delete


Hi @rubbun,

is this possible? Or do I always need to use "while(ros::ok)? You can have multiple conditions on the while loop. E.g.:

while(ros::ok && count < n_times)

is there a way to set a variable that I can input in arduino You can use the parameter server to adjust dynamically a variable.

If you really want to execute the code just a certain amount of times you can add to the while loop your condition and once the number is higher than a threshold jump out of the loop and return 0 in the main. Will be something like:

int main(int argc, char **argv)
while(ros::ok && count < n_times)
// Do your things here
return 0;
Weasfas gravatar image Weasfas  ( 2020-04-16 08:00:51 -0600 )edit