/************************************************************************
*                             ---- 居加居 ----                           
*  文件名:      	Flash.c
*  编写人员:    	Kinve JQ
*  说明:         
*  版本:        		V0.1
*  编写日期:    	2018-09-30
*  程序维护:     
*  维护记录:    
*    					2018-09-30.Kinve:1.创建文件
* 免责声明：
* (c) Author Kinve JQ. All rights reserved.
**************************************************************************/

#include "Flash.h"

volatile unsigned char xdata page_buffer[128];


UINT8 Read_APROM_BYTE ( UINT16 code *u16_addr )
{
    UINT8 rdata;
    rdata = *u16_addr >> 8;
    return rdata;
}
/*****************************************************************************************************************
write_DATAFLASH_BYTE :
user can copy all this subroutine into project, then call this function in main.
******************************************************************************************************************/
void Write_DATAFLASH_BYTE ( unsigned int u16EPAddr, unsigned char u8EPData )
{
    unsigned char looptmp = 0;
    unsigned int u16_addrl_r;
    unsigned int RAMtmp;

//Check page start address
    u16_addrl_r = ( u16EPAddr / 128 ) * 128;

//Save APROM data to XRAM0
    for ( looptmp = 0; looptmp < 0x80; looptmp++ )
    {
        RAMtmp = Read_APROM_BYTE ( ( unsigned int code * ) ( u16_addrl_r + looptmp ) );
        page_buffer[looptmp] = RAMtmp;
    }

// Modify customer data in XRAM
    page_buffer[u16EPAddr & 0x7f] = u8EPData;

//Erase APROM DATAFLASH page
    IAPAL = u16_addrl_r & 0xff;
    IAPAH = ( u16_addrl_r >> 8 ) & 0xff;
    IAPFD = 0xFF;
    set_IAPEN;
    set_APUEN;
    IAPCN = 0x22;
    set_IAPGO;

//Save changed RAM data to APROM DATAFLASH
    set_IAPEN;
    set_APUEN;
    IAPCN = 0x21;

    for ( looptmp = 0; looptmp < 0x80; looptmp++ )
    {
        IAPAL = ( u16_addrl_r & 0xff ) + looptmp;
        IAPAH = ( u16_addrl_r >> 8 ) & 0xff;
        IAPFD = page_buffer[looptmp];
        set_IAPGO;
    }

    clr_APUEN;
    clr_IAPEN;
}

/*************** (C) COPYRIGHT Kinve JQ  *******END OF FILE **************/

