0
$\begingroup$

Rosanswers logo

Hello everyone, I'm trying to get a parameter used in the launch command of a node and use it on my c++ code. For example, when you're about to launch a node: $rosrun [packet] [node] [string], the [string] being the string I want to use in my c++ code of the node.

I want it to give me the string so I can choose a specific topic to subscribe to. I'm using ROS Kinetic


Originally posted by Diatrix on ROS Answers with karma: 3 on 2018-07-18

Post score: 0

$\endgroup$

2 Answers 2

0
$\begingroup$

Rosanswers logo

If you're doing rosrun, you can use the argv passed into the main function of your C++ node:

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

    if (argc > 1)
        std::string value_from_cl = argv[1];
}

If you go through a launch file, you can use launch file args to pass in from the command line. For example, if you have in your launch file

<arg name="some_arg" default="my_default_value"/>

then you can run roslaunch like

roslaunch my_package my_file.launch some_arg:=some_other_value

Then to get the value to your node, you can pass it directly in the node tag in the launch file:

<node name="my_node" pkg="my_package" type="my_node" args="$(arg some_arg)"/>

You could alternatively set it with the ROS parameter server, in which case you would load it in your launch file by doing

<param name="my_param" value="$(arg some_arg)"/>

which can then be retrieved from the parameter server in your C++ code with

ros::NodeHande nh;
std::string value_from_ps;
// Retrieve and set a default value if not found on parameter server    
nh.param<std::string>("my_param", value_from_ps, "my_default_value");
// Retrieve without a default value
nh.getParam("my_param", value_from_ps);

Originally posted by adamconkey with karma: 642 on 2018-07-18

This answer was ACCEPTED on the original site

Post score: 1


Original comments

Comment by Diatrix on 2018-07-20:
Thank you, it's everything I needed.

$\endgroup$
0
$\begingroup$

Rosanswers logo

The best way to do this using the ROS system is to use the parameter system. This allows the setting to be controlled when you start the node by itself using rosrun or as part of a larger launch file. You would run your node using the following command:

rosrun <package_name> <node_name> _topic:=<topic_name>

You can then access this parameter in your node using the following code:

ros::NodeHandle n("~");
std::string topicName;
n.param<std::string>("topic", topicName, "default_topic");
printf("topic is [%s]\n", topicName.c_str() );

Hope this helps.


Originally posted by PeteBlackerThe3rd with karma: 9529 on 2018-07-18

This answer was NOT ACCEPTED on the original site

Post score: 1


Original comments

Comment by Diatrix on 2018-07-20:
It does, thank you!

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.