Advertisement
chayanforyou

Wear leveling on a microcontroller's EEPROM

Jan 12th, 2025
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.25 KB | None | 0 0
  1. struct
  2. {
  3.   uint32_t sequence_no;
  4.   uint16_t my_data;
  5. } QUEUE_ENTRY;
  6.  
  7. #define EEPROM_SIZE 128
  8. #define QUEUE_ENTRIES (EEPROM_SIZE / sizeof(QUEUE_ENTRY))
  9.  
  10. uint32_t last_sequence_no;
  11. uint8_t queue_tail;
  12. uint16_t current_value;
  13.  
  14. // Called at startup
  15. void load_queue()
  16. {
  17.   int i;
  18.  
  19.   last_sequence_no = 0;
  20.   queue_tail = 0;
  21.   current_value = 0;
  22.   for (i=0; i < QUEUE_ENTRIES; i++)
  23.   {
  24.     // Following assumes you've written a function where the parameters
  25.     // are address, pointer to data, bytes to read
  26.     read_EEPROM(i * sizeof(QUEUE_ENTRY), &QUEUE_ENTRY, sizeof(QUEUE_ENTRY));
  27.     if ((QUEUE_ENTRY.sequence_no > last_sequence_no) && (QUEUE_ENTRY.sequence_no != 0xFFFF))
  28.     {
  29.       queue_tail = i;
  30.       last_sequence_no = QUEUE_ENTRY.sequence_no;
  31.       current_value = QUEUE_ENTRY.my_data;
  32.     }
  33.   }
  34. }
  35.  
  36. void write_value(uint16_t v)
  37. {
  38.   queue_tail++;
  39.   if (queue_tail >= QUEUE_ENTRIES)
  40.     queue_tail = 0;
  41.   last_sequence_no++;
  42.   QUEUE_ENTRY.sequence_no = last_sequence_no;
  43.   QUEUE_ENTRY.my_data = v;
  44.   // Following assumes you've written a function where the parameters
  45.   // are address, pointer to data, bytes to write
  46.   write_EEPROM(queue_tail * sizeof(QUEUE_ENTRY), &QUEUE_ENTRY, sizeof(QUEUE_ENTRY));
  47.   current_value = v;
  48. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement