Basic read/write from flash.

Dependencies:   mbed-modifed

main.cpp

Committer:
ptcrews
Date:
2015-11-09
Revision:
0:cb78df310c5f
Child:
1:397846763432

File content as of revision 0:cb78df310c5f:

#include "mbed.h"

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

Serial pcSerial(USBTX, USBRX);

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

//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)
{
    for(int i = 0; i < offset; i++)
    {
        ptr[i] = readEEPROMByte(i);
    }
    return;
}

//Found this online and it claims that it resets ADC to work after deepsleep \_O_/
void resetADC()
{
    // Enable the HSI (to clock the ADC)
RCC_OscInitTypeDef RCC_OscInitStruct;
RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI;
RCC_OscInitStruct.HSIState       = RCC_HSI_ON;
RCC_OscInitStruct.PLL.PLLState   = RCC_PLL_NONE;
HAL_RCC_OscConfig(&RCC_OscInitStruct); 

}

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);
    pcSerial.printf("String: %s\n", fullStr);
}