打印
[活动专区]

【开源活动】-基于国民N32G45x的SD卡IAP升级开发

[复制链接]
8288|0
手机看帖
扫描二维码
随时随地手机跟帖
跳转到指定楼层
楼主
本帖最后由 6552918 于 2023-4-3 09:35 编辑

#申请原创# #技术资源#@安小芯
  
测试条件
  
IDE
硬件
编译器
软件包
MDK 5.38
N32G457XVL-STB V1.1
  SD卡读写模块-SPI接口
  
SD卡、TF卡.MMC卡
ARM Compiler 6(AC6)
SD_SPI
  
FATFS
  
FLASH_IAP

1.   硬件部分说明1.1 硬件说明
使用N32G457XVL-STB V1.1开发板,因为板子上并没有集成SD卡槽,所有需要扩展一个SD卡槽,SD卡支持两种驱动模式,一种是SPI驱动,另一种是SDIO驱动,因为我手上只有SPI接口的SD卡模块,所以本例程使用的是SPI驱动SD卡进行的演示。
SD卡读写模块-SPI接口 模块
SD卡读写模块-SPI接口 模块 原理图
为了做兼容性测试 我准备了3种卡有SD卡 TF卡 MMC卡
1.2 FLASH说明
N32G457的FLASH有256个页,每个页大小为2KB,需要根据使用情况对FLASH进行划分。
本例程FLASH划分:
  
  
起始地址
结束地址
大小
页数
Bootloader区
0x8000000
0x80037FF
14KB
7
升级标志去
0x8003800
0x8003FFF
2KB
1
Application区
0x8004000
0x8026000
486KB
248
2.   软件部分说明
首先要准备一个编译无错误并运行正常的工程文件(建议使用厂家例程库里的工程,我这里使用的是uart的printf工程)
2.1   软件包移植
SD_SPI驱动移植
在工程内添加SD_SPI的驱动文件
添加.c文件
添加.h头文件路径
sdspi_port.c文件是移植的接口文件,里面需要根据实际使用情况实现接口函数,包含SPI初始化、SPI时钟速率变更及SPI数据收发函数,我这里使用的是SPI1
相关接口函数如下:
/*
* Copyright 2022 MindMotion Microelectronics Co., Ltd.
* All rights reserved.
*
* SPDX-License-Identifier: BSD-3-Clause
*/
#include <stdio.h>
#include <stdint.h>
#include "sdspi.h"
#include "n32g45x_spi.h"

/* pins:
* tx : PA7/SPI_MOSI
* rx : PA6/SPI0_MISO
* clk: PA5/SPI1_SCK
* cs : PA4/SPI0_PCS0
*/

#define BOARD_SDSPI_TX_GPIO_PORT  GPIOA
#define BOARD_SDSPI_TX_GPIO_PIN   GPIO_PIN_7

#define BOARD_SDSPI_RX_GPIO_PORT  GPIOA
#define BOARD_SDSPI_RX_GPIO_PIN   GPIO_PIN_6

#define BOARD_SDSPI_CLK_GPIO_PORT GPIOA
#define BOARD_SDSPI_CLK_GPIO_PIN  GPIO_PIN_5

#define BOARD_SDSPI_CS_GPIO_PORT  GPIOA
#define BOARD_SDSPI_CS_GPIO_PIN   GPIO_PIN_4

SDSPI_ApiRetStatus_Type sdspi_spi_init(void);
SDSPI_ApiRetStatus_Type sdspi_spi_freq(uint32_t hz);
SDSPI_ApiRetStatus_Type sdspi_spi_xfer(uint8_t *in, uint8_t *out, uint32_t len);

const SDSPI_Interface_Type board_sdspi_if =
{
    .baudrate = 1000000u, /* 1mhz. */
    .spi_init = sdspi_spi_init,
    .spi_freq = sdspi_spi_freq,
    .spi_xfer = sdspi_spi_xfer
};

uint32_t board_sdspi_delay_count;

static void board_sdspi_delay(uint32_t count)
{
    for (uint32_t i = count; i > 0u; i--)
    {
        __NOP();
    }
}

