#pragma warn-

void boot_page_ew(unsigned long p_address, char code)

{      // Erase(code=0x03) and write(code=0x05)
    #asm
      ldd r26,y+3 
      out 0x3b,r26                   ; RAMPZ-Bit0
      ldd r30,y+1                    ; Z register low byte
      ldd r31,y+2                    ; Z register high byte
      ld  r22, y
      sts 0x68, r22
      spm
    #endasm
}

void boot_page_fill(unsigned int address, int data)

{   // write a word to temporary buffer page
     #asm
       ldd r30, y+2                ;r30 = LSB of address
       ldd r31, y+3                ;r31 = MSB of address, address in the Z-register(R31:R30)
       ld r0,   y                  ;LSB of data
       ldd r1,  y+1                ;MSB of data
       ldi r22,0x01
       sts 0x68, r22
       spm
     #endasm
}

#pragma warn+

void wait_page_rw_ok(void)

{           // wait for the end of writing a flash page
     while(SPMCSR & 0x40)             // 0x40 ->RWWSB=1, page erase or page write in progress
     {
         while(SPMCSR & 0x01)

                ;                   
         SPMCSR = 0x11;               // re-enable RWW
         #asm("spm");
     }   
}            

void write_one_page(unsigned long address)

{        //write one flash page
    unsigned int i;

    boot_page_ew(address,0x03);              // erase one flash page first
    wait_page_rw_ok();                             // wait for erase finish 
                                   
    for(i=0;i<FLASH_PAGESIZE;i+=2) {               // write data to flash buffer page
       boot_page_fill(i, data[i]+(((int)data[i+1])<<8));  // one word each time
    }
    boot_page_ew(address,0x05);               // write a flash page from buffer page
    wait_page_rw_ok();                             // wait for write finish  
}        
==========================

Only code inside NRWW section

can  be read during Self-Programming (Page Erase and Page Write).

==========================

 I believe by my code specifically setting the RAMPZ value, it would cause the compiled code to attempt to load code from the application section. In my test software, there wasn't any code in the application section, so this would more than likely cause the reset.

I put the following around my flash writing routine and it fixed the issue.


 

Code:

in   r23, RAMPZ      
push   r23   ;Store the current RAMPZ value


Code:

pop   r23   ;Restore the RAMPZ value
out   RAMPZ,r23