HMC5883L库未显示float的小数

时间:2015-05-12 17:52:06

标签: c++ arduino

我正在使用HMC5883L传感器来测量磁场,但是当我查看ESP8266上的数据时,它会错过小数......例如,值应为“-234.54”而我只得到“-234.00” 。我试图解决这个问题,但是它没有用。

我在HMC5883L.h中的结构:

struct MagnetometerScaled
{
    float XAxis;
    float YAxis;
    float ZAxis;
};

struct MagnetometerRaw
{
    float XAxis;
    float YAxis;
    float ZAxis;
};

正在使用的HMC5883L.cpp部分:

MagnetometerRaw HMC5883L::ReadRawAxis()
{
  const int8_t* buffer = Read(DataRegisterBegin, 6);
  MagnetometerRaw raw = MagnetometerRaw();
  raw.XAxis = (buffer[0] << 8) | buffer[1];
  raw.ZAxis = (buffer[2] << 8) | buffer[3];
  raw.YAxis = (buffer[4] << 8) | buffer[5];
  delete [] buffer;
  return raw;
}

MagnetometerScaled HMC5883L::ReadScaledAxis()
{
  MagnetometerRaw raw = ReadRawAxis();
  MagnetometerScaled scaled = MagnetometerScaled();
  scaled.XAxis = raw.XAxis * m_Scale; // m_scale = 0.92 -> A float value
  scaled.ZAxis = raw.ZAxis * m_Scale; // m_scale = 0.92 -> A float value
  scaled.YAxis = raw.YAxis * m_Scale; // m_scale = 0.92 -> A float value
  return scaled;
}

int8_t* HMC5883L::Read(int address, int length)
{
  Wire.beginTransmission(HMC5883L_Address);
  Wire.write(address);
  Wire.endTransmission();

  Wire.beginTransmission(HMC5883L_Address);
  Wire.requestFrom(HMC5883L_Address, length);

  // uint8_t buffer[length];
  int8_t *buffer = new int8_t[length];
  if(Wire.available() == length)
  {
    for(uint8_t i = 0; i < length; i++)
    {
      buffer[i] = Wire.read();
    }
  }
  Wire.endTransmission();

  return buffer;
}

在运行此代码(基本上)时使用:

HMC5883L magnetometer;
MagnetometerScaled scaledVals;
scaledVals = magnetometer.ReadScaledAxis();
Serial.println(scaledVals.XAxis);

如果我遗漏了代码中的一些重要部分,只需要它:)

EDIT1:如果我运行Serial.println(1.01);,它会正确打印值(输出= 1.01)。因此,Serial.println()不会截断浮点值...

EDIT2:正如我所看到的,问题似乎与Read()函数返回的类型有关。也许如果我将其更改为char*而不是int8_t,我将能够以正确的方式接收小数。我的问题与ReadRawAxis()函数有关。如何从buffer获取数据?

0 个答案:

没有答案