[英]How to swap two regions in FLASH memory for STM32L475 board?
我正在研究STM32L475 IoT套件,它是ARM M4 Cortex設備。 我想交換閃存的兩個區域。 我正在使用的板上有兩個用於閃存的存儲區,每個存儲區的大小為512KB。所以我有1 MB的閃存。 我讀到,要交換閃存的內容,您必須先將其解鎖,然后將其擦除,然后再寫入並在操作結束后鎖定閃存。
還有一個限制,一次只能復制2KB的內存,這被定義為一個頁面。 因此,只能逐頁復制內存。 對於我的應用程序,如果滿足某些條件,我必須交換存儲在閃存中的應用程序1和2。 盡管兩個應用程序均分配了384 KB的內存,但實際上它們都使用的內存少於該應用程序(例如264 KB)。
我嘗試按照上述步驟操作,但無法正常工作。 這是我嘗試的代碼:
#define APPLICATION_ADDRESS 0x0800F000
#define APPLICATION2_ADDRESS 0x0806F800
#define SWAP_ADDRESS 0x0806F000
boolean swap(void)
{
char *app_1=( char*) APPLICATION_ADDRESS;//points to the 1st address of application1
char *app_2=(char*) APPLICATION2_ADDRESS;//points to the 1st address of application2
int mem1 = getMemorySize((unsigned char*)APPLICATION_ADDRESS);//returns the number of bytes in Application1
int mem2 = getMemorySize((unsigned char*)APPLICATION2_ADDRESS);//returns the number of bytes in Application2
int limit;
if(mem1>mem2)
limit= mem1;
else
limit= mem2;
Unlock_FLASH();
int lm = limit/2048;
for(int i=1; i<=lm; i++,app_1+=2048,app_2+=2048)
{
int *swap = (int *)SWAP_ADDRESS;
Erase_FLASH(swap);
Write_FLASH(app_1, swap);
Erase_FLASH(app_1);
Write_FLASH(app_2, app_1);
Erase_FLASH(app_2);
Write_FLASH(swap, app_2);
}
Lock_FLASH();
return TRUE;
}
void Unlock_FLASH(void)
{
while ((FLASH->SR & FLASH_SR_BSY) != 0 );
// Check if the controller is unlocked already
if ((FLASH->CR & FLASH_CR_LOCK) != 0 ){
// Write the first key
FLASH->KEYR = FLASH_FKEY1;
// Write the second key
FLASH->KEYR = FLASH_FKEY2;
}
}
void Erase_FLASH(int *c)
{
FLASH->CR |= FLASH_CR_PER; // Page erase operation
FLASH->ACR = c; // Set the address to the page to be written
FLASH->CR |= FLASH_CR_STRT;// Start the page erase
// Wait until page erase is done
while ((FLASH->SR & FLASH_SR_BSY) != 0);
// If the end of operation bit is set...
if ((FLASH->SR & FLASH_SR_EOP) != 0){
// Clear it, the operation was successful
FLASH->SR |= FLASH_SR_EOP;
}
//Otherwise there was an error
else{
// Manage the error cases
}
// Get out of page erase mode
FLASH->CR &= ~FLASH_CR_PER;
}
void Write_FLASH(int *a, int *b)
{
for(int i=1;i<=2048;i++,a++,b++)
{
FLASH->CR |= FLASH_CR_PG; // Programing mode
*(__IO uint16_t*)(b) = *a; // Write data
// Wait until the end of the operation
while ((FLASH->SR & FLASH_SR_BSY) != 0);
// If the end of operation bit is set...
if ((FLASH->SR & FLASH_SR_EOP) != 0){
// Clear it, the operation was successful
FLASH->SR |= FLASH_SR_EOP;
}
//Otherwise there was an error
else{
// Manage the error cases
}
}
FLASH->CR &= ~FLASH_CR_PG;
}
void Lock_FLASH(void)
{
FLASH->CR |= FLASH_CR_LOCK;
}
在此,交換緩沖區用於在交換時將每個頁面(2KB)臨時存儲為緩沖區。 同樣,變量限制存儲了應用程序1和2的最大大小,因此,如前所述,在內存大小不相等的情況下進行交換時不會出錯。 所以基本上我是一頁一頁地交換,一次只交換2 KB。
任何人都可以找出代碼中的錯誤嗎?
謝謝,
舍圖
2K是2048字節 ,而不是2024。固定整個代碼的增量。
還有一個限制,一次只能復制2KB的內存
另外,這些存儲塊必須對齊2KB 。
這個地址
#define APPLICATION2_ADDRESS 0x08076400
未正確對齊,則其值應可被2048(0x800)整除。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.