Advertisement
Guest User

Untitled

a guest
Aug 27th, 2024
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <EEPROM.h>
  2.  
  3. const int EEPROM_SIZE = 2048;
  4. const int PAGE_SIZE = 32;
  5. const int CHUNK_SIZE = sizeof(double);
  6. int writeIndex = 0;
  7.  
  8. void writeData(double data) {
  9.     int currentPos = findCurrentPosition();
  10.     byte dataBytes[CHUNK_SIZE];
  11.  
  12.     memcpy(dataBytes, &data, sizeof(double));
  13.  
  14.     EEPROM.put(currentPos, dataBytes);
  15.  
  16.     // Erase the next page if we're at the last chunk of the current page
  17.     if ((currentPos + CHUNK_SIZE) % PAGE_SIZE == 0) {
  18.         int nextPageStart = (currentPos + CHUNK_SIZE) % EEPROM_SIZE;
  19.         byte emptyPage[PAGE_SIZE] = {0};
  20.         EEPROM.put(nextPageStart, emptyPage);
  21.     }
  22.  
  23.     EEPROM.commit();
  24. }
  25.  
  26. int findCurrentPosition() {
  27.     for (int i = 0; i < EEPROM_SIZE; i += CHUNK_SIZE) {
  28.         bool isEmpty = true;
  29.         for (int j = 0; j < CHUNK_SIZE; j++) {
  30.             if (EEPROM.read(i + j) != 0x00) {
  31.                 isEmpty = false;
  32.                 break;
  33.             }
  34.         }
  35.         if (isEmpty) {
  36.             return i;
  37.         }
  38.     }
  39.     return 0;
  40. }
  41.  
  42. void writeDataEverySecond() {
  43.     double data = random(0, 100) / 1.0;
  44.     writeData(data);
  45.     writeIndex++;
  46.     delay(1000);
  47. }
  48.  
  49. void setup() {
  50.     Serial.begin(9600);
  51.     EEPROM.begin(EEPROM_SIZE);
  52. }
  53.  
  54. void loop() {
  55.     writeDataEverySecond();
  56. }
  57.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement