Basic read/write from flash.

Dependencies:   mbed-modifed

main.cpp

Committer:
Dilsher
Date:
2015-11-09
Revision:
3:50a42705f3ea
Parent:
2:118a2f154b78

File content as of revision 3:50a42705f3ea:

#include "mbed.h"

//define where the EEPROM begins
#define stadr 0x08080000

Serial pcSerial(USBTX, USBRX);

//Our current offset in the EEPROM
int offset = 0;
int roffset = 0;

struct reading {
    float latitude;     //Signed positive if N, negative if S
    float longitude;    //Signed positive if W, negative if E
    float temperature;
    float pH;
    uint8_t day;
    uint8_t month;
    uint8_t year;
    uint8_t hour;
    uint8_t minutes;
};

//This function writes a byte of data to the EEPROM at the appropriate location.
//This is called by my writeEEPROMbytes.
//Use this if you want to write a single byte.
HAL_StatusTypeDef writeEEPROMByte(uint8_t data)
 {
    HAL_StatusTypeDef  status;
    int address = offset + stadr;
    offset++;
    HAL_FLASHEx_DATAEEPROM_Unlock();  //Unprotect the EEPROM to allow writing
    status = HAL_FLASHEx_DATAEEPROM_Program(TYPEPROGRAMDATA_BYTE, address, data);
    HAL_FLASHEx_DATAEEPROM_Lock();  // Reprotect the EEPROM
    return status;
}

//This function takes an array of bytes and its size and writes them to the EEPROM
//Use this if you want to write a lot of bytes.
void writeEEPROMbytes(uint8_t* data, uint8_t size)
{
    for(int i = 0; i < size; i++)
    {
        writeEEPROMByte(data[i]);
    }
}

//This function reads a byte of data from the EEPROM at the offset passed in.
//This is called by my getEEPROM function
uint8_t readEEPROMByte(uint32_t off) {
    uint8_t tmp = 0;
    off = off + stadr;
    tmp = *(__IO uint32_t*)off;
    
    return tmp;
}

//Call this function when you have sent all the data in the EEPROM through GSM
//It just resets the offset to 0 so we start writing from the start.
void resetEEPROM()
{
    offset = 0;
}

//This returns an array of bytes with size offset, that contains the entire EEPROM
//Call this function when you want to send the data over GSM
void getEEPROM(uint8_t *ptr, int nbytes)
{
    for(int i = 0; i < nbytes; i++)
    {
        ptr[i] = readEEPROMByte(roffset+i);
    }
    return;
}

int main(){
    resetEEPROM();
    pcSerial.printf("testing:\n");
    uint8_t test[] = "testing byte write and retrieval\0";
    uint8_t len = strlen((char*)test);
    writeEEPROMbytes(test, len);
    pcSerial.printf("write success\n");
    uint8_t fullStr[offset+1];
    getEEPROM(fullStr, 10);
    pcSerial.printf("String: %s\n", fullStr);
}