RTT小师弟 · 2022年05月10日

【国产MCU移植】手把手教你使用RT-Thread制作GD32F103系列BSP

本文由RT-Thread论坛用户@爱玩的小赵 原创发布:https://club.rt-thread.org/ask/article/ee67f1b59306ada8.html

熟悉RT-Thread的朋友都知道,RT-Thread提供了许多BSP,但不是所有的板子都能找到相应的BSP,这时就需要移植新的BSP。RT-Thread的所有BSP中,最完善的BSP就是STM32系列,但从2020年下半年开始,国内出现史无前例的芯片缺货潮,我们参考STM32F103系列进行GD32F103系列的BSP制作。
我使用的是GD32F103VET6芯片进行移植,在文章的末尾附上本人gitee库。

1 BSP 框架制作

在具体移植GD32407V-START的BSP之前,先做好GD32的BSP架构。BSP 框架结构如下图所示:
在这里插入图片描述
9f7e6ccb3bdd46e7878f6a700dd44997.png

GD32的BSP架构主要分为三个部分:libraries、tools和具体的Boards,其中libraries包含了GD32的通用库,包括每个系列的HAL以及适配RT-Thread的drivers;tools是生成工程的Python脚本工具;另外就是Boards文件,当然这里的Boards有很多,我这里值列举了GD32103C-eval。

这里先谈谈libraries和tools的构建,然后在后文单独讨论具体板级BSP的制作。

1.1 Libraries构建

Libraries文件夹包含兆易创新提供的HAL库,这个直接在兆易创新的官网就可以下载。
http://www.gd32mcu.com/cn/download/0?kw=GD32F1
然后将HAL库(GD32F10x_Firmware_Library)复制到libraries目录下,重命名为GD32F10x_Firmware_Library,其他的系列类似
bc9f564d7557f4724a83a04ecadb1663.png
GD32F10x_Firmware_Library就是官方的文件,基本是不用动的,只是在文件夹中需要添加构建工程的脚本文件SConscript,其实也就是Python脚本。
7a588809191cf6065e2caf4dd1234c2e.png
SConscript文件的内容如下:

import rtconfig
from building import *

# get current directory
cwd = GetCurrentDir()

# The set of source files associated with this SConscript file.

src = Split('''
CMSIS/GD/GD32F10x/Source/system_gd32f10x.c
GD32F10x_standard_peripheral/Source/gd32f10x_gpio.c
GD32F10x_standard_peripheral/Source/gd32f10x_rcu.c
GD32F10x_standard_peripheral/Source/gd32f10x_exti.c
GD32F10x_standard_peripheral/Source/gd32f10x_misc.c
''')
    
if GetDepend(['RT_USING_SERIAL']):
    src += ['GD32F10x_standard_peripheral/Source/gd32f10x_usart.c']
    
if GetDepend(['RT_USING_I2C']):
    src += ['GD32F10x_standard_peripheral/Source/gd32f10x_i2c.c']

if GetDepend(['RT_USING_SPI']):
    src += ['GD32F10x_standard_peripheral/Source/gd32f10x_spi.c']

if GetDepend(['RT_USING_CAN']):
    src += ['GD32F10x_standard_peripheral/Source/gd32f10x_can.c']

if GetDepend(['BSP_USING_ETH']):
    src += ['GD32F10x_standard_peripheral/Source/gd32f10x_enet.c']

if GetDepend(['RT_USING_ADC']):
    src += ['GD32F10x_standard_peripheral/Source/gd32f10x_adc.c']

if GetDepend(['RT_USING_DAC']):
    src += ['GD32F10x_standard_peripheral/Source/gd32f10x_dac.c']

if GetDepend(['RT_USING_HWTIMER']):
    src += ['GD32F10x_standard_peripheral/Source/gd32f10x_timer.c']

if GetDepend(['RT_USING_RTC']):
    src += ['GD32F10x_standard_peripheral/Source/gd32f10x_rtc.c']
    src += ['GD32F10x_standard_peripheral/Source/gd32f10x_pmu.c']

if GetDepend(['RT_USING_WDT']):
    src += ['GD32F10x_standard_peripheral/Source/gd32f10x_wwdgt.c']
    src += ['GD32F10x_standard_peripheral/Source/gd32f10x_fwdgt.c']

if GetDepend(['RT_USING_SDIO']):
    src += ['GD32F10x_standard_peripheral/Source/gd32f10x_sdio.c']

path = [
    cwd + '/CMSIS/GD/GD32F10x/Include',
    cwd + '/CMSIS',
    cwd + '/GD32F10x_standard_peripheral/Include',]

CPPDEFINES = ['USE_STDPERIPH_DRIVER']

group = DefineGroup('Libraries', src, depend = [''], CPPPATH = path, CPPDEFINES = CPPDEFINES)

Return('group')

