#include "stm32f0xx.h"
#define FLASH_USER_START_ADDR ((uint32_t)0x08004000)
#define FLASH_USER_END_ADDR ((uint32_t)0x08008000)
#define DATA_32 ((uint32_t)0x12345678)
void flash_write(uint32_t address, uint32_t data);
int main(void) {
// Enable the Flash interface clock
RCC->AHBENR |= RCC_AHBENR_FLASHEN;
// Check if the Flash is unlocked
if (FLASH->CR & FLASH_CR_LOCK) {
// Unlock the Flash
FLASH->KEYR = FLASH_KEY1;
FLASH->KEYR = FLASH_KEY2;
}
// Perform the Flash write operation
flash_write(FLASH_USER_START_ADDR, DATA_32);
// Lock the Flash
FLASH->CR |= FLASH_CR_LOCK;
while (1) {
// Your main code here
}
}
void flash_write(uint32_t address, uint32_t data) {
// Check if the Flash is ready
while ((FLASH->SR & FLASH_SR_BSY) != 0);
// Clear previous programming errors
FLASH->SR = FLASH_SR_PGERR | FLASH_SR_WRPERR;
// Set the PG bit to enable programming
FLASH->CR |= FLASH_CR_PG;
// Perform the data write
((__IO uint32_t)address) = data;
// Wait for the end of the Flash write operation
while ((FLASH->SR & FLASH_SR_BSY) != 0);
// Check for programming errors
if ((FLASH->SR & (FLASH_SR_PGERR | FLASH_SR_WRPERR)) == 0) {
// Clear the PG bit to disable programming
FLASH->CR &= ~FLASH_CR_PG;
}
}