0

This question already has an answer here:

I'm trying to write floats to I2C FRAM (like I2C EEPROM) but without result. I tried with this function but I lose all number after the decimal. Thank's for replying.

This for writing:

float floatNumber = 123.123;
byte floatPt1 = 0;
byte floatPt2 = 0;
byte floatPt3 = 0;
byte floatPt4 = 0;
byte b1 = (floatNumber);
byte b2 = (floatNumber >> 8);
byte b3 = (floatNumber >> 16);
byte b4 = (floatNumber >> 24);

This is for reading:

long floatRicomposto = 0;
floatPt1 = fram.read8(3);
floatPt2 = fram.read8(4);
floatPt3 = fram.read8(5);
floatPt4 = fram.read8(6);
//float RECOMPOSITION
floatRicomposto = (uint32_t) floatPt1 <<  0
  | (uint32_t) floatPt2 <<  8
  | (uint32_t) floatPt3 << 16
  | (uint32_t) floatPt4 << 24;

marked as duplicate by Code Gorilla, Nick Gammon Feb 8 '17 at 9:03

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

0

I solved it with the use of UNION:

//---------------------------------------------------------
union Scomp_float {
  // si utilizza union x float
  float temp;
  char byte_s[4];
} S_float;

//---------------------------------------------------------
//-------------------------FLOAT--------------------------------
float mioFlo = 123456.29;  
byte f0 = 0;  // contengono i byte del float
byte f1 = 0;
byte f2 = 0;
byte f3 = 0;
S_float.temp = mioFlo;
f0 = S_float.byte_s[0];
f1 = S_float.byte_s[1];
f2 = S_float.byte_s[2];
f3 = S_float.byte_s[3];
Serial.println(f0);
Serial.println(f1);
Serial.println(f2);
Serial.println(f3);
fram.writeEnable(true);
fram.write8(7, f0);
fram.writeEnable(false);
fram.writeEnable(true);
fram.write8(8, f1);
fram.writeEnable(false);
fram.writeEnable(true);
fram.write8(9, f2);
fram.writeEnable(false);
fram.writeEnable(true);
fram.write8(10, f3);
fram.writeEnable(false);
S_float.byte_s[0] = fram.read8(7); // si ricompone il float
S_float.byte_s[1] = fram.read8(8);
S_float.byte_s[2] = fram.read8(9);
S_float.byte_s[3] = fram.read8(10);
float masterFloat = S_float.temp;
Serial.println(masterFloat);
//-------------------------FLOAT--------------------------------
  • You are using an array in the S_float union but not for the variables f0. you could use a loop for the fram writes. – Code Gorilla Feb 8 '17 at 9:28
-1

A pointer can be used to easily decompose and reconstitute any multi byte type, like a float.

Not the answer you're looking for? Browse other questions tagged or ask your own question.