先打开文件并且初始化stm32的下载接口,其中 InitStm32Isp 用来初始化下载接口
int main (int argc, char *argv[])
{
unsigned char *codebuf;
int len,rst;
FILE *fp;
if(argc<2)
{
printf("no bin file\n");
return 1;
}
fp=fopen(argv[1],"rb");
if(fp<=0)
{
printf("open file error\n");
return 2;
}
//把文件的位置指针移到文件尾
fseek(fp,0,SEEK_END);
//获取文件长度;
len=ftell(fp);
fseek(fp,0,SEEK_SET);
codebuf=malloc(len);
rst=fread(codebuf,1,len,fp);
printf("read:%d %d\n",len,rst);
InitStm32Isp(opencom,writecom,readcom,flushcom,closecom );
rst=DemoPro(codebuf,len);
printf("pro rst=%d\n",rst);
free(codebuf);
return 0;
}
烧录过程:
int DemoPro(unsigned char *pdata,int len)
{
int ret=0;
stm32isp.fd=stm32isp.open();
printf("fd:%d\n",stm32isp.fd);
while(1){
if(TestLink()!=0) {ret= 1;break;} //握手失败
if(GetVersionAndCmd()!=0) {ret= 2;break;} //获取版本失败
printf("ver:%d.%d\n",stm32isp.ver>>4,stm32isp.ver&0x0f);
if(stm32isp.ver!=0x22) {ret= 3;break;} //下载器的版本不对,暂时只针对2.2版本的程序
if(GetProtectState()!=0) {ret= 4;break;} //其实读取不了是不是保护的状态的
if(GetStm32TypeId()!=0) {ret= 5;break;} //获得stm32的型号
printf("stm32 type:%X\r\n",stm32isp.typeid);
if(ReadMemory(0x1FFFF7E8,12,(unsigned char*)stm32isp.onlyId)!=0) //读取唯一id,读取失败则解锁再读取
{
printf("read id eror\n");
if(UnRdProtect()!=0) {ret= 6;break;}
continue;
}
else printf("stm32id:%08X%08X%08X\n",stm32isp.onlyId[0],stm32isp.onlyId[1],stm32isp.onlyId[2]);
if(EraseFlash()!=0)
{
//擦除失败 就擦除读保护
printf("Erase Chip error\n");
if(UnRdProtect()!=0) {ret= 7;break;}
continue;
}
//if(WriteMemory(0x8000000,sizeof(testcode),testcode)!=0) {ret= 8;break;}
//printf("Write Rom ok\n");
//if(EnRdProtect()!=0) {ret= 9;break;}
//printf("read protect\n");1
//if(EnWrProtectX(0,2)!=0) {ret= 10;break;}
//printf("write protect ok\n");
if(WriteBin2Flash(pdata, len)!=0) {ret= 8;break;}
if(VerifyRom(pdata, len)!=0) {ret= 9;break;}
if(EnWrProtectX(0,64)==0)
{
//写入写保护之后 系统会重启
if(TestLink()!=0) {ret= 1;break;} //握手失败
}else {ret= 10;break;}
if(RunProgram(0x8000000)!=0) {ret= 11;break;}
break;
}
stm32isp.release(stm32isp.fd);
return ret;
}
源码下载地址 stm32_linux_isp