该文件主要的作用就是添加库文件和头文件路径,一部分文件是属于基础文件,因此直接调用Python库的Split包含,另外一部分文件是根据实际的应用需求添加的。

接下来说说Kconfig文件,这里是对内核和组件的功能进行配置,对RT-Thread的组件进行自由裁剪。

如果使用RT-Thread studio,则通过RT-Thread Setting可以体现Kconfig文件的作用。
760eb2bc867748bc93a170686136d35e.png
如果使用ENV环境,则在使用 menuconfig配置和裁剪 RT-Thread时体现。
8aa44fe3a4f94fe783d57482011ed376.png
后面所有的Kconfig文件都是一样的逻辑。下表列举一些常用的Kconfig句法规则。aeed50adcc294b71aeb6fe6ecc6e6947.png
Kconfig的语法规则网上资料很多,自行去学习吧。

bsp/gd32/Kconfig内容如下:

config SOC_FAMILY_GD32
    bool

config SOC_SERIES_GD32F1
    bool
    select ARCH_ARM_CORTEX_M3
    select SOC_FAMILY_GD32

config SOC_SERIES_GD32F2
    bool
    select ARCH_ARM_CORTEX_M3
    select SOC_FAMILY_GD32

config SOC_SERIES_GD32F3
    bool
    select ARCH_ARM_CORTEX_M4
    select SOC_FAMILY_GD32

config SOC_SERIES_GD32F4
    bool
    select ARCH_ARM_CORTEX_M4
    select SOC_FAMILY_GD32

最后谈谈HAL_Drivers,这个文件夹就是GD32的外设驱动文件夹,为上层应用提供调用接口。
65f7b0e02708474f889d10f933066857.png.webp
好了,先看E:\RT_Thread\GD32_BSP\rt_thread_code\bsp\gd32f103\libraries\gd32_drivers/SConscript文件。

Import('RTT_ROOT')
Import('rtconfig')
from building import *

cwd = GetCurrentDir()

# add the general drivers.
src = Split("""
""")

# add pin drivers.
if GetDepend('RT_USING_PIN'):
    src += ['drv_gpio.c']

# add usart drivers.
if GetDepend(['RT_USING_SERIAL']):
    src += ['drv_usart.c']

# add i2c drivers.
if GetDepend(['RT_USING_I2C', 'RT_USING_I2C_BITOPS']):
    if GetDepend('BSP_USING_I2C0') or GetDepend('BSP_USING_I2C1') or GetDepend('BSP_USING_I2C2') or GetDepend('BSP_USING_I2C3'):
        src += ['drv_soft_i2c.c']

# add spi drivers.
if GetDepend('RT_USING_SPI'):
    src += ['drv_spi.c']

# add spi flash drivers.
if GetDepend('RT_USING_SFUD'):
    src += ['drv_spi_flash.c', 'drv_spi.c']

if GetDepend('RT_USING_WDT'):
    src += ['drv_wdt.c']

if GetDepend('RT_USING_RTC'):
    src += ['drv_rtc.c']

if GetDepend('RT_USING_HWTIMER'):
    src += ['drv_hwtimer.c']

if GetDepend('RT_USING_ADC'):
    src += ['drv_adc.c']

path = [cwd]

group = DefineGroup('Drivers', src, depend = [''], CPPPATH = path)

Return('group')

E:\RT_Thread\GD32_BSP\rt_thread_code\bsp\gd32f103\libraries\gd32_drivers/Kconfig文件结构如下:

if BSP_USING_USBD
    config BSP_USBD_TYPE_FS
        bool
        # "USB Full Speed (FS) Core"
    config BSP_USBD_TYPE_HS
        bool
        # "USB High Speed (HS) Core"

    config BSP_USBD_SPEED_HS
        bool 
        # "USB High Speed (HS) Mode"
    config BSP_USBD_SPEED_HSINFS
        bool 
        # "USB High Speed (HS) Core in FS mode"

    config BSP_USBD_PHY_EMBEDDED
        bool 
        # "Using Embedded phy interface"
    config BSP_USBD_PHY_UTMI
        bool 
        # "UTMI: USB 2.0 Transceiver Macrocell Interace"
    config BSP_USBD_PHY_ULPI
        bool 
        # "ULPI: UTMI+ Low Pin Interface"
endif

1.2 Tools构建

该文件夹就是工程构建的脚本,

import os
import sys
import shutil

cwd_path = os.getcwd()
sys.path.append(os.path.join(os.path.dirname(cwd_path), 'rt-thread', 'tools'))


