合并STM32 iap的hex文件合并为一个hex文件

--- title: 合并STM32 iap的hex文件合并为一个hex文件 date: 2020-06-15 04:32:26 categories: tags: - iap - stm32 ---

背景

只要设计了IAP功能,一般就需要有2段程序。手动烧写2段程序到不同的分区是一件比较麻烦的事情。

当然,也可以使用分散加载文件来把2段程序写为一个工程,但是工作量更大。

方法

记得在MDK中Options - Output 勾选 Create HEX File

先写再读写FALSH

IAP 先烧写进flash 的 0x0800 0000 开始位置, APP烧写到 flash 的0x 0800 3000开始的地方; 之后通过我上一篇博文的 IAP程序的文件读出功能读取flash 上的数据读到一个.bin文件上。然后通过程序刷写工具刷入起始flash地址为 0x0800 0000中。

手动编辑

手动合并iap 和app 的.hex 文件(麻烦,出错率高)

(1)设置IAP程序下载到flash 的开头地址为0x0800 0000,然后编译程序生成hex文件。

(2)设置APP程序下载到flash 的开头地址(地址依据芯片和程序大小而定),然后编译程序生成hex文件。

(3)用 notepad++ 打开 IAP 的hex文件和APP的hex 文件

    把IAP的.hex 最后一句结束语句去掉(即:删除:00000001FF)

    把APP的.hex 全部内容拷贝复制到 刚才删掉结束语句的 IAP的.hex后面

(4)把两个hex合成的hex文件重新命名为XXX.hex,然后通过烧写工具烧写到0x0800 0000 开始位置的地址即可。

这里有python3的实现

# -*- coding: utf-8 -*-
import sys,os
import intelhex

def createHelpDialog():
    #print("软件实现的是将两个Hex文件同时转为Bin文件并且合并为一个Bin文件输出的功能。") 
    print("将两个Hex文件合并为一个Hex文件。") 
        
def mergeHex(inhex1, inhex2, outhex):
    # 两个 hex
   #inHex1 = 'bootloader.hex'
   #inHex2 = 'app.hex'
   #outHex = 'python.hex'

    inHex1 = inhex1
    inHex2 = inhex2
    outHex = outhex
    
    #get file name
    hex_boot_len = os.path.getsize(inHex1)
    hex_app_len  = os.path.getsize(inHex2)
    print("First %s size is %d"  %(inHex1,  hex_boot_len))
    print("Second %s size is %d"%(inHex2, hex_boot_len))
    ## 删除 之前的结果
    if(os.path.isfile(outHex)):
        os.remove(outHex)
    
    #先读写hex,再合并成bin
    print("Merge Hex file....") 
    hex_boot_file = open(inHex1, 'rb')
    hex_app_file = open(inHex2, 'rb')
    hex_file = open(outHex, 'ab')
    
    for h in hex_boot_file.readlines():
        if h == b':00000001FF
' : 
            print(h)
            break
        else :
            hex_file.write(h)
            continue
        
    for h in hex_app_file.readlines():
        hex_file.write(h)
    hex_file.write(b'
')
        
    hex_boot_file.close()
    hex_app_file.close()
    hex_file.close()

def hex2bin(mergeHex, outBin) :
    ## 删除 之前的结果
    if(os.path.isfile(outBin)):
        os.remove(outBin)
    print("Hex File To Bin File...")
    # BUG 
    intelhex.hex2bin(mergeHex, outBin, None, None, None, 00)
    if(os.path.isfile(outBin)):
       bin_file_len = os.path.getsize(outBin)
       print("Bin File is [%s] "%(outBin))
       print("Bin File size is [%d] "%(bin_file_len))
       print("Hex File To Bin File completly")

if __name__ == "__main__":
    #mergeHex('bootloader.hex', 'app.hex', 'python2.hex')
    #hex2bin('python.hex', 'python.bin')
    hex2bin('merge.hex', 'python.bin')

使用现成的工具

我在网上找到了一个开源的项目:STM32-IAP-HEX-Merge

语言为c#,运行环境为 vs

原文地址:https://www.cnblogs.com/schips/p/13131723.html