To access the internal flash of STM32F042K6.

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers f042k6_flash.cpp Source File

f042k6_flash.cpp

00001 #include "f042k6_flash.h"
00002 
00003 #include <string.h>
00004 
00005 // Read flash content in this partition.
00006 void FlashPartition::Read(uint32_t offset, char* buf, size_t len) {
00007     memcpy(buf, (void*)(USER_FLASH_AREA_START + start_addr_ + offset), len);
00008 }
00009 
00010 // Write flash content into this partition.
00011 // Returns true for success.
00012 bool FlashPartition::Write(uint32_t offset, const char* buf, size_t len) {
00013     UnlockControlRegister();
00014 
00015     if (*REG32(FLASH_SR) & SR_BSY) {
00016         return false;
00017     }
00018 
00019     *REG32(FLASH_CR) |= CR_PG;
00020     
00021     const uint16_t* src = (uint16_t*)buf;
00022     uint16_t* dst = (uint16_t*)(USER_FLASH_AREA_START + start_addr_ + offset);
00023     for (int i = 0; i < (len + 1) / 2; i++) {
00024         *(dst++) = *(src++);
00025         while (*REG32(FLASH_SR) & SR_BSY);
00026     }
00027 
00028     *REG32(FLASH_CR) &= ~CR_PG;
00029 
00030     return true;
00031 }
00032 
00033 // Erase whole partition
00034 // Returns true for success.
00035 bool FlashPartition::EraseAll() {
00036     UnlockControlRegister();
00037     
00038     if (*REG32(FLASH_SR) & SR_BSY) {
00039         return false;
00040     }
00041 
00042     *REG32(FLASH_CR) |= CR_PER;
00043     
00044     for (uint32_t page = USER_FLASH_AREA_START + start_addr_;
00045          page < (USER_FLASH_AREA_START + start_addr_ + size_);
00046          page += kFlashPageInBytes) {
00047         *REG32(FLASH_AR) = page;
00048         *REG32(FLASH_CR) |= CR_STRT;
00049         while (*REG32(FLASH_SR) & SR_BSY);
00050     }
00051     *REG32(FLASH_CR) &= ~CR_PER;
00052 
00053     return true;
00054 }
00055 
00056 void FlashPartition::UnlockControlRegister() {
00057     if (*REG32(FLASH_CR) & CR_LOCK) {
00058         *REG32(FLASH_KEYR) = 0x45670123;
00059         *REG32(FLASH_KEYR) = 0xCDEF89AB;
00060     }
00061 }