Skip to content

Instantly share code, notes, and snippets.

@dragonlock2
Created January 8, 2021 01:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dragonlock2/c75fe401a6d6384656cea15f4d8a7f7a to your computer and use it in GitHub Desktop.
Save dragonlock2/c75fe401a6d6384656cea15f4d8a7f7a to your computer and use it in GitHub Desktop.
Code to interact with BRCF016GWZ
#include "EEPROM.h"
extern I2C i2c;
namespace EEPROM {
void resetEEPROM() {
char buff[MAX_BLOCK_WRITE];
for (uint16_t i = 0; i < MAX_BLOCK_WRITE; i++) {
buff[i] = 0xFF;
}
for (uint16_t i = 0; i < EEPROM_SIZE; i += MAX_BLOCK_WRITE) {
writeBlock(i, buff, MAX_BLOCK_WRITE);
}
}
void dumpEEPROM() {
char buff[32]; // size determines cells per line
printf("Dumping EEPROM...\n");
for (uint16_t i = 0; i < EEPROM_SIZE; i += sizeof(buff)) {
printf("%04X : ", i);
readBites(i, buff, sizeof(buff));
for (int j = 0; j < sizeof(buff); j++) {
printf("%X ", buff[j]);
}
printf("\n");
}
}
void readBites(uint16_t addr, char* dest, uint16_t length) {
if (addr + length > EEPROM_SIZE) {
return; // not enough memory!
}
while (i2c.write(ID, NULL, 0) != 0); // wait until chip is ready
char c = addr & 0xFF;
i2c.write(ID | (PAGE_MASK & (addr >> 7)), &c, 1);
i2c.read(ID, dest, length);
}
void writeBites(uint16_t addr, char* data, uint16_t length) {
if (addr + length > EEPROM_SIZE) {
return; // not enough memory!
}
// write until page aligned
uint16_t to_page_length = ((addr + MAX_BLOCK_WRITE - 1) / MAX_BLOCK_WRITE) * MAX_BLOCK_WRITE - addr;
if (length <= to_page_length) {
writeBlock(addr, data, length);
return; // no more bytes to write
}
writeBlock(addr, data, to_page_length);
addr += to_page_length;
data += to_page_length;
length -= to_page_length;
// now we can write MAX_BLOCK_WRITE at a time
while (length >= MAX_BLOCK_WRITE) {
writeBlock(addr, data, MAX_BLOCK_WRITE);
addr += MAX_BLOCK_WRITE;
data += MAX_BLOCK_WRITE;
length -= MAX_BLOCK_WRITE;
}
writeBlock(addr, data, length);
}
void writeBlock(uint16_t addr, char* data, uint16_t length) {
while (i2c.write(ID, NULL, 0) != 0);
char buff[length + 1];
buff[0] = addr & 0xFF;
memcpy(buff + 1, data, length);
i2c.write(ID | (PAGE_MASK & (addr >> 7)), buff, length + 1);
}
}
#ifndef EEPROM_H
#define EEPROM_H
#include "mbed.h"
namespace EEPROM {
// For BRCF016GWZ
const uint8_t ID = 0b10100000; // left 4 bits is ID
const uint8_t PAGE_MASK = 0b00001110; // 3 bits determines page
const uint16_t EEPROM_SIZE = 2048; // bytes
const uint8_t MAX_BLOCK_WRITE = 16; // bytes, size of pages
void resetEEPROM(); // call this if changing size of data structure stored
void dumpEEPROM();
void readBites(uint16_t addr, char* dest, uint16_t length);
void writeBites(uint16_t addr, char* data, uint16_t length);
void writeBlock(uint16_t addr, char* data, uint16_t length);
}
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment