STM32F042-Drivers-Pub/flash.c
Francesco Gritti fe64f5342d initial commit
2024-05-02 12:18:04 +02:00

89 lines
1.4 KiB
C

/*
* flash.c
*
* Created on: Apr 12, 2024
* Author: Francesco Gritti
*/
#include "flash.h"
#include "ftypes.h"
void flash_unlock (void) {
if ((FLASH->CR & FLASH_CR_LOCK) != 0) {
FLASH->KEYR = FLASH_KEY1;
FLASH->KEYR = FLASH_KEY2;
}
}
void flash_lock (void) {
FLASH->CR |= FLASH_CR_LOCK;
}
void flash_erase_page (u32 page) {
// make sure no operation is ongoing
flash_wait_last_op();
FLASH->CR |= FLASH_CR_PER;
FLASH->AR = page;
FLASH->CR |= FLASH_CR_STRT;
flash_wait_last_op ();
FLASH->CR &= ~FLASH_CR_PER;
}
// write data in LITTLE ENDIAN format
u8 flash_program_word (u32 address, u32 data) {
flash_program_hword (address, (u16)data);
flash_program_hword (address +2, (u16)(data>>16));
u32 read_data = *(volatile u32*) (address);
return (read_data == data);
}
u8 flash_program_hword (u32 address, u16 data) {
flash_wait_last_op ();
FLASH->CR |= FLASH_CR_PG;
// write the byte into FLASH as if it was with a normal memory address
*(volatile u16*) (address) = data;
flash_wait_last_op ();
FLASH->CR &= ~FLASH_CR_PG;
u16 read_data = *(volatile u16*) (address);
return (read_data == data);
}
void flash_wait_last_op () {
// wait for operation to complete
while((FLASH->SR & FLASH_SR_BSY) != 0);
// clear end of operation flag if it was set
if ((FLASH->SR & FLASH_SR_EOP) != 0)
FLASH->SR |= FLASH_SR_EOP;
}