Files @ 0f4aded51dc1
Branch filter:

Location: HydroBot/hydrobot-sharedlibs/src/flash.c

matthewreed
Fixed flash HAL definitions again
#include "flash.h"

__attribute__((__section__(".eeprom"))) uint16_t eeprom[512];

#define MAGIC_NUMBER 0x0BAE

static void __flash_write(flash_settings_t* tosave);

void flash_save(flash_settings_t* tosave)
{
    __flash_write(tosave);
}

void flash_restore(flash_settings_t* torestore)
{
    //read flash and calculate checksum
    uint16_t checksum = MAGIC_NUMBER;
    uint16_t i;
    for(i = 0; i < (sizeof(flash_settings_t)/2); i++)
    {
        torestore->data[i] = eeprom[i];
        checksum ^= torestore->data[i];
    }

    //if checksum doesn't match, load default settings
    if((checksum ^ eeprom[i+1]) != 0) {
        flash_load_defaults(torestore);
    }
}

void flash_load_defaults(flash_settings_t* torestore)
{

    torestore->val.can_id = DEFAULT_CAN_ID;
    torestore->val.data_rate = DEFAULT_DATA_RATE;
    torestore->val.led_brightness = DEFAULT_LED_BRIGHTNESS;

}

static void __flash_write(flash_settings_t* tosave)
{
    //TODO: Check to see if anything has changed before saving

    // Erase mem
    HAL_FLASH_Unlock();

    // Erase the FLASH pages
    FLASH_EraseInitTypeDef erase;
    erase.TypeErase = FLASH_TYPEERASE_PAGES;
    erase.PageAddress = (uint32_t) eeprom;
    erase.NbPages = 1;
    uint32_t SectorError = 0;
    HAL_FLASHEx_Erase(&erase, &SectorError);
    CLEAR_BIT(FLASH->CR, FLASH_CR_PER);

    // write to flash and calculate the checksum
    uint16_t checksum = MAGIC_NUMBER;
    uint16_t i;
    for(i = 0; i < (sizeof(flash_settings_t)/2); i++)
    {
        HAL_FLASH_Program(FLASH_TYPEPROGRAM_HALFWORD, (uint32_t)&eeprom[i], tosave->data[i]);
        checksum ^= tosave->data[i];
    }

    // write the checksum
    HAL_FLASH_Program(FLASH_TYPEPROGRAM_HALFWORD, (uint32_t)&eeprom[i+1], checksum);

    HAL_FLASH_Lock();
}