dstroy0
Zeroes and Ones
Code to read/write anything to adafruits SPI or i2c fram:
C++:
#include <Arduino.h> //type definitions
#include <Wire.h> //dependent
#include <Adafruit_FRAM_I2C.h> //dependent
Adafruit_FRAM_I2C fram = Adafruit_FRAM_I2C(); //fram object
//FRAM_writeAnything
template <class T> int FRAM_writeAnything(int ee, const T& value)
{
const byte* p = (const byte*)(const void*)&value;
unsigned int i;
for (i = 0; i < sizeof(value); i++)
fram.write8(ee++, *p++);
return i;
}
//FRAM_readAnything
template <class T> int FRAM_readAnything(int ee, T& value)
{
byte* p = (byte*)(void*)&value;
unsigned int i;
for (i = 0; i < sizeof(value); i++)
*p++ = fram.read8(ee++);
return i;
}
//example structure to be written/read to/from fram
struct example
{
float one = 0.0;
float two = 0.0;
float three = 0.0;
};
//struct objects
example struct_written_to_fram, struct_read_from_fram;
//number of cycles
int CYCLE_ADDRESS = 0;
//address to write/read to/from
int STRUCT_FRAM_ADDRESS = 2;
void setup() {
// put your setup code here, to run once:
//initialize serial output
Serial.begin(500000);
//initialize fram
fram.begin();
//set struct members to nonzero values
struct_written_to_fram.one = 10.0;
struct_written_to_fram.two = 100.0;
struct_written_to_fram.three = 1000.0;
//write zero to CYCLE_ADDRESS
int zero_cycles = 0;
FRAM_writeAnything(CYCLE_ADDRESS, zero_cycles);
}
void loop() {
// put your main code here, to run repeatedly:
//read cycle number from fram
int cycle = 0; //variable to read into
FRAM_readAnything(CYCLE_ADDRESS, cycle); //read cycle number from fram
//print cycle number
Serial.print(F("Cycle number: "));Serial.println(cycle);
//print struct info
Serial.print(F("Size of struct to be written: "));Serial.println(sizeof(struct_written_to_fram));
Serial.println(F("Struct member values:"));
Serial.println(struct_written_to_fram.one);
Serial.println(struct_written_to_fram.two);
Serial.println(struct_written_to_fram.three);
//write struct to fram
FRAM_writeAnything(STRUCT_FRAM_ADDRESS, struct_written_to_fram);
//read from fram into different struct
FRAM_readAnything(STRUCT_FRAM_ADDRESS, struct_read_from_fram);
//print different struct info
Serial.print(F("Size of struct read: "));Serial.println(sizeof(struct_read_from_fram));
Serial.println(struct_read_from_fram.one);
Serial.println(struct_read_from_fram.two);
Serial.println(struct_read_from_fram.three);
//increment cycle, write it to fram
cycle++;
FRAM_writeAnything(CYCLE_ADDRESS, cycle);
//wait 5 seconds
delay(5000);
}