SDSPI_ApiRetStatus_Type sdspi_spi_init(void)
{
                SPI_InitType SPI_InitStructure;
        
                GPIO_SetBits(BOARD_SDSPI_CS_GPIO_PORT, BOARD_SDSPI_CS_GPIO_PIN);
        
                /*!< SPI configuration */
    SPI_InitStructure.DataDirection = SPI_DIR_DOUBLELINE_FULLDUPLEX;
    SPI_InitStructure.SpiMode       = SPI_MODE_MASTER;
    SPI_InitStructure.DataLen       = SPI_DATA_SIZE_8BITS;
    SPI_InitStructure.CLKPOL        = SPI_CLKPOL_HIGH;
    SPI_InitStructure.CLKPHA        = SPI_CLKPHA_SECOND_EDGE;
    SPI_InitStructure.NSS           = SPI_NSS_SOFT;

    SPI_InitStructure.BaudRatePres = SPI_BR_PRESCALER_128;                //        562.5K SDMMC_CLOCK_400KHZ

    SPI_InitStructure.FirstBit = SPI_FB_MSB;
    SPI_InitStructure.CRCPoly  = 7;
    SPI_Init(SPI1, &SPI_InitStructure);

    /*!< Enable the SPI1  */
    SPI_Enable(SPI1, ENABLE);

    return SDSPI_ApiRetStatus_Success;
}

SDSPI_ApiRetStatus_Type sdspi_spi_freq(uint32_t hz)
{
                SPI_InitType SPI_InitStructure;
        
                GPIO_SetBits(BOARD_SDSPI_CS_GPIO_PORT, BOARD_SDSPI_CS_GPIO_PIN);
        
                SPI_Enable(SPI1, DISABLE);
        
                /*!< SPI configuration */
    SPI_InitStructure.DataDirection = SPI_DIR_DOUBLELINE_FULLDUPLEX;
    SPI_InitStructure.SpiMode       = SPI_MODE_MASTER;
    SPI_InitStructure.DataLen       = SPI_DATA_SIZE_8BITS;
    SPI_InitStructure.CLKPOL        = SPI_CLKPOL_HIGH;
    SPI_InitStructure.CLKPHA        = SPI_CLKPHA_SECOND_EDGE;
    SPI_InitStructure.NSS           = SPI_NSS_SOFT;

    SPI_InitStructure.FirstBit = SPI_FB_MSB;
    SPI_InitStructure.CRCPoly  = 7;
   
               
    switch (hz)
    {
    case SDMMC_CLOCK_400KHZ:
                                SPI_InitStructure.BaudRatePres = SPI_BR_PRESCALER_128;                //        562.5K SDMMC_CLOCK_400KHZ
        break;
    default:
                                SPI_InitStructure.BaudRatePres = SPI_BR_PRESCALER_4;                //        18M SD_CLOCK_25MHZ
        break;
    }
               
                SPI_Init(SPI1, &SPI_InitStructure);
                /*!< Enable the sFLASH_SPI  */
    SPI_Enable(SPI1, ENABLE);
               
    return SDSPI_ApiRetStatus_Success;
}

/* SPI tx. */
void app_spi_putbyte(uint8_t c)
{
    /*!< Loop while DAT register in not emplty */
    while (SPI_I2S_GetStatus(SPI1, SPI_I2S_TE_FLAG) == RESET);

    /*!< Send byte through the SPI1 peripheral */
    SPI_I2S_TransmitData(SPI1, c);
}

/* SPI rx. */
uint8_t app_spi_getbyte(void)
{
    /*!< Wait to receive a byte */
    while (SPI_I2S_GetStatus(SPI1, SPI_I2S_RNE_FLAG) == RESET);

    /*!< Return the byte read from the SPI bus */
    return SPI_I2S_ReceiveData(SPI1);
}

uint8_t spi_xfer(uint8_t tx_dat)
{        
                /*!< Loop while DAT register in not emplty */
    while (SPI_I2S_GetStatus(SPI1, SPI_I2S_TE_FLAG) == RESET)
        ;

    /*!< Send byte through the SPI1 peripheral */
    SPI_I2S_TransmitData(SPI1, tx_dat);

    /*!< Wait to receive a byte */
    while (SPI_I2S_GetStatus(SPI1, SPI_I2S_RNE_FLAG) == RESET)
        ;

    /*!< Return the byte read from the SPI bus */
    return SPI_I2S_ReceiveData(SPI1);
}

