I'm using HMC5883L sensor to measure magnetic field but when I look to the data on my ESP8266 it misses the decimals... The value should be, for example, "-234.54" and I got only "-234.00". I'm trying to fix this looking into the library but it didn't work.
My structures in HMC5883L.h:
struct MagnetometerScaled
{
float XAxis;
float YAxis;
float ZAxis;
};
struct MagnetometerRaw
{
float XAxis;
float YAxis;
float ZAxis;
};
Parts of HMC5883L.cpp in use:
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;
}
In run this code (basically) using:
HMC5883L magnetometer;
MagnetometerScaled scaledVals;
scaledVals = magnetometer.ReadScaledAxis();
Serial.println(scaledVals.XAxis);
If I left some important part of the code behind, just ask for it :)
EDIT1: If I run Serial.println(1.01);
it prints the value correctly (output = 1.01). So, Serial.println() is not truncating float values...
EDIT2: As I see, the problem seems to be with the type returned by Read()
function. Maybe if I change it to char*
instead of int8_t
I'll be able to receive the decimals on the right way. My question related to this is with the ReadRawAxis()
function. How to get the data from buffer
?