一个经典的指针交换数值函数:
#include <stdio.h>
void interchange(int *u,int *v);
void interchange(int *u,int *v)
{
int temp;
temp=*v;
*v=*u;
*u=temp;
}
int main()
{
int x=5,y=10;
printf("before swap value x:%d value y:%d\n",x,y);
interchange(&x,&y);
printf("after swap value x:%d value y:%d\n",x,y);
return 0;
}
输出结果
before swap value x:5 value y:10
after swap value x:10 value y:5
//计算所要擦除 的页数
static u32 FLASH_PagesMask(vu32 Size)
{
u32 pagenumber = 0x0;
u32 size = Size;
if ((size % FLASH_PAGE_SIZE) != 0)
{
pagenumber = (size / FLASH_PAGE_SIZE) + 1;
}
else
{
pagenumber = size / FLASH_PAGE_SIZE;
}
return pagenumber;
}
/*
flash的写函数:
输入:
u32 StarAddr :FLASH起始地址
u32 p_data :待写入数据指针
u32 size :写入数据的数量
输出:
0 :写入成功
非0 :出错
注意:输入数据一定是u32 的指针,即数据一定是按照4字节对齐写入的。
所以:size也是u32的个数(字节数的4分之一)
*/
bool flash_write(u32 StartAddr,u32 *p_data,u32 size_u32)
{
volatile FLASH_Status FLASHStatus; //FLASH状态
u32 EndAddr = StartAddr + 4*size_u32; //末地址
vu32 NbrOfPage = 0;
u32 EraseCounter = 0x0, Address = 0x0;
int MemoryProgramStatus = 1,i;
FLASH_Unlock(); //FLASH解锁
NbrOfPage = FLASH_PagesMask(size_u32*4); //有多少个页被擦除
//清除所有已有标志
FLASH_ClearFlag(FLASH_FLAG_BSY | FLASH_FLAG_EOP | FLASH_FLAG_PGERR | FLASH_FLAG_WRPRTERR);
//擦除
FLASHStatus = FLASH_COMPLETE;
for(EraseCounter = 0;(EraseCounter<NbrOfPage)&&(FLASHStatus==FLASH_COMPLETE);EraseCounter++)
{
FLASHStatus = FLASH_ErasePage(StartAddr+(FLASH_PAGE_SIZE*EraseCounter));
}
//写入FLASH
Address = StartAddr;
for(i = 0 ;(Address < EndAddr) && (FLASHStatus==FLASH_COMPLETE);Address += 4)
{
FLASHStatus = FLASH_ProgramWord(Address,p_data[i++]);
}
//校验写入的数据
Address = StartAddr;
for(i = 0 ;(Address < EndAddr) && (MemoryProgramStatus != 0);Address += 4)
{
if((*(vu32*)Address != p_data[i++]))
{
MemoryProgramStatus = 0;
return false;
}
}
return true;
}
/*
flash的读函数:
输入:
u32 StarAddr :FLASH起始地址
u32 p_data :读出数据预存地址指针
u32 size :读出数据的数量
*/
bool flash_read(u32 StartAddr,u32 *p_data,u32 size_u32)
{
u32 EndAddr = StartAddr + 4*size_u32; //flash末地址
int MemoryProgramStatus = 1;
u32 Address = 0x0;
int i = 0;
Address = StartAddr;
//读取flash
while( (Address < EndAddr) && (MemoryProgramStatus != 0) )
{
p_data[i++]=(*(vu32*) Address);
Address += 4;
}
return true;
}