Reading and writing to EEPROM for an intelligent ball

Hiya, working on a loop that gives me 512 pieces of data, loop works currently but now looking to write data to EEPROM and have really struggled to understand other information online

#include <EEPROM.h>
const int gyro1 = A0;
const int gyro2 = A1;
int thetaDot = 0;
int phiDot = 0;
int n = 1;

void setup() {
 // put your setup code here, to run once:
Serial.begin(9600);
Serial.println();
//Serial.println(map(thetaDot,0,1023,0,255));
//Serial.println(map(phiDot,0,1023,0,255));
//for (int n = 0; n <= 511; n++);
    
}
void loop() {
  // put your main code here, to run repeatedly:
for(n = 1;n <= 512;n++){ 
   //statements block will executed 511 times
thetaDot = analogRead(gyro1); 
phiDot = analogRead(gyro2); 
 //EEPROM.write(n, thetaDot);
    //EEPROM.write(n + 512, phiDot);
    Serial.println(map(thetaDot,0,1023,0,255));
Serial.println(map(phiDot,0,1023,0,255));
    delay (2);}
  exit(0);
  // Look for Serial input:
}

Or was that 512?

It's never too early as a C/C++ programmer to embrace the use of zero as a legitimate number.

Most would loop 512 times by writing

    for (n = 0; n < 512; n++) {  //... 

and use 0 to 511 inclusive in the body of the loop.

You may see why one day.

a7

I can change that yeah, thanks for spotting and explaining

I just googled, see

how to use eeprom

You can only write one byte at a time with the write() method.

Larger things, like 16 bit signed integers, need a bit more care.

The linked article "solved" the problem by dividing the analogRead() value by 4, putting it into the range 0..255, which fits in one byte, before writing it to EEPROM.

You may want to find a way to not lose precision when you store and later retrieve values.

a7

The EEPROM is a series of 8 bit buckets. If there is a 16 bit number then the number to be stored into the EEPROM must be broken down into 2 8 bit numbers so it can fit into 2 8 bit buckets.

Here is some CAN code that breaks down a 32 bit number into 4 8 bit buckets.

          rx_frame.FIR.B.FF = CAN_frame_std;
          rx_frame.MsgID = 1;
          rx_frame.FIR.B.DLC = 8;
          rx_frame.data.u8[0] = *item & 0xFF;
          rx_frame.data.u8[1] = (*item >> 8) & 0xFF;
          rx_frame.data.u8[2] = (*item >> 16) & 0xFF;
          rx_frame.data.u8[3] = (*item >> 24) & 0xFF;
          PassTwo = true;

*item refers to the 32 bit number. rx_frame.data.u8[0] is a 8 bit bucket. *item & 0xFF takes bits 0 through 7 and puts them into the first 8 bit bucket. Here (*item >> 8) & 0xFF, the 2nd 8 bits of the 32 bit number are extracted and moved into the 2nd 8 bit bucket, and so on and so forth. Hopefully this gives you an idea of something. Oh and you will want to keep track of where 8 bit numbers are stored vs 16 bit number or 32 bit numbers or just use a single data type to store all the numbers.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.