#include<xc.h>
/*
* Program to erase a page of flash memory
* family:dspic33ev256gm106
*/
_FOSCSEL(FNOSC_FRC & IESO_OFF);
_FOSC(FCKSM_CSECMD & OSCIOFNC_OFF & POSCMD_XT);
_FWDT(FWDTEN_OFF)
_FICD(ICS_PGD2)
#define MEMORY_PAGE_ERASE_OPERATION (3u)
#define WREN (1 << 14)
#define NVMOP (MEMORY_PAGE_ERASE_OPERATION)
#define FLASH_PAGE_ERASE_CODE (WREN | NVMOP)
#define SET (1u)
#define PM_ROW __attribute__((space(prog), aligned(2)))
const PM_ROW eoldata_in_flash[10];
unsigned int nvmAdru;
unsigned int nvmAdr;
unsigned int nvmAdrPageAligned;
int main(int argc , char *argv[])
{
PLLFBD=38; // M=40
CLKDIVbits.PLLPOST=1; // N2=4
CLKDIVbits.PLLPRE=0; // N1=2
// Initiate Clock Switch to Primary Oscillator with PLL (NOSC=0b011)
__builtin_write_OSCCONH(0x03);
__builtin_write_OSCCONL(OSCCON | 0x01);
// Wait for Clock switch to occur
while (OSCCONbits.COSC!= 0b011);
// Wait for PLL to locke
while (OSCCONbits.LOCK!= 1);
/*step1 ---> set the NVMOP<3:0> to erase the page of flash program memory */
NVMCON = FLASH_PAGE_ERASE_CODE;
/*step2: write the starting address of the page to be erased into NVMADRU and NVMADR registers */
nvmAdru=__builtin_tblpage(&eoldata_in_flash[0]);
nvmAdr=__builtin_tbloffset(&eoldata_in_flash[0]);
nvmAdrPageAligned=nvmAdr & 0xFC00; /* Get the Flash Page Aligned address */
NVMADRU = nvmAdru;
NVMADR = nvmAdrPageAligned;
/*step3: with interrupts disabled write the key sequence */
__builtin_write_NVM();
/* set the WR bit it will start erase operation */
NVMCONbits.WR = SET;
while(1);
return 0;
}