SDSPI_ApiRetStatus_Type sdspi_spi_xfer(uint8_t *in, uint8_t *out, uint32_t len)
{
    uint8_t inbuf, outbuf;

                GPIO_ResetBits(BOARD_SDSPI_CS_GPIO_PORT, BOARD_SDSPI_CS_GPIO_PIN);

    for (uint32_t i = 0u; i < len; i++)
    {
        inbuf = (in == NULL) ? SDSPI_DUMMY_DATA: *in++;
        outbuf = spi_xfer(inbuf);
        if (out)
        {
            *out = outbuf;
            out++;
        }
    }

                GPIO_SetBits(BOARD_SDSPI_CS_GPIO_PORT, BOARD_SDSPI_CS_GPIO_PIN);

    return SDSPI_ApiRetStatus_Success;
}

/* EOF. */


FATFS移植
因为SD卡都是需要文件系统支持才能进行读写操作,因此,需要移植FATFS文件系统
fatfs 的官方网站: http://elm-chan.org/fsw/ff/00index_e.html
我这里使用的是最新的R0.15 (November 6, 2022)版本
在工程内添加FATFS的驱动文件
添加.c文件
添加.h文件路径
diskio.c文件是移植的接口文件,里面需要根据实际使用情况实现接口函数
disk_status、disk_initialize、disk_read、disk_write、disk_ioctl等函数
这些函数的具体操作需要调用SD_SPI中的先关API
/*-----------------------------------------------------------------------*/
/* Low level disk I/O module SKELETON for FatFs     (C)ChaN, 2019        */
/*-----------------------------------------------------------------------*/
/* If a working storage control module is available, it should be        */
/* attached to the FatFs via a glue function rather than modifying it.   */
/* This is an example of glue functions to attach various exsisting      */
/* storage control modules to the FatFs module with a defined API.       */
/*-----------------------------------------------------------------------*/

#include "ff.h"                        /* Obtains integer types */
#include "diskio.h"                /* Declarations of disk functions */
#include "sdspi.h"

/* Definitions of physical drive number for each drive */
#define DEV_RAM                0        /* Example: Map Ramdisk to physical drive 0 */
#define DEV_MMC                1        /* Example: Map MMC/SD card to physical drive 1 */
#define DEV_USB                2        /* Example: Map USB MSD to physical drive 2 */

SDSPI_ApiRetStatus_Type app_sdspi_ret;
SDSPI_CardHandler_Type app_sdspi_card;
extern const SDSPI_Interface_Type board_sdspi_if;

/*-----------------------------------------------------------------------*/
/* Get Drive Status                                                      */
/*-----------------------------------------------------------------------*/

DSTATUS disk_status (
        BYTE pdrv                /* Physical drive nmuber to identify the drive */
)
{
        DSTATUS stat;
        int result;

        switch (pdrv) {
        case DEV_RAM :
                //result = RAM_disk_status();

                // translate the reslut code here

                return stat;

        case DEV_MMC :
                //result = MMC_disk_status();
                stat = RES_OK;
                // translate the reslut code here

                return stat;

        case DEV_USB :
                //result = USB_disk_status();

                // translate the reslut code here

                return stat;
        }
        
        return STA_NOINIT;
}



/*-----------------------------------------------------------------------*/
/* Inidialize a Drive                                                    */
/*-----------------------------------------------------------------------*/

DSTATUS disk_initialize (
        BYTE pdrv                                /* Physical drive nmuber to identify the drive */
)
{
        DSTATUS stat;
        //int result;

        switch (pdrv) {
        case DEV_RAM :
                //result = RAM_disk_initialize();

                // translate the reslut code here

                return stat;

        case DEV_MMC :
                //result = MMC_disk_initialize();

                if(!SDSPI_Init(&app_sdspi_card, &board_sdspi_if)){
                        stat = RES_OK;
                }else{
                        stat = STA_NOINIT;
                }
                // translate the reslut code here

                return stat;

        case DEV_USB :
                //result = USB_disk_initialize();

                // translate the reslut code here

                return stat;
        }
        return STA_NOINIT;
}



/*-----------------------------------------------------------------------*/
/* Read Sector(s)                                                        */
/*-----------------------------------------------------------------------*/

DRESULT disk_read (
        BYTE pdrv,                /* Physical drive nmuber to identify the drive */
        BYTE *buff,                /* Data buffer to store read data */
        LBA_t sector,        /* Start sector in LBA */
        UINT count                /* Number of sectors to read */
)
{
        DRESULT res;
        //int result;
        uint8_t i;

        switch (pdrv) {
        case DEV_RAM :
                // translate the arguments here

                //result = RAM_disk_read(buff, sector, count);

                // translate the reslut code here

                return res;

        case DEV_MMC :
                // translate the arguments here
                        if(!SDSPI_ReadBlocks(&app_sdspi_card,buff, sector, count))
                        {
                                res = RES_OK;
                        }else{
                                res = RES_ERROR;
                        }
                //result = MMC_disk_read(buff, sector, count);
               

                // translate the reslut code here

                return res;

        case DEV_USB :
                // translate the arguments here

                //result = USB_disk_read(buff, sector, count);

                // translate the reslut code here

                return res;
        }

        return RES_PARERR;
}



