Falsh的写入函数

这里写自定义目录标题

Falsh的写入函数


/**
 * @Description: 
 * @param {unsigned int} address
 * @param {void} *pbuf
 * @param {int} NumByteToWrite
 * @return {*}
 */
int User_Read_flash(unsigned int address, void *pbuf, int NumByteToWrite)
{
    hal_flash_read(address,pbuf,NumByteToWrite);
    return MK_EOK;   
}

/**
 * @Description: 
 * @param {unsigned int} address
 * @param {void} *pbuf
 * @param {int} len
 * @return {*}
 */
int writer_flash(unsigned int address, void *pbuf, int len)
{   
    hal_flash_unlock();
    hal_flash_write(address,pbuf,len);
    hal_flash_lock();
    return MK_EOK;   
}
/**
 * @Description: 
 * @param {unsigned int} address
 * @param {void} *pbuf
 * @return {*}
 */
int User_Write_Page_Nocheck(unsigned int address,void *pbuf)
{
    writer_flash(address,pbuf,2048);
    return MK_EOK;   
}
/**
 * @Description: 
 * @param {unsigned int} address
 * @return {*}
 */
int User_Erase_Page(unsigned int address)   
{    
    hal_flash_unlock();
    if(hal_flash_erase(address,2048) == MK_EOK)
	{
		hal_flash_lock();
		return MK_EOK;
	}
    return MK_ERR;
}
/**
 * @Description: 
 * @param {unsigned int} address
 * @param {void} *pbuf
 * @param {int} NumByteToWrite
 * @return {*}
 */

int User_Write_Flash(unsigned int address, void *pbuf, int NumByteToWrite)
{
    uint8_t *buf = (uint8_t *)pbuf;
    uint32_t secpos;	
	uint16_t secoff;
    uint16_t secremain;
	uint16_t i;
	
    uint8_t *Buffer;
	Buffer = rt_malloc(2048);
	if (!Buffer)
    {
        LOG_E("%d[%s] malloc failed.", __func__, __LINE__);
        return MK_ERR;
    }

	secoff = address % 2048;  //Intra-sector offset
    secpos = address - secoff;  //Sector address  

    secremain=2048-secoff;  //Sector remaining size
    if(NumByteToWrite<=secremain)
        secremain=NumByteToWrite;
        
	User_Read_flash(secpos,Buffer,2048);
    while(1) 
	{	
		for(i = 0;i < secremain;i++)
		{
			if(Buffer[secoff+i]!=0XFF)
				break;  	  
		}
		if(i<secremain)
		{
			User_Erase_Page(secpos);
			for(i=0;i<secremain;i++)
			{
				Buffer[i+secoff] = buf[i];	  
			}
			User_Write_Page_Nocheck(secpos,Buffer);  
		}
        else 
            writer_flash(address,buf,secremain);

		if(NumByteToWrite==secremain)
            break;
		else
		{
			secpos++;
			secoff=0;	 
		   	buf+=secremain;  				
			address+=secremain;					   
		   	NumByteToWrite-=secremain;			
			if(NumByteToWrite>2048)secremain=2048;
			else secremain=NumByteToWrite;		
		}	 
	}	

	rt_free(Buffer);
    return  MK_EOK;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值