# BSP dist function
def dist_do_building(BSP_ROOT, dist_dir):
    from mkdist import bsp_copy_files
    import rtconfig

    print("=> copy gd32 bsp library")
    library_dir = os.path.join(dist_dir, 'libraries')
    library_path = os.path.join(os.path.dirname(BSP_ROOT), 'libraries')
    bsp_copy_files(os.path.join(library_path, rtconfig.BSP_LIBRARY_TYPE),
                   os.path.join(library_dir, rtconfig.BSP_LIBRARY_TYPE))

    print("=> copy bsp drivers")
    bsp_copy_files(os.path.join(library_path, 'HAL_Drivers'), os.path.join(library_dir, 'HAL_Drivers'))
    shutil.copyfile(os.path.join(library_path, 'Kconfig'), os.path.join(library_dir, 'Kconfig'))

以上代码很简单,主要使用了Python的OS模块的join函数,该函数的作用就是连接两个或更多的路径名。最后将BSP依赖的文件复制到指定目录下。

在使用scons --dist 命令打包的时候,就是依赖的该脚本,生成的dist 文件夹的工程到任何目录下使用,也就是将BSP相关的库以及内核文件提取出来,可以将该工程任意拷贝。

1.3 gd32f103vet6-eval构建

2fea1027571f442d89337d865510f1f7.png

2 BSP移植

2.1 Keil环境准备

接下来我们下载GD32F30x的软件支持包。
下载地址:http://www.gd32mcu.com/cn/dow...
1e724716a4379d4171c8aaeaa94bcb9e.png
双击安装包,按照操作步骤进行安装。
安装成功后,重新打开Keil,则可以在File->Device Database中出现Gigadevice的下拉选项,点击可以查看到相应的型号。
28b20cfdd836e6c554fcaefa4c89ead9.png.webp

2.2 BSP工程制作

1.构建基础工程
首先看看RT-Thread代码仓库中已有很多BSP,而我要移植的是Cortex-M4内核。这里我找了一个相似的内核,把它复制一份,并修改文件名为:gd32103C-eval。这样就有一个基础的工程。然后就开始增删改查,完成最终的BSP,几乎所有的BSP的制作都是如此。
2.修改BSP构建脚本
E:\RT_Thread\GD32_BSP\rt_thread_code\bsp\gd32f103\gd32f103vet6/Kconfig修改后的内容如下

mainmenu "RT-Thread Configuration"

config BSP_DIR
    string
    option env="BSP_ROOT"
    default "."

config RTT_DIR
    string
    option env="RTT_ROOT"
    default "../../.."

config PKGS_DIR
    string
    option env="PKGS_ROOT"
    default "packages"
 
source "$RTT_DIR/Kconfig"
source "$PKGS_DIR/Kconfig"
source "../libraries/Kconfig"
source "board/Kconfig"

该文件是获取所有路径下的Kconfig。

E:\RT_Thread\GD32_BSP\rt_thread_code\bsp\gd32f103\gd32f103vet6/SConscript修改后的内容如下:

# for module compiling
import os
Import('RTT_ROOT')
from building import *

cwd = GetCurrentDir()
objs = []
list = os.listdir(cwd)

for d in list:
    path = os.path.join(cwd, d)
    if os.path.isfile(os.path.join(path, 'SConscript')):
        objs = objs + SConscript(os.path.join(d, 'SConscript'))

Return('objs')

该文件是用于遍历当前目录的所有文件夹。

E:\RT_Thread\GD32_BSP\rt_thread_code\bsp\gd32f103\gd32f103vet6/SConstruct修改后的内容如下:

import os
import sys
import rtconfig

if os.getenv('RTT_ROOT'):
    RTT_ROOT = os.getenv('RTT_ROOT')
else:
    RTT_ROOT = os.path.normpath(os.getcwd() + '/../../..')

sys.path = sys.path + [os.path.join(RTT_ROOT, 'tools')]
try:
    from building import *
except:
    print('Cannot found RT-Thread root directory, please check RTT_ROOT')
    print(RTT_ROOT)
    exit(-1)

TARGET = 'rtthread.' + rtconfig.TARGET_EXT

DefaultEnvironment(tools=[])
env = Environment(tools = ['mingw'],
    AS = rtconfig.AS, ASFLAGS = rtconfig.AFLAGS,
    CC = rtconfig.CC, CCFLAGS = rtconfig.CFLAGS,
    AR = rtconfig.AR, ARFLAGS = '-rc',
    CXX = rtconfig.CXX, CXXFLAGS = rtconfig.CXXFLAGS,
    LINK = rtconfig.LINK, LINKFLAGS = rtconfig.LFLAGS)
env.PrependENVPath('PATH', rtconfig.EXEC_PATH)

if rtconfig.PLATFORM == 'iar':
    env.Replace(CCCOM = ['$CC $CCFLAGS $CPPFLAGS $_CPPDEFFLAGS $_CPPINCFLAGS -o $TARGET $SOURCES'])
    env.Replace(ARFLAGS = [''])
    env.Replace(LINKCOM = env["LINKCOM"] + ' --map rtthread.map')

Export('RTT_ROOT')
Export('rtconfig')

SDK_ROOT = os.path.abspath('./')

if os.path.exists(SDK_ROOT + '/libraries'):
    libraries_path_prefix = SDK_ROOT + '/libraries'
else:
    libraries_path_prefix = os.path.dirname(SDK_ROOT) + '/libraries'

SDK_LIB = libraries_path_prefix
Export('SDK_LIB')

# prepare building environment
objs = PrepareBuilding(env, RTT_ROOT, has_libcpu=False)

gd32_library = 'GD32F10x_Firmware_Library'
rtconfig.BSP_LIBRARY_TYPE = gd32_library

# include libraries
objs.extend(SConscript(os.path.join(libraries_path_prefix, gd32_library, 'SConscript')))

# include drivers
objs.extend(SConscript(os.path.join(libraries_path_prefix, 'gd32_drivers', 'SConscript')))

# make a building
DoBuilding(TARGET, objs)

该文件用于链接所有的依赖文件,并调用make进行编译。
3.修改开发环境信息
E:\RT_Thread\GD32_BSP\rt_thread_code\bsp\gd32f103\gd32f103vet6/cconfig.h修改后的内容如下

#ifndef CCONFIG_H__
#define CCONFIG_H__
/* Automatically generated file; DO NOT EDIT. */
/* compiler configure file for RT-Thread in GCC*/

#define HAVE_NEWLIB_H 1
#define LIBC_VERSION "newlib 2.4.0"

#define HAVE_SYS_SIGNAL_H 1
#define HAVE_SYS_SELECT_H 1
#define HAVE_PTHREAD_H 1

#define HAVE_FDSET 1
#define HAVE_SIGACTION 1
#define GCC_VERSION_STR "5.4.1 20160919 (release) [ARM/embedded-5-branch revision 240496]"
#define STDC "2011"

#endif

该文件是是编译BSP的环境信息,需根据实时修改。
4.修改KEIL的模板工程
双击:template.uvprojx即可修改模板工程。
修改为对应芯片设备:
f8cf340361179082a4c4452b36cd981d.png.webp
修改FLASH和RAM的配置:该部分需参照技术手册进行修改
b50aa6a51bd6f4336ea28f34721cd743.png.webp

修改可执行文件名字:
2bdfa55c14e83002b755060b016da075.png

修改默认调试工具:CMSIS-DAP Debugger。
P72Q03Q_2PJ5MQX1OUEVLPX.png
修改编程算法:
5b25080f219792d40003921acc5809c6.png.webp
5.修改board文件夹
(1) 修改E:\RT_Thread\GD32_BSP\rt_thread_code\bsp\gd32f103\gd32f103vet6\board\linker_scripts/link.icf

修改后的内容如下

/*###ICF### Section handled by ICF editor, don't touch! ****/
/*-Editor annotation file-*/
/* IcfEditorFile="$TOOLKIT_DIR$\config\ide\IcfEditor\cortex_v1_0.xml" */
/*-Specials-*/
define symbol __ICFEDIT_intvec_start__ = 0x08000000;
/*-Memory Regions-*/
define symbol __ICFEDIT_region_ROM_start__ = 0x08000000;
define symbol __ICFEDIT_region_ROM_end__   = 0x08080000;
define symbol __ICFEDIT_region_RAM_start__ = 0x20000000;
define symbol __ICFEDIT_region_RAM_end__   = 0x20010000;
/*-Sizes-*/
define symbol __ICFEDIT_size_cstack__ = 0x200;
define symbol __ICFEDIT_size_heap__   = 0x200;
/**** End of ICF editor section. ###ICF###*/

export symbol __ICFEDIT_region_RAM_end__;

define symbol __region_RAM1_start__ = 0x10000000;
define symbol __region_RAM1_end__   = 0x1000FFFF;

define memory mem with size = 4G;
define region ROM_region   = mem:[from __ICFEDIT_region_ROM_start__   to __ICFEDIT_region_ROM_end__];
define region RAM_region   = mem:[from __ICFEDIT_region_RAM_start__   to __ICFEDIT_region_RAM_end__];
define region RAM1_region  = mem:[from __region_RAM1_start__   to __region_RAM1_end__];

define block CSTACK    with alignment = 8, size = __ICFEDIT_size_cstack__   { };
define block HEAP      with alignment = 8, size = __ICFEDIT_size_heap__     { };

initialize by copy { readwrite };
do not initialize  { section .noinit };

keep { section FSymTab };
keep { section VSymTab };
keep { section .rti_fn* };
place at address mem:__ICFEDIT_intvec_start__ { readonly section .intvec };

place in ROM_region   { readonly };
place in RAM_region   { readwrite,
                        block CSTACK, block HEAP };                        
place in RAM1_region  { section .sram };

该文件是IAR编译的链接脚本,根据《GD32F103xx_Datasheet_Rev2.1》可知,GD32F103VET6的flash大小为3072KB,SRAM大小为192KB,因此需要设置ROM和RAM的起始地址和堆栈大小等。

(2) 修改E:\RT_Thread\GD32_BSP\rt_thread_code\bsp\gd32f103\gd32f103vet6\board\linker_scripts/link.ld
修改后的内容如下:

/*
 * linker script for GD32F30x with GNU ld
 * BruceOu 2021-12-18
 */

/* Program Entry, set to mark it as "used" and avoid gc */
MEMORY
{
    CODE (rx) : ORIGIN = 0x08000000, LENGTH = 512k /* 256KB flash */
    DATA (rw) : ORIGIN = 0x20000000, LENGTH =  64k /* 48KB sram */
}
ENTRY(Reset_Handler)
_system_stack_size = 0x200;

SECTIONS
{
    .text :
    {
        . = ALIGN(4);
        _stext = .;
        KEEP(*(.isr_vector))            /* Startup code */
        . = ALIGN(4);
        *(.text)                        /* remaining code */
        *(.text.*)                      /* remaining code */
        *(.rodata)                      /* read-only data (constants) */
        *(.rodata*)
        *(.glue_7)
        *(.glue_7t)
        *(.gnu.linkonce.t*)

        /* section information for finsh shell */
        . = ALIGN(4);
        __fsymtab_start = .;
        KEEP(*(FSymTab))
        __fsymtab_end = .;
        . = ALIGN(4);
        __vsymtab_start = .;
        KEEP(*(VSymTab))
        __vsymtab_end = .;
        . = ALIGN(4);

        /* section information for initial. */
        . = ALIGN(4);
        __rt_init_start = .;
        KEEP(*(SORT(.rti_fn*)))
        __rt_init_end = .;
        . = ALIGN(4);

        . = ALIGN(4);
        _etext = .;
    } > CODE = 0

    /* .ARM.exidx is sorted, so has to go in its own output section.  */
    __exidx_start = .;
    .ARM.exidx :
    {
        *(.ARM.exidx* .gnu.linkonce.armexidx.*)

        /* This is used by the startup in order to initialize the .data secion */
        _sidata = .;
    } > CODE
    __exidx_end = .;

    /* .data section which is used for initialized data */

    .data : AT (_sidata)
    {
        . = ALIGN(4);
        /* This is used by the startup in order to initialize the .data secion */
        _sdata = . ;

        *(.data)
        *(.data.*)
        *(.gnu.linkonce.d*)

        . = ALIGN(4);
        /* This is used by the startup in order to initialize the .data secion */
        _edata = . ;
    } >DATA

    .stack : 
    {
        . = . + _system_stack_size;
        . = ALIGN(4);
        _estack = .;
    } >DATA

    __bss_start = .;
    .bss :
    {
        . = ALIGN(4);
        /* This is used by the startup in order to initialize the .bss secion */
        _sbss = .;

        *(.bss)
        *(.bss.*)
        *(COMMON)

        . = ALIGN(4);
        /* This is used by the startup in order to initialize the .bss secion */
        _ebss = . ;
        
        *(.bss.init)
    } > DATA
    __bss_end = .;

    _end = .;

    /* Stabs debugging sections.  */
    .stab          0 : { *(.stab) }
    .stabstr       0 : { *(.stabstr) }
    .stab.excl     0 : { *(.stab.excl) }
    .stab.exclstr  0 : { *(.stab.exclstr) }
    .stab.index    0 : { *(.stab.index) }
    .stab.indexstr 0 : { *(.stab.indexstr) }
    .comment       0 : { *(.comment) }
    /* DWARF debug sections.
     * Symbols in the DWARF debugging sections are relative to the beginning
     * of the section so we begin them at 0.  */
    /* DWARF 1 */
    .debug          0 : { *(.debug) }
    .line           0 : { *(.line) }
    /* GNU DWARF 1 extensions */
    .debug_srcinfo  0 : { *(.debug_srcinfo) }
    .debug_sfnames  0 : { *(.debug_sfnames) }
    /* DWARF 1.1 and DWARF 2 */
    .debug_aranges  0 : { *(.debug_aranges) }
    .debug_pubnames 0 : { *(.debug_pubnames) }
    /* DWARF 2 */
    .debug_info     0 : { *(.debug_info .gnu.linkonce.wi.*) }
    .debug_abbrev   0 : { *(.debug_abbrev) }
    .debug_line     0 : { *(.debug_line) }
    .debug_frame    0 : { *(.debug_frame) }
    .debug_str      0 : { *(.debug_str) }
    .debug_loc      0 : { *(.debug_loc) }
    .debug_macinfo  0 : { *(.debug_macinfo) }
    /* SGI/MIPS DWARF 2 extensions */
    .debug_weaknames 0 : { *(.debug_weaknames) }
    .debug_funcnames 0 : { *(.debug_funcnames) }
    .debug_typenames 0 : { *(.debug_typenames) }
    .debug_varnames  0 : { *(.debug_varnames) }
}

该文件是GCC编译的链接脚本,根据《GD32F407xx_Datasheet_Rev2.1》可知,GD32F407VKT6的flash大小为3072KB,SRAM大小为192KB,因此CODE和DATA 的LENGTH分别设置为3072KB和192KB,其他芯片类似,但其实地址都是一样的。

(3) 修改E:\RT_Thread\GD32_BSP\rt_thread_code\bsp\gd32f103\gd32f103vet6\board/linker_scripts/link.sct
该文件是MDK的连接脚本,根据《GD32F407xx_Datasheet_Rev2.1》手册,因此需要将 LR_IROM1 和 ER_IROM1 的参数设置为 0x00300000;RAM 的大小为192k,因此需要将 RW_IRAM1 的参数设置为 0x00030000。

; *************************************************************
; *** Scatter-Loading Description File generated by uVision ***
; *************************************************************

LR_IROM1 0x08000000 0x00080000  {    ; load region size_region
  ER_IROM1 0x08000000 0x00080000  {  ; load address = execution address
   *.o (RESET, +First)
   *(InRoot$$Sections)
   .ANY (+RO)
  }
  RW_IRAM1 0x20000000 0x00010000  {  ; RW data
   .ANY (+RW +ZI)
  }
}

(4) 修改E:\RT_Thread\GD32_BSP\rt_thread_code\bsp\gd32f103\gd32f103vet6\board/board.h文件
修改后内容如下:

/*
 * Copyright (c) 2006-2021, RT-Thread Development Team
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Change Logs:
 * Date           Author       Notes
 * 2021-12-18     BruceOu      first implementation
 */
#ifndef __BOARD_H__
#define __BOARD_H__

#include "gd32f10x.h"
#include "drv_usart.h"
#include "drv_gpio.h"

#include "gd32f10x_exti.h"

#define EXT_SDRAM_BEGIN    (0xC0000000U) /* the begining address of external SDRAM */
#define EXT_SDRAM_END      (EXT_SDRAM_BEGIN + (32U * 1024 * 1024)) /* the end address of external SDRAM */

// <o> Internal SRAM memory size[Kbytes] <8-48>
//  <i>Default: 48
#ifdef __ICCARM__
// Use *.icf ram symbal, to avoid hardcode.
extern char __ICFEDIT_region_RAM_end__;
#define GD32_SRAM_END          &__ICFEDIT_region_RAM_end__
#else
#define GD32_SRAM_SIZE         64
#define GD32_SRAM_END          (0x20000000 + GD32_SRAM_SIZE * 1024)
#endif

#ifdef __CC_ARM
extern int Image$$RW_IRAM1$$ZI$$Limit;
#define HEAP_BEGIN    (&Image$$RW_IRAM1$$ZI$$Limit)
#elif __ICCARM__
#pragma section="HEAP"
#define HEAP_BEGIN    (__segment_end("HEAP"))
#else
extern int __bss_end;
#define HEAP_BEGIN    (&__bss_end)
#endif

#define HEAP_END          GD32_SRAM_END

#endif

值得注意的是,不同的编译器规定的堆栈内存的起始地址 HEAP_BEGIN 和结束地址 HEAP_END。这里 HEAP_BEGIN 和 HEAP_END 的值需要和前面的链接脚本是一致的,需要结合实际去修改。
(5) 修改E:\RT_Thread\GD32_BSP\rt_thread_code\bsp\gd32f103\gd32f103vet6\board/board.c文件

修改后的文件如下:

/*
 * Copyright (c) 2006-2021, RT-Thread Development Team
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Change Logs:
 * Date           Author       Notes
 * 2021-12-18     BruceOu      first implementation
 */
#include <stdint.h>
#include <rthw.h>
#include <rtthread.h>
#include <board.h>

/**
  * @brief  This function is executed in case of error occurrence.
  * @param  None
  * @retval None
  */
void Error_Handler(void)
{
    /* USER CODE BEGIN Error_Handler */
    /* User can add his own implementation to report the HAL error return state */
    while (1)
    {
    }
    /* USER CODE END Error_Handler */
}

/** System Clock Configuration
*/
void SystemClock_Config(void)
{
    SysTick_Config(SystemCoreClock / RT_TICK_PER_SECOND);
    NVIC_SetPriority(SysTick_IRQn, 0);
}

/**
 * This is the timer interrupt service routine.
 *
 */
void SysTick_Handler(void)
{
    /* enter interrupt */
    rt_interrupt_enter();

    rt_tick_increase();

    /* leave interrupt */
    rt_interrupt_leave();
}

/**
 * This function will initial GD32 board.
 */
