This discussion has been locked.
You can no longer post new replies to this discussion. If you have a question you can start a new discussion

STM32F030 Read/Write Flash Throwing HardFault

Hello,

I'm trying to read and write data in the flash on the STM32F030R8 Nucleo dev board. I took example firmware straight from ST, but i'm getting hardfault error whenever I tried to write to flash or read from flash. I am out of ideas, hopefully someone can shed some light on this issue.

void WriteToFlash(uint16_t Temperature){
        //Declare and initialize variables
        uint16_t *pPage = (uint16_t*)FLASH_PAGE;

        //Clear Flags
        FLASH->SR |= FLASH_SR_EOP;   //Clear end of operation flag
        FLASH->SR |= FLASH_SR_WRPRTERR;      //Clear write protect error flag
        FLASH->SR |= FLASH_SR_PGERR; //Clear programming error

        //Unlock Flash
        while ((FLASH->SR & FLASH_SR_BSY) != 0); //Wait until flash not busy
        if ((FLASH->CR & FLASH_CR_LOCK) != 0){    //If flash is locked, do unlk seq.
                FLASH->KEYR = FLASH_FKEY1;    //Unlock code 1
                FLASH->KEYR = FLASH_FKEY2;    //Unlock code 2
        }

        //Erase Page before writing
        FLASH->CR |= FLASH_CR_PER;           //Enable flash page erase
        FLASH->AR = FLASH_PAGE;              //Set page to erase
        FLASH->CR |= FLASH_CR_STRT;          //Start erase
        while ((FLASH->SR & FLASH_SR_BSY) != 0);//Wait until flash no busy
        if ((FLASH->SR & FLASH_SR_EOP) != 0){    //If flash finished operation
                FLASH->SR |= FLASH_SR_EOP;   //Clear flag
        }
        FLASH->CR &= ~FLASH_CR_PER;              //Disable page erase

        //Write to Page
        FLASH->CR |= FLASH_CR_PG;            //Write 1 to PG (programming bit)
        //*pPage = Temperature;                 //Write to flash page
         *(__IO uint16_t*)(FLASH_PAGE) = Temperature; //GET HARDFAULT HERE. CODE FROM ST
        while ((FLASH->SR & FLASH_SR_BSY) != 0);      //Wait until bus is not busy
        if ((FLASH->SR & FLASH_SR_EOP) != 0){          //Check if flash is completed
                FLASH->SR |= FLASH_SR_EOP;            //Clear flag is flash is complete
        }
        FLASH->CR &= ~FLASH_CR_PG;               //Clear prog bit to disable write to flash
}

unsigned int ReadFromFlash(void){
unsigned int *pPage = (unsigned int*)FLASH_PAGE;
unsigned int InitTemp;

        //Unlock the flash
        if ((FLASH->CR & FLASH_CR_LOCK) != 0){   //If flash is locked
                FLASH->KEYR = FLASH_FKEY1;   //Unlock code 1
                FLASH->KEYR = FLASH_FKEY2;   //Unlock code 2
        }

        //Read value in flash
        //InitTemp = *pPage;                    //Attempt to read flash mem
        InitTemp = *((uint16_t *) FLASH_PAGE);  //GET HARDFAULT HERE. CODE FROM ST

        //Lock the flash
        FLASH->CR |= FLASH_CR_LOCK;          //Lock the flash

        return InitTemp;
}

Thanks.

Parents Reply Children