/*-----------------------------------------------------------------------*/
/* Write Sector(s)                                                       */
/*-----------------------------------------------------------------------*/

#if FF_FS_READONLY == 0

DRESULT disk_write (
        BYTE pdrv,                        /* Physical drive nmuber to identify the drive */
        const BYTE *buff,        /* Data to be written */
        LBA_t sector,                /* Start sector in LBA */
        UINT count                        /* Number of sectors to write */
)
{
        DRESULT res;
        //int result;

        switch (pdrv) {
        case DEV_RAM :
                // translate the arguments here

                //result = RAM_disk_write(buff, sector, count);

                // translate the reslut code here

                return res;

        case DEV_MMC :
                // translate the arguments here

                //result = MMC_disk_write(buff, sector, count);
                if(!SDSPI_WriteBlocks(&app_sdspi_card,(uint8_t *)buff, sector, count))
                {
                        res = RES_OK;
                }else{
                        res = RES_ERROR;
                }

                // translate the reslut code here

                return res;

        case DEV_USB :
                // translate the arguments here

                //result = USB_disk_write(buff, sector, count);

                // translate the reslut code here

                return res;
        }

        return RES_PARERR;
}

#endif


/*-----------------------------------------------------------------------*/
/* Miscellaneous Functions                                               */
/*-----------------------------------------------------------------------*/

DRESULT disk_ioctl (
        BYTE pdrv,                /* Physical drive nmuber (0..) */
        BYTE cmd,                /* Control code */
        void *buff                /* Buffer to send/receive control data */
)
{
        DRESULT res;
        int result;

        switch (pdrv) {
        case DEV_RAM :

                // Process of the command for the RAM drive

                return res;

        case DEV_MMC :

                // Process of the command for the MMC/SD card
                switch(cmd)
                {
                        case GET_SECTOR_COUNT:
         *(DWORD *)buff = app_sdspi_card.blockCount;
         res = RES_OK;
         break;

      case GET_BLOCK_SIZE:
         *(DWORD *)buff = SDSPI_DEFAULT_BLOCK_SIZE;
         res = RES_OK;
         break;
                }

                return res;

        case DEV_USB :

                // Process of the command the USB drive

                return res;
        }

        return RES_PARERR;
}


FATFS定义了RAM MMC(SD/TF) USB设备的盘符,这些盘符在操作API时会用到
/* Definitions of physical drive number for each drive */
#define DEV_RAM                0        /* Example: Map Ramdisk to physical drive 0 */
#define DEV_MMC                1        /* Example: Map MMC/SD card to physical drive 1 */
#define DEV_USB                2        /* Example: Map USB MSD to physical drive 2 */

ffconf.h内是FATFS的配置文件,相关配置项需要根据自己的实际情况进行配置
/*---------------------------------------------------------------------------/
/  Configurations of FatFs Module
/---------------------------------------------------------------------------*/

#define FFCONF_DEF        80286        /* Revision ID */

/*---------------------------------------------------------------------------/
/ Function Configurations
/---------------------------------------------------------------------------*/

#define FF_FS_READONLY        0
/* This option switches read-only configuration. (0:Read/Write or 1:Read-only)
/  Read-only configuration removes writing API functions, f_write(), f_sync(),
/  f_unlink(), f_mkdir(), f_chmod(), f_rename(), f_truncate(), f_getfree()
/  and optional writing functions as well. */


#define FF_FS_MINIMIZE        0
/* This option defines minimization level to remove some basic API functions.
/
/   0: Basic functions are fully enabled.
/   1: f_stat(), f_getfree(), f_unlink(), f_mkdir(), f_truncate() and f_rename()
/      are removed.
/   2: f_opendir(), f_readdir() and f_closedir() are removed in addition to 1.
/   3: f_lseek() function is removed in addition to 2. */


#define FF_USE_FIND                0
/* This option switches filtered directory read functions, f_findfirst() and
/  f_findnext(). (0:Disable, 1:Enable 2:Enable with matching altname[] too) */


