总述
由于没有注意 参数 与 句柄的 全局/局部 关系,从而使得launch文件的参数无法正常进入节点中。
表现
问题代码来自 https://github.com/RuPingCen/publish_pointcloud
launch文件。
<launch>
<node name="publish_pointcloud" pkg="publish_pointcloud" type="publish_pointcloud" output="screen">
<param name="path" value="$(find publish_pointcloud)/data/test3.pcd" type="string" />
<param name="frame_id" value="camera" type="string" />
<param name="topic" value="/pointcloud/output" type="string" />
<param name="hz" value="20" type="int" />
</node>
</launch>
节点文件 .cpp
int main (int argc, char **argv)
{
std::string topic,path,frame_id;
int hz;
ros::init (argc, argv, "publish_pointcloud");
ros::NodeHandle nh;
nh.param<std::string>("path", path, "/home/shuangyu/catkin_pcd2ros/src/publish_pointcloud/data/test.pcd");
cout << "path:: "<<path << endl;
nh.param<std::string>("frame_id", frame_id, "camera");
nh.param<std::string>("topic", topic, "/pointcloud/output");
nh.param<int>("hz", hz, 2);
cout << "path:: "<<path << endl;
...
运行的结果
代码仍然我行我素地采用 nh.param 中的默认值。
原因
nh是全局句柄,launch文件中的参数都是局部参数,所以可以:
- 改为局部句柄
ros::NodeHandle nh("~");
或者
2. launch文件采用全局参数
只有"path"是全局参数。
<launch>
<param name="path" value="test3.pcd" type="string" />
<node name="publish_pointcloud" pkg="publish_pointcloud" type="publish_pointcloud" output="screen">
<param name="frame_id" value="camera" type="string" />
<param name="topic" value="/pointcloud/output" type="string" />
<param name="hz" value="20" type="int" />
</node>
</launch>