really implement write user_id to flash

This commit is contained in:
Hubert Denkmair 2016-06-11 18:36:59 +02:00
parent ea1e32e86e
commit 1453d70dc9
5 changed files with 46 additions and 4 deletions

View File

@ -29,6 +29,7 @@ THE SOFTWARE.
#include <stdbool.h>
#include <stdint.h>
void flash_load();
bool flash_set_user_id(uint8_t channel, uint32_t user_id);
uint32_t flash_get_user_id(uint8_t channel);
void flash_flush();

View File

@ -14,6 +14,7 @@
MEMORY
{
FLASH (rx) : ORIGIN = 0x08000000, LENGTH = 64K
DATA (rwx) : ORIGIN = 0x0801F800, LENGTH = 2K
RAM (xrw) : ORIGIN = 0x20000000, LENGTH = 16K
/*

View File

@ -53,6 +53,12 @@ ENTRY(_start)
SECTIONS
{
/* user data flash */
.user_data : ALIGN(4)
{
*(.user_data)
} > DATA
/*
* For Cortex-M devices, the beginning of the startup code is stored in
* the .isr_vector section, which goes to FLASH.

View File

@ -24,18 +24,35 @@ THE SOFTWARE.
*/
#include "flash.h"
#include <string.h>
#include "stm32f0xx_hal_flash.h"
#define NUM_CHANNEL 1
static struct {
typedef struct {
uint32_t user_id[NUM_CHANNEL];
} flash_data;
} flash_data_t;
static flash_data_t flash_data_ram;
__attribute__((__section__(".user_data"))) const flash_data_t flash_data_rom;
void flash_load()
{
memcpy(&flash_data_ram, &flash_data_rom, sizeof(flash_data_t));
}
bool flash_set_user_id(uint8_t channel, uint32_t user_id)
{
if (channel<NUM_CHANNEL) {
flash_data.user_id[channel] = user_id;
if (flash_data_ram.user_id[channel] != user_id) {
flash_data_ram.user_id[channel] = user_id;
flash_flush();
}
return true;
} else {
return false;
@ -45,7 +62,7 @@ bool flash_set_user_id(uint8_t channel, uint32_t user_id)
uint32_t flash_get_user_id(uint8_t channel)
{
if (channel<NUM_CHANNEL) {
return flash_data.user_id[channel];
return flash_data_ram.user_id[channel];
} else {
return 0;
}
@ -54,4 +71,18 @@ uint32_t flash_get_user_id(uint8_t channel)
void flash_flush()
{
FLASH_EraseInitTypeDef erase_pages;
erase_pages.PageAddress = (uint32_t)&flash_data_rom;
erase_pages.NbPages = 1;
erase_pages.TypeErase = TYPEERASE_PAGES;
uint32_t error;
HAL_FLASH_Unlock();
__HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_EOP | FLASH_FLAG_WRPERR | FLASH_SR_PGERR);
HAL_FLASHEx_Erase(&erase_pages, &error);
if (error==0xFFFFFFFF) { // erase finished successfully
HAL_FLASH_Program(FLASH_TYPEPROGRAM_WORD, (uint32_t)&flash_data_rom.user_id[0], flash_data_ram.user_id[0]);
}
HAL_FLASH_Lock();
}

View File

@ -40,6 +40,7 @@ THE SOFTWARE.
#include "led.h"
#include "dfu.h"
#include "timer.h"
#include "flash.h"
void HAL_MspInit(void);
void SystemClock_Config(void);
@ -61,6 +62,8 @@ int main(void)
HAL_Init();
SystemClock_Config();
flash_load();
gpio_init();
led_init(&hLED, LED1_GPIO_Port, LED1_Pin, false, LED2_GPIO_Port, LED2_Pin, false);