#define FF_USE_MKFS                1
/* This option switches f_mkfs() function. (0:Disable or 1:Enable) */


#define FF_USE_FASTSEEK        0
/* This option switches fast seek function. (0:Disable or 1:Enable) */


#define FF_USE_EXPAND        0
/* This option switches f_expand function. (0:Disable or 1:Enable) */


#define FF_USE_CHMOD        0
/* This option switches attribute manipulation functions, f_chmod() and f_utime().
/  (0:Disable or 1:Enable) Also FF_FS_READONLY needs to be 0 to enable this option. */


#define FF_USE_LABEL        0
/* This option switches volume label functions, f_getlabel() and f_setlabel().
/  (0:Disable or 1:Enable) */


#define FF_USE_FORWARD        0
/* This option switches f_forward() function. (0:Disable or 1:Enable) */


#define FF_USE_STRFUNC        1
#define FF_PRINT_LLI                0
#define FF_PRINT_FLOAT        0
#define FF_STRF_ENCODE        0
/* FF_USE_STRFUNC switches string functions, f_gets(), f_putc(), f_puts() and
/  f_printf().
/
/   0: Disable. FF_PRINT_LLI, FF_PRINT_FLOAT and FF_STRF_ENCODE have no effect.
/   1: Enable without LF-CRLF conversion.
/   2: Enable with LF-CRLF conversion.
/
/  FF_PRINT_LLI = 1 makes f_printf() support long long argument and FF_PRINT_FLOAT = 1/2
/  makes f_printf() support floating point argument. These features want C99 or later.
/  When FF_LFN_UNICODE >= 1 with LFN enabled, string functions convert the character
/  encoding in it. FF_STRF_ENCODE selects assumption of character encoding ON THE FILE
/  to be read/written via those functions.
/
/   0: ANSI/OEM in current CP
/   1: Unicode in UTF-16LE
/   2: Unicode in UTF-16BE
/   3: Unicode in UTF-8
*/


/*---------------------------------------------------------------------------/
/ Locale and Namespace Configurations
/---------------------------------------------------------------------------*/

#define FF_CODE_PAGE        932
/* This option specifies the OEM code page to be used on the target system.
/  Incorrect code page setting can cause a file open failure.
/
/   437 - U.S.
/   720 - Arabic
/   737 - Greek
/   771 - KBL
/   775 - Baltic
/   850 - Latin 1
/   852 - Latin 2
/   855 - Cyrillic
/   857 - Turkish
/   860 - Portuguese
/   861 - Icelandic
/   862 - Hebrew
/   863 - Canadian French
/   864 - Arabic
/   865 - Nordic
/   866 - Russian
/   869 - Greek 2
/   932 - Japanese (DBCS)
/   936 - Simplified Chinese (DBCS)
/   949 - Korean (DBCS)
/   950 - Traditional Chinese (DBCS)
/     0 - Include all code pages above and configured by f_setcp()
*/


#define FF_USE_LFN                0
#define FF_MAX_LFN                255
/* The FF_USE_LFN switches the support for LFN (long file name).
/
/   0: Disable LFN. FF_MAX_LFN has no effect.
/   1: Enable LFN with static  working buffer on the BSS. Always NOT thread-safe.
/   2: Enable LFN with dynamic working buffer on the STACK.
/   3: Enable LFN with dynamic working buffer on the HEAP.
/
/  To enable the LFN, ffunicode.c needs to be added to the project. The LFN function
/  requiers certain internal working buffer occupies (FF_MAX_LFN + 1) * 2 bytes and
/  additional (FF_MAX_LFN + 44) / 15 * 32 bytes when exFAT is enabled.
/  The FF_MAX_LFN defines size of the working buffer in UTF-16 code unit and it can
/  be in range of 12 to 255. It is recommended to be set it 255 to fully support LFN
/  specification.
/  When use stack for the working buffer, take care on stack overflow. When use heap
/  memory for the working buffer, memory management functions, ff_memalloc() and
/  ff_memfree() exemplified in ffsystem.c, need to be added to the project. */


#define FF_LFN_UNICODE        0
/* This option switches the character encoding on the API when LFN is enabled.
/
/   0: ANSI/OEM in current CP (TCHAR = char)
/   1: Unicode in UTF-16 (TCHAR = WCHAR)
/   2: Unicode in UTF-8 (TCHAR = char)
/   3: Unicode in UTF-32 (TCHAR = DWORD)
/
/  Also behavior of string I/O functions will be affected by this option.
/  When LFN is not enabled, this option has no effect. */


