Pages: [1]   Go Down
Author Topic: Non-Int Storage in EEPROM.  (Read 350 times)
0 Members and 1 Guest are viewing this topic.
0
Offline Offline
Newbie
*
Karma: 0
Posts: 1
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Hi,

I am trying to store either a float or a double to the EEPROM.
How would I go about doing this? the library currently only supports integers,
I have read about bitwise operators but I was unable to find anything related to my problem.

Thank you
Logged

0
Offline Offline
Jr. Member
**
Karma: 1
Posts: 64
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

You can use a union to access each byte of the 4-byte float. A union is similar to a struct, except that it only allocates enough space to contain the largest single type that is defined inside it. Here's an example of how to copy a float byte by byte from the original to another, using C++ on a PC.

Code:
#include <iostream>
using namespace std;

union bitFloat {
      float float_num;
      char byte[4];
};

int main()
{
      bitFloat test;
      test.float_num = 10.5f;
      bitFloat test2;
      test2.byte[0] = test.byte[0];
      test2.byte[1] = test.byte[1];
      test2.byte[2] = test.byte[2];
      test2.byte[3] = test.byte[3];

      cout << test.float_num << endl;
      cout << test2.float_num << endl;

      getchar();
      return 0;
}

The important thing to realise is that the bitFloat type defined is only 4 bytes, and you have two ways of accessing its data - one through the float type test.float_num or through the byte array, test.byte.
So, the practical upshot of all this is that you can store your floating point numbers in EEPROM, and read them out byte by byte, and use them to build up your whole float variable. (floats and doubles are both 4 bytes on the AVR cores.) The only thing you might have to worry about is endian-ness... which order the bytes need to be stored in. Unfortunately I don't know myself what the AVRs are. ):
Logged

Pages: [1]   Go Up
Jump to: