If I write a large value to position 0, this code breaks the number into 4 bytes and spans it across 32 bits in the eeprom if it's even that big. If I want to write a second large number do I start writing that at Bit 5 and that will go to bit 8?. then 9 to 12? If I'm correct, On a atmega328 I could write all the way to 512 with the last address being 509?
I'm just a bit confused and would like clarity. Thank you.
code:
void EEPROMWritelong(int address, long value)
{
//Decomposition from a long to 4 bytes by using bitshift.
//One = Most significant -> Four = Least significant byte
byte four = (value & 0xFF);
byte three = ((value >> 8) & 0xFF);
byte two = ((value >> 16) & 0xFF);
byte one = ((value >> 24) & 0xFF);
//Write the 4 bytes into the eeprom memory.
EEPROM.write(address, four);
EEPROM.write(address + 1, three);
EEPROM.write(address + 2, two);
EEPROM.write(address + 3, one);
}
//This function will return a 4 byte (32bit) long from the eeprom
//at the specified address to address + 3.
long EEPROMReadlong(long address)
{
//Read the 4 bytes from the eeprom memory.
long four = EEPROM.read(address);
long three = EEPROM.read(address + 1);
long two = EEPROM.read(address + 2);
long one = EEPROM.read(address + 3);
//Return the recomposed long by using bitshift.
return ((four << 0) & 0xFF) + ((three << 8) & 0xFFFF) + ((two << 16) & 0xFFFFFF) + ((one << 24) & 0xFFFFFFFF);
}
BobofDOOM:
If I write a large value to position 0...
Is the goal to write values to EEPROM or to devise your own technique as a learning experience? If the former, there's EEPROM.put and an accompanying .get to handle the grunt work.
In either case it's up to you to manage the addressing. If you write four bytes sequentially starting at address 0 in what address should the fifth sequential byte be stored?
The following example may satisfy Op's queries:
Figure-1: Conceptual layout for internal EEPROM space of ATmega328P
A: Writing 5 units of long (32-bit = 4 byte) data
(1) 1st unit will occupy locations: 0 - 3
(2) 2nd unit will occupy locations: 4 - 7
......................................................
(3) Codes
#include<EEPROM.h>
long int myData[5] = {0x12345678, ........, };
int address = 0;
for(int i = 0; i<5; i++)
{
EEPROM.put(address, myData[i]);
delay(5); //write time delay
address = address + 4;
}
B: Writing long data 1-byte at a time.
union
{
long myData x;
byte myArray[4];//[edit][8][/edit]; //x is broken into bytes little endianess
}data;
data.myData = 0x12345678;
for(int i=0; i<4; i++) //[edit]i<8; i++)[/edit]
{
EEPROM.write(address, data.myArray[i]);
delay(5);
address = address + 1;
}
{
long myData x;
byte myArray[8]; //x is broken into bytes little endianess
}data;
Eight bytes would be a long long, n'est pas?
I am searching to know from where the symbol 8 has come -- it has come from my own mother tongue alphabet 8 for 4. I am at a loss how to correct it except being careful for the future!