#define FF_LFN_BUF                255
#define FF_SFN_BUF                12
/* This set of options defines size of file name members in the FILINFO structure
/  which is used to read out directory items. These values should be suffcient for
/  the file names to read. The maximum possible length of the read file name depends
/  on character encoding. When LFN is not enabled, these options have no effect. */


#define FF_FS_RPATH                0
/* This option configures support for relative path.
/
/   0: Disable relative path and remove related functions.
/   1: Enable relative path. f_chdir() and f_chdrive() are available.
/   2: f_getcwd() function is available in addition to 1.
*/


/*---------------------------------------------------------------------------/
/ Drive/Volume Configurations
/---------------------------------------------------------------------------*/

#define FF_VOLUMES                2
/* Number of volumes (logical drives) to be used. (1-10) */


#define FF_STR_VOLUME_ID        0
#define FF_VOLUME_STRS                "RAM","NAND","CF","SD","SD2","USB","USB2","USB3"
/* FF_STR_VOLUME_ID switches support for volume ID in arbitrary strings.
/  When FF_STR_VOLUME_ID is set to 1 or 2, arbitrary strings can be used as drive
/  number in the path name. FF_VOLUME_STRS defines the volume ID strings for each
/  logical drives. Number of items must not be less than FF_VOLUMES. Valid
/  characters for the volume ID strings are A-Z, a-z and 0-9, however, they are
/  compared in case-insensitive. If FF_STR_VOLUME_ID >= 1 and FF_VOLUME_STRS is
/  not defined, a user defined volume string table is needed as:
/
/  const char* VolumeStr[FF_VOLUMES] = {"ram","flash","sd","usb",...
*/


#define FF_MULTI_PARTITION        0
/* This option switches support for multiple volumes on the physical drive.
/  By default (0), each logical drive number is bound to the same physical drive
/  number and only an FAT volume found on the physical drive will be mounted.
/  When this function is enabled (1), each logical drive number can be bound to
/  arbitrary physical drive and partition listed in the VolToPart[]. Also f_fdisk()
/  function will be available. */


#define FF_MIN_SS                512
#define FF_MAX_SS                512
/* This set of options configures the range of sector size to be supported. (512,
/  1024, 2048 or 4096) Always set both 512 for most systems, generic memory card and
/  harddisk, but a larger value may be required for on-board flash memory and some
/  type of optical media. When FF_MAX_SS is larger than FF_MIN_SS, FatFs is configured
/  for variable sector size mode and disk_ioctl() function needs to implement
/  GET_SECTOR_SIZE command. */


#define FF_LBA64                0
/* This option switches support for 64-bit LBA. (0:Disable or 1:Enable)
/  To enable the 64-bit LBA, also exFAT needs to be enabled. (FF_FS_EXFAT == 1) */


#define FF_MIN_GPT                0x10000000
/* Minimum number of sectors to switch GPT as partitioning format in f_mkfs and
/  f_fdisk function. 0x100000000 max. This option has no effect when FF_LBA64 == 0. */


#define FF_USE_TRIM                0
/* This option switches support for ATA-TRIM. (0:Disable or 1:Enable)
/  To enable Trim function, also CTRL_TRIM command should be implemented to the
/  disk_ioctl() function. */



/*---------------------------------------------------------------------------/
/ System Configurations
/---------------------------------------------------------------------------*/

#define FF_FS_TINY                0
/* This option switches tiny buffer configuration. (0:Normal or 1:Tiny)
/  At the tiny configuration, size of file object (FIL) is shrinked FF_MAX_SS bytes.
/  Instead of private sector buffer eliminated from the file object, common sector
/  buffer in the filesystem object (FATFS) is used for the file data transfer. */


#define FF_FS_EXFAT                0
/* This option switches support for exFAT filesystem. (0:Disable or 1:Enable)
/  To enable exFAT, also LFN needs to be enabled. (FF_USE_LFN >= 1)
/  Note that enabling exFAT discards ANSI C (C89) compatibility. */