void rt_hw_board_init()
{
    /* NVIC Configuration */
#define NVIC_VTOR_MASK              0x3FFFFF80
#ifdef  VECT_TAB_RAM
    /* Set the Vector Table base location at 0x10000000 */
    SCB->VTOR  = (0x10000000 & NVIC_VTOR_MASK);
#else  /* VECT_TAB_FLASH  */
    /* Set the Vector Table base location at 0x08000000 */
    SCB->VTOR  = (0x08000000 & NVIC_VTOR_MASK);
#endif

    SystemClock_Config();

#ifdef RT_USING_COMPONENTS_INIT
    rt_components_board_init();
#endif

#ifdef RT_USING_CONSOLE
    rt_console_set_device(RT_CONSOLE_DEVICE_NAME);
#endif

#ifdef BSP_USING_SDRAM
    rt_system_heap_init((void *)EXT_SDRAM_BEGIN, (void *)EXT_SDRAM_END);
#else
    rt_system_heap_init((void *)HEAP_BEGIN, (void *)HEAP_END);
#endif
}

/*@}*/

该文件重点关注的就是SystemClock_Config配置,SystemCoreClock的定义在system_gd32f1xx.c中定义的.
(6) 修改E:\RT_Thread\GD32_BSP\rt_thread_code\bsp\gd32f103\gd32f103vet6\board/Kconfig文件
修改后内容如下:

menu "Hardware Drivers Config"

config SOC_SERIES_GD32F10x
    bool
    default y
    
config SOC_GD32103V
    bool
    select SOC_SERIES_GD32F10x
    select RT_USING_COMPONENTS_INIT
    select RT_USING_USER_MAIN
    default y
    
menu "Onboard Peripheral Drivers"

endmenu

menu "On-chip Peripheral Drivers"

    config BSP_USING_GPIO
        bool "Enable GPIO"
        select RT_USING_PIN
        default y

    menuconfig BSP_USING_UART
        bool "Enable UART"
        default y
        select RT_USING_SERIAL
        if BSP_USING_UART
            config BSP_USING_UART0
                bool "Enable UART0"
                default n

            config BSP_UART0_RX_USING_DMA
                bool "Enable UART0 RX DMA"
                depends on BSP_USING_UART0 
                select RT_SERIAL_USING_DMA
                default n

            config BSP_USING_UART1
                bool "Enable UART1"
                default y

            config BSP_UART1_RX_USING_DMA
                bool "Enable UART1 RX DMA"
                depends on BSP_USING_UART1 
                select RT_SERIAL_USING_DMA
                default n

            config BSP_USING_UART2
                bool "Enable UART2"
                default n

            config BSP_UART2_RX_USING_DMA
                bool "Enable UART2 RX DMA"
                depends on BSP_USING_UART2 
                select RT_SERIAL_USING_DMA
                default n

            config BSP_USING_UART3
                bool "Enable UART3"
                default n

            config BSP_UART3_RX_USING_DMA
                bool "Enable UART3 RX DMA"
                depends on BSP_USING_UART3 
                select RT_SERIAL_USING_DMA
                default n

            config BSP_USING_UART4
                bool "Enable UART4"
                default n

            config BSP_UART4_RX_USING_DMA
                bool "Enable UART4 RX DMA"
                depends on BSP_USING_UART4 
                select RT_SERIAL_USING_DMA
                default n
        endif

    menuconfig BSP_USING_SPI
        bool "Enable SPI BUS"
        default n
        select RT_USING_SPI
        if BSP_USING_SPI
            config BSP_USING_SPI1
                bool "Enable SPI1 BUS"
                default n

            config BSP_SPI1_TX_USING_DMA
                bool "Enable SPI1 TX DMA"
                depends on BSP_USING_SPI1
                default n
                
            config BSP_SPI1_RX_USING_DMA
                bool "Enable SPI1 RX DMA"
                depends on BSP_USING_SPI1
                select BSP_SPI1_TX_USING_DMA
                default n
        endif

    menuconfig BSP_USING_I2C1
        bool "Enable I2C1 BUS (software simulation)"
        default n
        select RT_USING_I2C
        select RT_USING_I2C_BITOPS
        select RT_USING_PIN
        if BSP_USING_I2C1
            config BSP_I2C1_SCL_PIN
                int "i2c1 scl pin number"
                range 1 216
                default 24
            config BSP_I2C1_SDA_PIN
                int "I2C1 sda pin number"
                range 1 216
                default 25
        endif

    config BSP_USING_WDT
        bool "Enable Watchdog Timer"
        select RT_USING_WDT
        default n

    config BSP_USING_RTC
        bool "Enable Internal RTC"
        select RT_USING_RTC
        default n

    menuconfig BSP_USING_HWTIMER
        bool "Enable hwtimer"
        default n
        select RT_USING_HWTIMER
        if BSP_USING_HWTIMER
            config BSP_USING_HWTIMER0
                bool "using hwtimer0"
                default n
            config BSP_USING_HWTIMER1
                bool "using hwtimer1"
                default n
            config BSP_USING_HWTIMER2
                bool "using hwtimer2"
                default n
            config BSP_USING_HWTIMER3
                bool "using hwtimer3"
                default n
            config BSP_USING_HWTIMER4
                bool "using hwtimer4"
                default n
            config BSP_USING_HWTIMER5
                bool "using hwtimer5"
                default n
            config BSP_USING_HWTIMER6
                bool "using hwtimer6"
                default n
            config BSP_USING_HWTIMER7
                bool "using hwtimer7"
                default n
        endif

    menuconfig BSP_USING_ADC
        bool "Enable ADC"
        default n
        select RT_USING_ADC
        if BSP_USING_ADC
            config BSP_USING_ADC0
                bool "using adc0"
                default n
            config BSP_USING_ADC1
                bool "using adc1"
                default n
        endif
    source "../libraries/gd32_drivers/Kconfig"

