Skip to content

Instantly share code, notes, and snippets.

@HoseanRC
Last active December 18, 2024 13:06
Show Gist options
  • Save HoseanRC/c3e1000456c5254678ba26d054af7116 to your computer and use it in GitHub Desktop.
Save HoseanRC/c3e1000456c5254678ba26d054af7116 to your computer and use it in GitHub Desktop.
native xc8 eeprom_read and eeprom_write functions to support structures instead of char array (imagine storing all your data in bits and splitted bytes manually when c can do it by itself!)
void readEE(void *var_struct, void *eeprom_struct, size_t struct_size)
{
unsigned char *var_pointer = (unsigned char *)var_struct;
unsigned char eeprom_pointer = (unsigned char)eeprom_struct;
for (unsigned char i = 0; i < struct_size; i++)
{
// based on __eeread.c in xc8 library
do
CLRWDT();
#if _EEPROM_INT == _EEREG_INT
while (EECON1bits.WR);
#elif _EEPROM_INT == _NVMREG_INT
while (NVMCON1bits.WR);
#else
#error "Unknonwn EEPROM register interface"
#endif
*var_pointer = EEPROM_READ(eeprom_pointer);
var_pointer++;
eeprom_pointer++;
}
}
void writeEE(void *var_struct, void *eeprom_struct, size_t struct_size)
{
unsigned char *var_pointer = (unsigned char *)var_struct;
unsigned char eeprom_pointer = (unsigned char)eeprom_struct;
for (unsigned char i = 0; i < struct_size; i++)
{
// based on __eewrite.c in xc8 library
EEPROM_WRITE(eeprom_pointer, *var_pointer);
var_pointer++;
eeprom_pointer++;
}
}
#ifndef _EEPROM_H
#define _EEPROM_H
#include <xc.h>
#include <stddef.h>
#include "eeprom.c"
void readEE(void *var_struct, void *eeprom_struct, size_t struct_size);
void writeEE(void *var_struct, void *eeprom_struct, size_t struct_size);
#endif
#include "eeprom.h"
// create the eeprom data structure
struct eepromData_struct {
unsigned bit0 : 1;
unsigned bit1 : 1;
unsigned char number0;
unsigned short number1;
unsigned bit2 : 1;
}
// create a pair of the same structure, one in eeprom and another in ram (a pair for each structure)
__eeprom struct eepromData_struct eepromData = {
// you can also give a default value to the eeprom structure (this is the default behavior of xc.h)
bit0 = 0,
number1 = 1000,
};
struct eepromData_struct data;
void main(void)
{
// read the data from eeprom
readEE(&data, &eepromData, sizeof(data) /* or sizeof(eepromData) as they have the same size */);
// modify the data in ram
data.number0 = 80;
// store the data in eeprom
writeEE(&data, &eepromData, sizeof(data) /* or sizeof(eepromData) as they have the same size */);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment