我想从文本文件中发布ROS主题浮动数

I want to publish in a ROS topic floating numbers from a text file

本文关键字:ROS 文本 文件      更新时间:2023-10-16

我试图读取一个文本文件,其中包含许多浮点数在一列中,如在这个例子:

0.872
0.876
0.880
0.888
0.900

特别地,我想逐行读取它,每次读取一行时,我想要将该数值存储在一个变量中,该变量必须在ROS主题上发布,等待时间约为1秒,然后它必须再次执行该操作,直到文件结束。我正试着以循序渐进的方式写出我的问题,以便(也许)更清楚:

  1. 读取第一行(例如0.872)
  2. 将数字0.872保存在变量
  3. 在ROS主题中发布只有0.872值的变量
  4. 等待一秒钟
  5. 重复循环直到文件结束。

通过在web上和Stack Overflow上的一些搜索,我写了一个代码,现在,在终端上打印数字(即使它不是我想要的),因为我不知道如何实现ROS命令来发布,尽管我已经阅读了教程。但有些数字似乎是这样切割的:

0.876
0.88
0.888
0.9
0.9
0.876
0.904
0.908
0.88

而不是在精度上与其他数字相等。下面是我现在写的代码:

#include <iostream>
#include <fstream>
#include <sstream>
using namespace std;
int main()
{
    ifstream inputFile("/home/marco/Scrivania/marks.txt");
    string line;
    while (getline(inputFile, line))
    {
        istringstream ss(line);
        float heart;
        ss >> heart;
        cout << heart << endl << endl;
    }

注意:它是用普通c++语言编写的,没有任何ROS命令,如ROS init等。所以,如果你能告诉我怎么做就太好了,因为到目前为止我只做了一个ROS节点。

编辑:在放入ROS节点、编译和执行时,通过建议的修改,它运行起来没有问题。然后我试着添加主题部分,没有成功。我更新下面的代码:

#include "ros/ros.h"
#include "std_msgs/Float32.h"
#include "../include/heart_rate_monitor/wfdb.h"
#include <stdio.h>
#include <sstream>
#include <iostream>
#include <fstream>
#include <iomanip>
using namespace std;

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

ros::NodeHandle n;

ifstream inputFile("/home/marco/Scrivania/marks.txt");
string line;
while (getline(inputFile, line))
{
    istringstream ss(line);
    float heart;
    ss >> heart;
    //std::cout << std::fixed << std::setprecision(3) << heart << endl  << endl;
}
ros::Publisher HeartRateInterval_pub = n.advertise<std_msgs::Float32>("HeartRateInterval", 1000);
ros::Rate loop_rate(1);
int count = 0;
while (ros::ok())
{
std_msgs::Float32 msg;
std::stringstream ss;
ss << std::cout << std::fixed << std::setprecision(3) << heart << endl << endl << count;
msg.data = ss.str();
HeartRateInterval_pub.publish(msg)
ROS_INFO("%s", msg.data.c_str());
ros::spinOnce();
loop_rate.sleep();
++count;
}
return 0;
}

另外

#include <iomanip>

,然后在输出值

之前
cout << setprecision(3) << heart //... etc

docos

这是我经过很多努力和很好的运气获得的代码!它做了我想要的,唯一的小问题是我可以用Ctrl+c关闭ROS节点。如有任何建议,不胜感激。

代码:

#include "ros/ros.h"
#include "std_msgs/String.h"
#include "../include/heart_rate_monitor/wfdb.h"
#include <stdio.h>
#include <sstream>
#include <iostream>
#include <fstream>
#include <iomanip>
using namespace std;

int main(int argc, char **argv)
{
ros::init(argc, argv, "heart_rate_monitor");
ros::NodeHandle n;
ros::Publisher pub = n.advertise<std_msgs::String>("/HeartRateInterval", 1000);
ros::Rate loop_rate(1);
while (ros::ok())
{ 
ifstream inputFile("/home/marco/Scrivania/marks.txt");
string line;
while (getline(inputFile, line)) {

istringstream ss(line);
string heart;
ss >> heart;
std_msgs::String msg;
msg.data = ss.str();
pub.publish(msg);
ros::spinOnce();
loop_rate.sleep();
}
}
return 0;
}