#define FF_FS_NORTC                1
#define FF_NORTC_MON        1
#define FF_NORTC_MDAY        1
#define FF_NORTC_YEAR        2022
/* The option FF_FS_NORTC switches timestamp feature. If the system does not have
/  an RTC or valid timestamp is not needed, set FF_FS_NORTC = 1 to disable the
/  timestamp feature. Every object modified by FatFs will have a fixed timestamp
/  defined by FF_NORTC_MON, FF_NORTC_MDAY and FF_NORTC_YEAR in local time.
/  To enable timestamp function (FF_FS_NORTC = 0), get_fattime() function need to be
/  added to the project to read current time form real-time clock. FF_NORTC_MON,
/  FF_NORTC_MDAY and FF_NORTC_YEAR have no effect.
/  These options have no effect in read-only configuration (FF_FS_READONLY = 1). */


#define FF_FS_NOFSINFO        0
/* If you need to know correct free space on the FAT32 volume, set bit 0 of this
/  option, and f_getfree() function at the first time after volume mount will force
/  a full FAT scan. Bit 1 controls the use of last allocated cluster number.
/
/  bit0=0: Use free cluster count in the FSINFO if available.
/  bit0=1: Do not trust free cluster count in the FSINFO.
/  bit1=0: Use last allocated cluster number in the FSINFO if available.
/  bit1=1: Do not trust last allocated cluster number in the FSINFO.
*/


#define FF_FS_LOCK                0
/* The option FF_FS_LOCK switches file lock function to control duplicated file open
/  and illegal operation to open objects. This option must be 0 when FF_FS_READONLY
/  is 1.
/
/  0:  Disable file lock function. To avoid volume corruption, application program
/      should avoid illegal open, remove and rename to the open objects.
/  >0: Enable file lock function. The value defines how many files/sub-directories
/      can be opened simultaneously under file lock control. Note that the file
/      lock control is independent of re-entrancy. */


#define FF_FS_REENTRANT        0
#define FF_FS_TIMEOUT        1000
/* The option FF_FS_REENTRANT switches the re-entrancy (thread safe) of the FatFs
/  module itself. Note that regardless of this option, file access to different
/  volume is always re-entrant and volume control functions, f_mount(), f_mkfs()
/  and f_fdisk() function, are always not re-entrant. Only file/directory access
/  to the same volume is under control of this featuer.
/
/   0: Disable re-entrancy. FF_FS_TIMEOUT have no effect.
/   1: Enable re-entrancy. Also user provided synchronization handlers,
/      ff_mutex_create(), ff_mutex_delete(), ff_mutex_take() and ff_mutex_give()
/      function, must be added to the project. Samples are available in ffsystem.c.
/
/  The FF_FS_TIMEOUT defines timeout period in unit of O/S time tick.
*/



/*--- End of configuration options ---*/

片内FLASH_IAP移植
此部分直接使用原厂提供的IAP函数即可,将文件添加到工程
添加.c文件
添加.h文件路径
#include <stdio.h>
#include "iap.h"
#include "string.h"

iapfun jump2app;  
uint8_t uart_receiveBIN_ok;

uint8_t pages_number = 0;
uint32_t ready_write_addr = 0;

uint8_t flash_buf[2048];
extern uint8_t receive_app_done;
extern void IAP_UPDATE_APP(void);

/**================================================================
                读取Flash
================================================================*/
uint32_t FLASH_ReadWord(uint32_t address)
{
  return *(__IO uint32_t*)address;
}
/**================================================================
                APP 跳转
                appxaddr:用户代码起始地址.
================================================================*/
void iap_load_app(u32 appxaddr)
{
        if(((*(vu32*)appxaddr)&0x0FFFFFFF) < 1024*512)                // 检查栈顶地址是否合法.
        {
                jump2app = (iapfun)*(vu32*)(appxaddr+4);                                
                __set_MSP(*(vu32*)appxaddr);                                                // 初始化堆栈指针
                jump2app();                                                                                // 跳转到APP.
        }
}               
/**================================================================
================================================================*/
int32_t app_flag_write(uint32_t data ,uint32_t start_add)
{
        FLASH_Unlock();
        //
        FLASH_EraseOnePage(start_add);                        //写之前先擦一遍,每次擦2K
        if (FLASH_COMPL != FLASH_ProgramWord(start_add, data))                //写
        {
                FLASH_Lock();
                //printf("flash write fail! \r\n");
                return 1;
        }
        FLASH_Lock();
    return 0;
}
/**================================================================
================================================================*/
#define FLASH_PAGE_SIZE                 2048                                 