endmenu

menu "Board extended module Drivers"

endmenu

endmenu

这个文件就是配置板子驱动的,这里可根据实际需求添加。
(7) 修改E:\RT_Thread\GD32_BSP\rt_thread_code\bsp\gd32f103\gd32f103vet6\board/SConscript文件

修改后内容如下:

import os
import rtconfig
from building import *

Import('SDK_LIB')

cwd = GetCurrentDir()

# add general drivers
src = Split('''
board.c
''')

path =  [cwd]

startup_path_prefix = SDK_LIB

if rtconfig.PLATFORM == 'gcc':
    src += [startup_path_prefix + '/GD32F10x_Firmware_Library/CMSIS/GD/GD32F10x/Source/GCC/startup_gd32f10x_hd.s']
elif rtconfig.PLATFORM in ['armcc', 'armclang']:
    src += [startup_path_prefix + '/GD32F10x_Firmware_Library/CMSIS/GD/GD32F10x/Source/ARM/startup_gd32f10x_hd.s']
elif rtconfig.CROSS_TOOL == 'iar':
    src += [startup_path_prefix + '/GD32F10x_Firmware_Library/CMSIS/GD/GD32F10x/Source/IAR/startup_gd32f10x_hd.s']
    
CPPDEFINES = ['GD32F10X_HD']
group = DefineGroup('Drivers', src, depend = [''], CPPPATH = path, CPPDEFINES = CPPDEFINES)

Return('group')



cwd = GetCurrentDir()

# add general drivers
src = Split('''
board.c
''')

path =  [cwd]

startup_path_prefix = SDK_LIB

if rtconfig.CROSS_TOOL == 'gcc':
    src += [startup_path_prefix + '/GD32F4xx_HAL/CMSIS/GD/GD32F4xx/Source/GCC/startup_gd32f4xx.S']
elif rtconfig.CROSS_TOOL == 'keil':
    src += [startup_path_prefix + '/GD32F4xx_HAL/CMSIS/GD/GD32F4xx/Source/ARM/startup_gd32f4xx.s']
elif rtconfig.CROSS_TOOL == 'iar':
    src += [startup_path_prefix + '/GD32F4xx_HAL/CMSIS/GD/GD32F4xx/Source/IAR/startup_gd32f4xx.s']
    
CPPDEFINES = ['GD32F407xx']
group = DefineGroup('Drivers', src, depend = [''], CPPPATH = path, CPPDEFINES = CPPDEFINES)

Return('group')

该文件主要添加board文件夹的.c文件和头文件路径。另外根据开发环境选择相应的汇编文件,和前面的libraries的SConscript语法是一样,文件的结构都是类似的,这里就没有注释了。

到这里,基本所有的依赖脚本都配置完成了,接下来将通过menuconfig配置工程。
6.menuconfig配置
87de6d2428e1551f89d59c096f9018ce.png

剩下的笔者参考:https://club.rt-thread.org/ask/article/dcb4e9b8f7ebc7b3.html
同时文章结构也采用·BruceOu 博主的文章结构,在这里对原文章博主表示感谢。
对@乐乐爱学习 学长表示感谢,哈哈哈,学长的话如同涛涛江水,络绎不绝。一位优秀的全栈工程师@乐乐爱学习
72c38b31fc18a93193ecce4e56caddf6.png.webp

Gitee:https://gitee.com/zhaodhajhdjahwd/gd32-bsp

推荐阅读
关注数
8072
内容数
181
小而美的物联网操作系统,经过14年的累积发展,RT-Thread 已经拥有一个国内最大的嵌入式开源社区,同时被广泛应用于能源、车载、医疗、消费电子等多个行业,累积装机量超过4亿台,成为国人自主开发、国内最成熟稳定和装机量最大的开源 RTOS。
目录
极术微信服务号
关注极术微信号
实时接收点赞提醒和评论通知
安谋科技学堂公众号
关注安谋科技学堂
实时获取安谋科技及 Arm 教学资源
安谋科技招聘公众号
关注安谋科技招聘
实时获取安谋科技中国职位信息