/**
* [url=home.php?mod=space&uid=247401]@brief[/url]
* @param void
* @return
* - `SUCCESS: 表示操作成功
* - 其它值表示出错
*/
int32_t app_flash_write(uint32_t *data ,uint32_t Flash_address)
{
    uint32_t i;
        uint32_t start_add;
        start_add = Flash_address;
               
        FLASH_Unlock();
        //
        for(i = 0;i<FLASH_PAGE_SIZE/FLASH_PAGE_SIZE;i++)
        {
                FLASH_EraseOnePage(start_add+i*FLASH_PAGE_SIZE);                        //写之前先擦一遍,每次擦2K
        }
        //
        for(i=0;i<FLASH_PAGE_SIZE/4 ;i++)
        {
                if (FLASH_COMPL != FLASH_ProgramWord(start_add+i*4, data[i]))                //写
                {
                        FLASH_Lock();
                        //printf("flash write fail! \r\n");
//                        receive_app_done = 0;
                        return 1;
                }
        }
        FLASH_Lock();
    return 0;
}
/**================================================================
                //升级APP
================================================================*/
void IAP_UPDATE_APP(void)
{
        ready_write_addr = FLASH_APP_BASE_ADDR + pages_number*2048;
        //
        while(app_flash_write((uint32_t *)flash_buf , ready_write_addr));                //IAP每次升级2K
        //
        memset(flash_buf,0x00,2048);
        pages_number++;

}

至此,软件包的移植工作就都完成了,接下来实现具体的逻辑操作。
2.2   升级流程说明
本实例仅实现基础功能,在实际使用过程中需要根据实际情况进行修改
整体流程如下:
整个方案流程如下
1     MCU启动
2      bootloader判断升级标志状态,标志不为0x12345678,进入步骤3,标志为0x12345678,进行跳转至app,进入步骤7
3      bootloader初始化外设
4      bootloader初始化文件系统
5      bootloader检查app升级文件是否存在,升级文件存在,输出提示信息,并等待升级命令。未收到升级命令则正常运行。
6      bootloader收到升级命令,读取SD卡内升级文件写入app区,写入完成,跳转至APP
7      app判断升级标志状态,标志不为0x12345678,代表第一次进入app,需要将升级标志写为0x12345678。标志为0x12345678,代表从bootloader正常启动。
8      app初始化外设
9      app初始化文件系统
10    app检查app升级文件是否存在,升级文件存在,输出提示信息,并等待升级命令
11    app收到升级命令,需要先擦除升级标志,并进行系统复位,回到步骤1。未收到升级命令则正常运行。

我的这个SD_IAP实例因为BootLoader和application功能都十分类似,因此使用一个工程下的不同项目进行维护
在不同点使用宏定义进行编译选择。在app内添加SD_SPI_APP宏定义作为编译开关。
不同项目输出的bin文件路径也分别进行了设置,防止出现错误
这里重点说一个MDK的小技巧,在进入bootloader和application后都要进行中断向量的重新映射才能使程序正常运行,例如:
一般的做法都是在bootloader和application使用不同的宏定义区实现,比如
这种方式在修改时有时会遗忘,比较麻烦,MDK可采用下图的方式修改,一劳永逸。不用再为不同起始地址配置不同的宏定义,一切都由MDK根据FLASH地址的配置自动设置。
void System_Init(void)
{
    /* 设置中断向量表后,开启总中断 */
    extern int Image$ER_IROM1$Base;
    __disable_irq();
    SCB->VTOR = (uint32_t)&Image$ER_IROM1$Base;
    __enable_irq();
}

3.   升级兼容性测试
为了测试此升级程序的兼容性,我准备了SD卡(512MB)TF卡(16GB)MMC卡(1GB)分别使用不同的文件格式进行了测试
SD卡(512MB)FAT格式,升级正常
SD卡(512MB)FAT32格式,升级正常
SD卡(512MB)exFAT格式,升级失败
TF卡(16GB),FAT32格式,升级正常,不支持FAT,没测试
TF卡(16GB),exFAT格式,升级失败
MMC卡(1GB)任何格式升级都失败

失败原因应该是文件系统的配置有问题,理论上3中卡都可以支持,如需对各种格式的卡进行兼容需要仔细研究ffconf.h内的配置项,根据需求进行配置。

源码: Nationstech.N32G45x_Library.2.1.0(SD_IAP).zip (5.3 MB)
视频:

  
  

使用特权

评论回复
发新帖 我要提问
您需要登录后才可以回帖 登录 | 注册

本版积分规则

认证:北京汇冠触摸技术有限公司/电子工程师
简介:电子工程师,嵌入式应用爱好者。

102

主题

1234

帖子

6

粉丝