Init
This commit is contained in:
commit
da6593b70a
|
|
@ -0,0 +1,202 @@
|
|||
#include "Clock.h"
|
||||
|
||||
|
||||
/* ################################################################################## */
|
||||
/* ################################### Type define ################################## */
|
||||
|
||||
/* PCBA external oscillator value, these macro is user defined. */
|
||||
/* FOSC/SOSC clock need to manually configuration according to PCBA XTAL value
|
||||
* in SOSC/FOSc configuration.
|
||||
* Current default value is the XTAL value on EVB board. */
|
||||
|
||||
|
||||
/* ################################################################################## */
|
||||
/* ########################### Local Prototype Functions ############################ */
|
||||
static void Bsp_SCG_Init(void);
|
||||
|
||||
static void Bsp_PCC_Init(void);
|
||||
|
||||
/* ################################################################################## */
|
||||
/* ################################ Local Functions ################################# */
|
||||
|
||||
|
||||
/**
|
||||
* @brief Local SCG initial
|
||||
*
|
||||
*/
|
||||
|
||||
// Ядро процессора: 240 МГц
|
||||
// Системная шина: 120 МГц
|
||||
// Медленная периферия: 120 МГц
|
||||
// PLL0/PLL1: 240 МГц
|
||||
// FOSC: 24 МГц
|
||||
// SIRC: 12 МГц
|
||||
|
||||
static void Bsp_SCG_Init(void) {
|
||||
|
||||
SCG_Deinit();
|
||||
|
||||
/* Enable FOSC, frequency is 24M, DIVH=DIV1(24M), DIVM=DIV1(24M), DIVL=DIV2(12M)*/
|
||||
// FOSC - Внешний кварцевый генератор (Базовый источник 24 МГц)
|
||||
SCG_FoscType tFoscStruct =
|
||||
{
|
||||
.bLock = false,
|
||||
.bCm = false,
|
||||
.bCmre = false,
|
||||
.bSten = false,
|
||||
.bBypass = false,
|
||||
.eDivH = SCG_ASYNCCLOCKDIV_BY1,
|
||||
.eDivM = SCG_ASYNCCLOCKDIV_BY1,
|
||||
.eDivL = SCG_ASYNCCLOCKDIV_BY2,
|
||||
};
|
||||
SCG_EnableFOSC(&tFoscStruct);
|
||||
|
||||
/* Enable PLL0, frequency is 240M, DIVH=DIV2(120M), DIVM=DIV2(120M), DIVL=DIV4(60M), src=FOSC*/
|
||||
/* The value of multiplier factor(FOSC/u8Prediv) between 2 ~ 4 is better*/
|
||||
|
||||
// FOSC = 24 МГц
|
||||
// После предделителя: 24 МГц / (11 + 1) = 24 МГц / 12 = 2 МГц
|
||||
// После умножения: 2 МГц × (239 + 1) = 2 МГц × 240 = 480 МГц
|
||||
// После постделителя: 480 МГц / 2 = 240 МГц
|
||||
|
||||
SCG_PllType tPll0Struct =
|
||||
{
|
||||
.bLock = false,
|
||||
.bCm = false,
|
||||
.bCmre = false,
|
||||
.bSten = false,
|
||||
.eDivH = SCG_ASYNCCLOCKDIV_BY2,
|
||||
.eDivM = SCG_ASYNCCLOCKDIV_BY2,
|
||||
.eDivL = SCG_ASYNCCLOCKDIV_BY4,
|
||||
.u8Prediv = 11U,
|
||||
.ePstDiv = SCG_PLLPSTDIV_BY2,
|
||||
.u16Mult = 239U,
|
||||
.eSrc = SCG_PLLSOURCE_FOSC
|
||||
};
|
||||
SCG_EnablePLL(SCG_PLL0, &tPll0Struct);
|
||||
|
||||
/* Enable PLL1, frequency is 240M, DIVH=DIV2(120M), DIVM=DIV2(120M), DIVL=DIV4(60M), src=FOSC*/
|
||||
/* The value of multiplier factor(FOSC/u8Prediv) between 2 ~ 4 is better*/
|
||||
|
||||
// Аналогична PLL0, также 240 МГц
|
||||
// Обычно используется для периферии
|
||||
|
||||
SCG_PllType tPll1Struct =
|
||||
{
|
||||
.bLock = false,
|
||||
.bCm = false,
|
||||
.bCmre = false,
|
||||
.bSten = false,
|
||||
.eDivH = SCG_ASYNCCLOCKDIV_BY2,
|
||||
.eDivM = SCG_ASYNCCLOCKDIV_BY2,
|
||||
.eDivL = SCG_ASYNCCLOCKDIV_BY4,
|
||||
.u8Prediv = 11U,
|
||||
.ePstDiv = SCG_PLLPSTDIV_BY2,
|
||||
.u16Mult = 239U,
|
||||
.eSrc = SCG_PLLSOURCE_FOSC
|
||||
};
|
||||
SCG_EnablePLL(SCG_PLL1, &tPll1Struct);
|
||||
|
||||
/* Enable SIRC DIV, DIVH=DIV1(12M), DIVM=DIV1(12M), DIVL=DIV2(6M) */
|
||||
// Резервный источник тактирования
|
||||
// Меньшая точность, но быстрый запуск
|
||||
|
||||
SCG_SircType tSircStruct =
|
||||
{
|
||||
.bLock = false,
|
||||
.bCm = false,
|
||||
.bTrEn = false,
|
||||
.bLpen = false,
|
||||
.bSten = false,
|
||||
.eDivH = SCG_ASYNCCLOCKDIV_BY1,
|
||||
.eDivM = SCG_ASYNCCLOCKDIV_BY1,
|
||||
.eDivL = SCG_ASYNCCLOCKDIV_BY2,
|
||||
.u8TrimSrc = 0U
|
||||
};
|
||||
SCG_SetSIRC(&tSircStruct);
|
||||
|
||||
/* Set core clock source from PLL0, DIV_CORE=DIV1(240M), DIV_BUS=DIV2(120M), DIV_SLOW=DIV4(60M)*/
|
||||
// Системное тактирование
|
||||
|
||||
//.eSrc = PLL0, // Источник - PLL0 (240 МГц)
|
||||
//.eDivCore = DIV1, // Ядро: 240 МГц
|
||||
//.eDivBus = DIV2, // Шина: 120 МГц
|
||||
//.eDivSlow = DIV2 // Медленная периферия: 120 МГц
|
||||
|
||||
SCG_ClockCtrlType tClockStruct =
|
||||
{
|
||||
.bSysClkMonitor = false,
|
||||
.eSrc = SCG_CLOCK_SRC_PLL0,
|
||||
.eDivSlow = SCG_CLOCK_DIV_BY2,
|
||||
.eDivBus = SCG_CLOCK_DIV_BY2,
|
||||
.eDivCore = SCG_CLOCK_DIV_BY1
|
||||
};
|
||||
SCG_SetClkCtrl(&tClockStruct);
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Local PCC Initial
|
||||
*
|
||||
*/
|
||||
static void Bsp_PCC_Init(void) {
|
||||
PCC_CtrlType bSP_PCC_Config;
|
||||
|
||||
// UART 1 (DBG)
|
||||
bSP_PCC_Config.eClockName = PCC_CLK_FCUART1;
|
||||
bSP_PCC_Config.bEn = true;
|
||||
bSP_PCC_Config.eClkSrc = PCC_CLKGATE_SRC_FOSCDIV;
|
||||
bSP_PCC_Config.eDivider = PCC_CLK_UNINVOLVED;
|
||||
|
||||
PCC_SetPcc(&bSP_PCC_Config);
|
||||
|
||||
// DMA 0
|
||||
bSP_PCC_Config.eClockName = PCC_CLK_DMA0;
|
||||
bSP_PCC_Config.bEn = true;
|
||||
bSP_PCC_Config.eClkSrc = PCC_CLKGATE_SRC_FOSCDIV;
|
||||
bSP_PCC_Config.eDivider = PCC_CLK_UNINVOLVED;
|
||||
|
||||
PCC_SetPcc(&bSP_PCC_Config);
|
||||
|
||||
// DMAMUX 0
|
||||
bSP_PCC_Config.eClockName = PCC_CLK_DMAMUX0;
|
||||
bSP_PCC_Config.bEn = true;
|
||||
bSP_PCC_Config.eClkSrc = PCC_CLKGATE_SRC_FOSCDIV;
|
||||
bSP_PCC_Config.eDivider = PCC_CLK_UNINVOLVED;
|
||||
|
||||
PCC_SetPcc(&bSP_PCC_Config);
|
||||
|
||||
// PCC_CLK_WKU0
|
||||
bSP_PCC_Config.eClockName = PCC_CLK_WKU0;
|
||||
bSP_PCC_Config.bEn = true;
|
||||
bSP_PCC_Config.eClkSrc = PCC_CLKGATE_UNINVOLVED;
|
||||
bSP_PCC_Config.eDivider = PCC_CLK_UNINVOLVED;
|
||||
|
||||
PCC_SetPcc(&bSP_PCC_Config);
|
||||
}
|
||||
|
||||
/* ################################################################################## */
|
||||
/* ################################# Global Functions ############################### */
|
||||
|
||||
|
||||
/**
|
||||
* @brief General Clock Initial
|
||||
*
|
||||
*/
|
||||
void Bsp_CLOCK_Init(void) {
|
||||
CSC0_ClkoutType tCSCClkOutCfg = {0};
|
||||
|
||||
/* Configure CSC(clock out configuration) */
|
||||
tCSCClkOutCfg.bEnable = true;
|
||||
tCSCClkOutCfg.eClkOutSrc = CSC0_CLKOUT_BUS_CLK;
|
||||
tCSCClkOutCfg.eDivider = CSC0_CLKOUT_DIV_BY4;
|
||||
|
||||
SCG_Deinit();
|
||||
Bsp_SCG_Init();
|
||||
// Bsp_PCC_Init();
|
||||
|
||||
/* Set clock out */
|
||||
SCG_SetClkOut(SCG_CLOCKOUT_SRC_FOSC);
|
||||
CSC0_SetClockOut(&tCSCClkOutCfg, false);
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,20 @@
|
|||
#ifndef INCLUDE_BSP_CLOCK_H_
|
||||
#define INCLUDE_BSP_CLOCK_H_
|
||||
|
||||
#include "fc7xxx_driver_fcuart.h"
|
||||
#include "fc7xxx_driver_pcc.h"
|
||||
#include "fc7xxx_driver_port.h"
|
||||
#include "fc7xxx_driver_scg.h"
|
||||
#include "fc7xxx_driver_gpio.h"
|
||||
#include "fc7xxx_driver_dma.h"
|
||||
#include "fc7xxx_driver_csc.h"
|
||||
#include "interrupt_manager.h"
|
||||
#include "fc7xxx_driver_systick.h"
|
||||
|
||||
/**
|
||||
* @brief General Clock Initial
|
||||
*
|
||||
*/
|
||||
void Bsp_CLOCK_Init(void);
|
||||
|
||||
#endif /* INCLUDE_BSP_CLOCK_H_ */
|
||||
|
|
@ -0,0 +1,239 @@
|
|||
/* Entry Point */
|
||||
ENTRY(Reset_Handler)
|
||||
|
||||
|
||||
M_VECTOR_RAM_SIZE = 0x0400;
|
||||
|
||||
_BootloaderSize = 64K;
|
||||
_BootloaderBegin = 0x01000000; /* BANK1 */
|
||||
|
||||
_FirmwareSize = 704K;
|
||||
_MetadataSize = 256;
|
||||
_FirmwareSize_CALIB = 256K;
|
||||
|
||||
_FirmwareMainBegin = _BootloaderBegin + _BootloaderSize;
|
||||
_FirmwareMetaBegin = _FirmwareMainBegin + _FirmwareSize - _MetadataSize;
|
||||
_FirmwareCalibBegin = _FirmwareMainBegin + _FirmwareSize;
|
||||
_FirmwareMetaCalibBegin = _FirmwareCalibBegin + _FirmwareSize_CALIB - _MetadataSize;
|
||||
|
||||
_FirmwareRecoveryBegin = 0x01100000; /* BANK2 */
|
||||
_FirmwareRecoveryMetaBegin = _FirmwareRecoveryBegin + _FirmwareSize - _MetadataSize;
|
||||
_FirmwareRecoveryCalibBegin = _FirmwareRecoveryBegin + _FirmwareSize;
|
||||
_FirmwareRecoveryMetaCalibBegin = _FirmwareRecoveryCalibBegin + _FirmwareSize_CALIB - _MetadataSize;
|
||||
|
||||
/* Specify the memory areas */
|
||||
MEMORY
|
||||
{
|
||||
|
||||
ITCM (RW) : ORIGIN = 0x00000000, LENGTH = 0x00008000 /* 32KB */
|
||||
|
||||
SRAM0 (RW) : ORIGIN = 0x21000000, LENGTH = 0x00010000 /* 64KB */
|
||||
SRAM1 (RW) : ORIGIN = 0x21010000, LENGTH = 0x00008000 /* 32KB */
|
||||
|
||||
PFLASH_BOOT (RW) : ORIGIN = _BootloaderBegin, LENGTH = _BootloaderSize /* 64K */
|
||||
PFLASH_BOOT_META (RW) : ORIGIN = _BootloaderBegin + _BootloaderSize - _MetadataSize, LENGTH = _MetadataSize
|
||||
|
||||
PFLASH_MAIN (RW) : ORIGIN = _FirmwareMainBegin, LENGTH = _FirmwareSize /* 704K */
|
||||
PFLASH_MAIN_META (RW) : ORIGIN = _FirmwareMetaBegin, LENGTH = _MetadataSize /* 256 */
|
||||
PFLASH_CALIB (RW) : ORIGIN = _FirmwareCalibBegin, LENGTH = _FirmwareSize_CALIB /* 256K */
|
||||
PFLASH_CALIB_META (RW) : ORIGIN = _FirmwareMetaCalibBegin, LENGTH = _MetadataSize /* 256 */
|
||||
|
||||
PFLASH_R_MAIN (RW) : ORIGIN = _FirmwareRecoveryBegin, LENGTH = _FirmwareSize /* 704K */
|
||||
PFLASH_R_MAIN_META (RW) : ORIGIN = _FirmwareRecoveryMetaBegin, LENGTH = _MetadataSize /* 256 */
|
||||
PFLASH_R_CALIB (RW) : ORIGIN = _FirmwareRecoveryCalibBegin, LENGTH = _FirmwareSize_CALIB /* 192K */
|
||||
PFLASH_R_CALIB_META (RW) : ORIGIN = _FirmwareRecoveryMetaCalibBegin, LENGTH = _FirmwareSize_CALIB /* 256 */
|
||||
|
||||
|
||||
DFLASH (RW) : ORIGIN = 0x04000000, LENGTH = 0x00020000 /* 128KB */
|
||||
|
||||
NVR0 (RW) : ORIGIN = 0x04400000, LENGTH = 0x00004000 /* 16KB */
|
||||
NVR1 (RW) : ORIGIN = 0x04408000, LENGTH = 0x00004000 /* 16KB */
|
||||
NVR2 (RW) : ORIGIN = 0x04410000, LENGTH = 0x00002000 /* 8KB */
|
||||
|
||||
/* DTCM */
|
||||
DTCM (RW) : ORIGIN = 0x20000000, LENGTH = 0x0001FA00 /* 128K - 0x600 */
|
||||
DTCM_STACK (RW) : ORIGIN = 0x2001FA00, LENGTH = 0x00000600 /* 0x600 */
|
||||
|
||||
}
|
||||
|
||||
/* Define output sections */
|
||||
SECTIONS
|
||||
{
|
||||
|
||||
/* The program code and other data goes into internal flash */
|
||||
.text :
|
||||
{
|
||||
. = ALIGN(1024); /* VTOR must be align to 1K */
|
||||
__vector_table = .;
|
||||
__interrupts_start__ = .;
|
||||
. = ALIGN(4);
|
||||
KEEP(*(.isr_vector))
|
||||
__interrupts_end__ = .;
|
||||
. = ALIGN(4);
|
||||
|
||||
*(.text) /* .text sections (code) */
|
||||
*(.text*) /* .text* sections (code) */
|
||||
*(.rodata) /* .rodata sections (constants, strings, etc.) */
|
||||
*(.rodata*) /* .rodata* sections (constants, strings, etc.) */
|
||||
*(.init) /* section used in crti.o files */
|
||||
*(.fini) /* section used in crti.o files */
|
||||
*(.eh_frame) /* section used in crtbegin.o files */
|
||||
. = ALIGN(4);
|
||||
} > PFLASH_BOOT
|
||||
|
||||
.meta_boot : SUBALIGN(1)
|
||||
{
|
||||
__ram_boot_meta_start = .;
|
||||
|
||||
KEEP(*(.meta_fw_name_size))
|
||||
KEEP(*(.meta_fw_name))
|
||||
|
||||
KEEP(*(.meta_internal_hw_year))
|
||||
KEEP(*(.meta_internal_hw_month))
|
||||
KEEP(*(.meta_internal_hw_day))
|
||||
KEEP(*(.meta_internal_hw_rev))
|
||||
|
||||
KEEP(*(.meta_internal_sw_year))
|
||||
KEEP(*(.meta_internal_sw_month))
|
||||
KEEP(*(.meta_internal_sw_day))
|
||||
KEEP(*(.meta_internal_sw_rev))
|
||||
|
||||
KEEP(*(.meta_finger_module))
|
||||
KEEP(*(.meta_finger_tester_serial))
|
||||
KEEP(*(.meta_finger_year))
|
||||
KEEP(*(.meta_finger_month))
|
||||
KEEP(*(.meta_finger_day))
|
||||
|
||||
. = ALIGN(256);
|
||||
|
||||
} > PFLASH_BOOT_META
|
||||
|
||||
.data :
|
||||
{
|
||||
__ram_data_start = .;
|
||||
. = ALIGN(4);
|
||||
*(.data*)
|
||||
|
||||
. = ALIGN(4);
|
||||
/* preinit data */
|
||||
PROVIDE_HIDDEN (__preinit_array_start = .);
|
||||
KEEP(*(.preinit_array))
|
||||
PROVIDE_HIDDEN (__preinit_array_end = .);
|
||||
|
||||
. = ALIGN(4);
|
||||
/* init data */
|
||||
PROVIDE_HIDDEN (__init_array_start = .);
|
||||
KEEP(*(SORT(.init_array.*)))
|
||||
KEEP(*(.init_array))
|
||||
PROVIDE_HIDDEN (__init_array_end = .);
|
||||
|
||||
|
||||
. = ALIGN(4);
|
||||
/* finit data */
|
||||
PROVIDE_HIDDEN (__fini_array_start = .);
|
||||
KEEP(*(SORT(.fini_array.*)))
|
||||
KEEP(*(.fini_array))
|
||||
PROVIDE_HIDDEN (__fini_array_end = .);
|
||||
|
||||
. = ALIGN(4);
|
||||
/* All data end */
|
||||
__ram_data_end = .;
|
||||
|
||||
} > DTCM AT > PFLASH_BOOT
|
||||
|
||||
/* Non-cache RAM section with data initialization */
|
||||
.ncache_data :
|
||||
{
|
||||
. = ALIGN(4);
|
||||
__ram_ncache_data_start = .;
|
||||
*(.nocacheable_data*)
|
||||
__ram_ncache_data_end = .;
|
||||
. = ALIGN(4);
|
||||
} > SRAM1 AT > PFLASH_BOOT
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
.cals_data(NOLOAD) :
|
||||
{
|
||||
__itcm_start = .;
|
||||
|
||||
/* Начало .caldata */
|
||||
__caldata_start = .;
|
||||
KEEP(*(.caldata))
|
||||
. = ALIGN(4);
|
||||
|
||||
/* Проверяем и резервируем 20K */
|
||||
__caldata_actual_size = . - __caldata_start;
|
||||
ASSERT(__caldata_actual_size <= 20K, "Ошибка: .caldata превышает 20K!");
|
||||
|
||||
/* Если данные меньше 20K, резервируем оставшееся пространство */
|
||||
. = __caldata_start + 20K;
|
||||
|
||||
KEEP(*(.nvmdata))
|
||||
|
||||
__itcm_end = .;
|
||||
. = ALIGN(4);
|
||||
} > ITCM
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
.xcp_data(NOLOAD) :
|
||||
{
|
||||
__xcp_start = .;
|
||||
KEEP(*(.xcpdata))
|
||||
__xcp_end = .;
|
||||
. = ALIGN(4);
|
||||
} > SRAM0
|
||||
|
||||
.cals_text :
|
||||
{
|
||||
KEEP(*(.caltext))
|
||||
. = ALIGN(4);
|
||||
} > DFLASH
|
||||
|
||||
.bss(NOLOAD) :
|
||||
{
|
||||
. = ALIGN(4);
|
||||
__bss_start = .;
|
||||
|
||||
*Model_actuator.c.obj(.bss .bss*)
|
||||
. = ALIGN(4);
|
||||
|
||||
*(.bss*)
|
||||
*(COMMON)
|
||||
__bss_end = .;
|
||||
. = ALIGN(4);
|
||||
} > DTCM
|
||||
|
||||
/* Non-cache RAM section with no initialization */
|
||||
.ncache_bss(NOLOAD) :
|
||||
{
|
||||
. = ALIGN(4);
|
||||
__ncache_bss_start = .;
|
||||
*(.nocacheable_bss*)
|
||||
__ncache_bss_end = .;
|
||||
. = ALIGN(4);
|
||||
} > SRAM1
|
||||
|
||||
__HeapBegin = ORIGIN(DTCM_STACK);
|
||||
__HeapLimit = ORIGIN(DTCM_STACK) + 0x200 - 8;
|
||||
|
||||
__StackLimit = ORIGIN(DTCM_STACK)+0x200;
|
||||
__StackTop = ORIGIN(DTCM_STACK) + LENGTH(DTCM_STACK) - 8;
|
||||
|
||||
__rom_data_start = LOADADDR(.data);
|
||||
__rom_ncache_data_start = LOADADDR(.ncache_data);
|
||||
|
||||
}
|
||||
|
||||
|
|
@ -0,0 +1,177 @@
|
|||
/* USER CODE BEGIN Header */
|
||||
/*
|
||||
* FreeRTOS Kernel V10.3.1
|
||||
* Portion Copyright (C) 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
|
||||
* Portion Copyright (C) 2019 StMicroelectronics, Inc. All Rights Reserved.
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy of
|
||||
* this software and associated documentation files (the "Software"), to deal in
|
||||
* the Software without restriction, including without limitation the rights to
|
||||
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
|
||||
* the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
* subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in all
|
||||
* copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
|
||||
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
|
||||
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
|
||||
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
|
||||
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*
|
||||
* http://www.FreeRTOS.org
|
||||
* http://aws.amazon.com/freertos
|
||||
*
|
||||
* 1 tab == 4 spaces!
|
||||
*/
|
||||
/* USER CODE END Header */
|
||||
|
||||
#ifndef FREERTOS_CONFIG_H
|
||||
#define FREERTOS_CONFIG_H
|
||||
|
||||
/*-----------------------------------------------------------
|
||||
* Application specific definitions.
|
||||
*
|
||||
* These definitions should be adjusted for your particular hardware and
|
||||
* application requirements.
|
||||
*
|
||||
* These parameters and more are described within the 'configuration' section of the
|
||||
* FreeRTOS API documentation available on the FreeRTOS.org web site.
|
||||
*
|
||||
* See http://www.freertos.org/a00110.html
|
||||
*----------------------------------------------------------*/
|
||||
|
||||
/* USER CODE BEGIN Includes */
|
||||
/* Section where include file can be added */
|
||||
/* USER CODE END Includes */
|
||||
|
||||
/* Ensure definitions are only used by the compiler, and not by the assembler. */
|
||||
#if defined(__ICCARM__) || defined(__CC_ARM) || defined(__GNUC__)
|
||||
|
||||
#include <stdint.h>
|
||||
|
||||
extern uint32_t SystemCoreClock;
|
||||
#endif
|
||||
|
||||
//#ifndef CMSIS_device_header
|
||||
//#define CMSIS_device_header "niietcm4.h"
|
||||
//#define CMSIS_device_header "at32f435_437.h"
|
||||
//#endif /* CMSIS_device_header */
|
||||
//#include "niietcm4.h"
|
||||
//#include "at32f435_437.h"
|
||||
|
||||
#define configCHECK_FOR_STACK_OVERFLOW 1
|
||||
|
||||
#define configENABLE_FPU 1
|
||||
#define configENABLE_MPU 0
|
||||
|
||||
#define configUSE_PREEMPTION 1
|
||||
#define configSUPPORT_STATIC_ALLOCATION 1
|
||||
#define configSUPPORT_DYNAMIC_ALLOCATION 1
|
||||
#define configUSE_IDLE_HOOK 0
|
||||
#define configUSE_TICK_HOOK 0
|
||||
#define configCPU_CLOCK_HZ ( 240000000 )
|
||||
#define configTICK_RATE_HZ ((TickType_t)1000)
|
||||
#define configMAX_PRIORITIES ( 56 )
|
||||
#define configMINIMAL_STACK_SIZE ((uint16_t)64)
|
||||
#define configTOTAL_HEAP_SIZE ((size_t)16 * 1024)
|
||||
#define configMAX_TASK_NAME_LEN ( 16 )
|
||||
#define configUSE_TRACE_FACILITY 1
|
||||
#define configUSE_16_BIT_TICKS 0
|
||||
#define configUSE_MUTEXES 1
|
||||
#define configQUEUE_REGISTRY_SIZE 8
|
||||
#define configUSE_RECURSIVE_MUTEXES 1
|
||||
#define configUSE_COUNTING_SEMAPHORES 1
|
||||
#define configUSE_PORT_OPTIMISED_TASK_SELECTION 0
|
||||
/* USER CODE BEGIN MESSAGE_BUFFER_LENGTH_TYPE */
|
||||
/* Defaults to size_t for backward compatibility, but can be changed
|
||||
if lengths will always be less than the number of bytes in a size_t. */
|
||||
#define configMESSAGE_BUFFER_LENGTH_TYPE size_t
|
||||
/* USER CODE END MESSAGE_BUFFER_LENGTH_TYPE */
|
||||
|
||||
/* Co-routine definitions. */
|
||||
#define configUSE_CO_ROUTINES 0
|
||||
#define configMAX_CO_ROUTINE_PRIORITIES ( 2 )
|
||||
|
||||
/* Software timer definitions. */
|
||||
#define configUSE_TIMERS 1
|
||||
#define configTIMER_TASK_PRIORITY ( 2 )
|
||||
#define configTIMER_QUEUE_LENGTH 10
|
||||
#define configTIMER_TASK_STACK_DEPTH 128
|
||||
|
||||
/* CMSIS-RTOS V2 flags */
|
||||
#define configUSE_OS2_THREAD_SUSPEND_RESUME 1
|
||||
#define configUSE_OS2_THREAD_ENUMERATE 1
|
||||
#define configUSE_OS2_EVENTFLAGS_FROM_ISR 1
|
||||
#define configUSE_OS2_THREAD_FLAGS 1
|
||||
#define configUSE_OS2_TIMER 1
|
||||
#define configUSE_OS2_MUTEX 1
|
||||
|
||||
/* Set the following definitions to 1 to include the API function, or zero
|
||||
to exclude the API function. */
|
||||
#define INCLUDE_vTaskPrioritySet 1
|
||||
#define INCLUDE_uxTaskPriorityGet 1
|
||||
#define INCLUDE_vTaskDelete 1
|
||||
#define INCLUDE_vTaskCleanUpResources 0
|
||||
#define INCLUDE_vTaskSuspend 1
|
||||
#define INCLUDE_vTaskDelayUntil 1
|
||||
#define INCLUDE_vTaskDelay 1
|
||||
#define INCLUDE_xTaskGetSchedulerState 1
|
||||
#define INCLUDE_xTimerPendFunctionCall 1
|
||||
#define INCLUDE_xQueueGetMutexHolder 1
|
||||
#define INCLUDE_uxTaskGetStackHighWaterMark 1
|
||||
#define INCLUDE_xTaskGetCurrentTaskHandle 1
|
||||
#define INCLUDE_eTaskGetState 1
|
||||
|
||||
/*
|
||||
* The CMSIS-RTOS V2 FreeRTOS wrapper is dependent on the heap implementation used
|
||||
* by the application thus the correct define need to be enabled below
|
||||
*/
|
||||
#define USE_FreeRTOS_HEAP_4
|
||||
|
||||
/* Cortex-M specific definitions. */
|
||||
#ifdef __NVIC_PRIO_BITS
|
||||
/* __BVIC_PRIO_BITS will be specified when CMSIS is being used. */
|
||||
#define configPRIO_BITS __NVIC_PRIO_BITS
|
||||
#else
|
||||
#define configPRIO_BITS 3U
|
||||
#endif
|
||||
|
||||
/* The lowest interrupt priority that can be used in a call to a "set priority"
|
||||
function. */
|
||||
#define configLIBRARY_LOWEST_INTERRUPT_PRIORITY 7 // 15
|
||||
|
||||
/* The highest interrupt priority that can be used by any interrupt service
|
||||
routine that makes calls to interrupt safe FreeRTOS API functions. DO NOT CALL
|
||||
INTERRUPT SAFE FREERTOS API FUNCTIONS FROM ANY INTERRUPT THAT HAS A HIGHER
|
||||
PRIORITY THAN THIS! (higher priorities are lower numeric values. */
|
||||
#define configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY 1 // 5
|
||||
|
||||
/* Interrupt priorities used by the kernel port layer itself. These are generic
|
||||
to all Cortex-M ports, and do not rely on any particular library functions. */
|
||||
#define configKERNEL_INTERRUPT_PRIORITY ( configLIBRARY_LOWEST_INTERRUPT_PRIORITY << (8 - configPRIO_BITS) )
|
||||
/* !!!! configMAX_SYSCALL_INTERRUPT_PRIORITY must not be set to zero !!!!
|
||||
See http://www.FreeRTOS.org/RTOS-Cortex-M3-M4.html. */
|
||||
#define configMAX_SYSCALL_INTERRUPT_PRIORITY ( configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY << (8 - configPRIO_BITS) )
|
||||
|
||||
/* Normal assert() semantics without relying on the provision of an assert.h
|
||||
header file. */
|
||||
/* USER CODE BEGIN 1 */
|
||||
|
||||
//#define configASSERT(x) if ((x) == 0) {nvic_system_reset();}
|
||||
#define configASSERT(x) if ((x) == 0) {taskDISABLE_INTERRUPTS(); for( ;; );}
|
||||
/* USER CODE END 1 */
|
||||
|
||||
/* Definitions that map the FreeRTOS port interrupt handlers to their CMSIS
|
||||
standard names. */
|
||||
#define vPortSVCHandler SVC_Handler
|
||||
#define xPortPendSVHandler PendSV_Handler
|
||||
|
||||
/* IMPORTANT: After 10.3.1 update, Systick_Handler comes from NVIC (if SYS timebase = systick), otherwise from cmsis_os2.c */
|
||||
|
||||
#define USE_CUSTOM_SYSTICK_HANDLER_IMPLEMENTATION 0
|
||||
|
||||
|
||||
#endif /* FREERTOS_CONFIG_H */
|
||||
|
|
@ -0,0 +1,26 @@
|
|||
#include "Systick.h"
|
||||
|
||||
uint32_t g_tickcounter;
|
||||
|
||||
void SysTick_Handler(void);
|
||||
|
||||
void Bsp_Systick_Init(void)
|
||||
{
|
||||
uint32_t freq = 0U;
|
||||
g_tickcounter = 0U;
|
||||
|
||||
freq = SCG_GetScgClockFreq(SCG_CORE_CLK);
|
||||
Core_SysTick_Config(freq / 1000U);
|
||||
|
||||
Core_SysTick_Enable();
|
||||
}
|
||||
|
||||
uint32_t Bsp_Systick_GetSystick(void)
|
||||
{
|
||||
return g_tickcounter;
|
||||
}
|
||||
|
||||
void SysTick_Handler(void)
|
||||
{
|
||||
g_tickcounter++;
|
||||
}
|
||||
|
|
@ -0,0 +1,14 @@
|
|||
/*
|
||||
* Systick.h
|
||||
*
|
||||
*/
|
||||
|
||||
#ifndef INCLUDE_EVB_SYSTICK_H_
|
||||
#define INCLUDE_EVB_SYSTICK_H_
|
||||
#include "Clock.h"
|
||||
|
||||
void Bsp_Systick_Init(void);
|
||||
uint32_t Bsp_Systick_GetSystick(void);
|
||||
|
||||
#endif /* INCLUDE_EVB_SYSTICK_H_ */
|
||||
|
||||
|
|
@ -0,0 +1,45 @@
|
|||
//
|
||||
// Created by cfif on 22.09.2025.
|
||||
//
|
||||
#include "Clock.h"
|
||||
#include "Systick.h"
|
||||
#include "GpioPin.h"
|
||||
|
||||
void DefaultISR(void) {
|
||||
asm("nop");
|
||||
}
|
||||
|
||||
int main(void) {
|
||||
bool bExitFlag = true;
|
||||
uint32_t u32SystickCnt = 0U;
|
||||
uint32_t u32PreviousCnt = 0U;
|
||||
|
||||
Bsp_CLOCK_Init();
|
||||
Bsp_Systick_Init();
|
||||
|
||||
tGpioPin LED_G = vInitGpioPinPull(GPIO_D, PORT_PIN_2, GPIO_OUT, GPIO_PIN_NOREVERSE, GPIO_HIGH, GPIO_PUSH_PULL, PORT_PULL_DOWN);
|
||||
|
||||
tGpioPin ShutOffFront_EN = vInitGpioPinPull(GPIO_A, PORT_PIN_20, GPIO_OUT, GPIO_PIN_NOREVERSE, GPIO_HIGH, GPIO_PUSH_PULL, PORT_PULL_UP);
|
||||
bool isLED = false;
|
||||
|
||||
while (bExitFlag) {
|
||||
u32SystickCnt = Bsp_Systick_GetSystick();
|
||||
|
||||
if (((u32SystickCnt % 1000U) == 0U) && (u32SystickCnt != u32PreviousCnt)) {
|
||||
u32PreviousCnt = u32SystickCnt;
|
||||
|
||||
if (isLED) {
|
||||
isLED = false;
|
||||
GpioPinSet(&LED_G, 1);
|
||||
GpioPinSet(&ShutOffFront_EN, 1);
|
||||
} else {
|
||||
isLED = true;
|
||||
GpioPinSet(&LED_G, 0);
|
||||
GpioPinSet(&ShutOffFront_EN, 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return 0;
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,15 @@
|
|||
{
|
||||
"cmake": {
|
||||
"inc_dirs": [
|
||||
"./",
|
||||
"./clock",
|
||||
"./int"
|
||||
],
|
||||
"srcs": [
|
||||
"./**.c",
|
||||
"./clock/**.c",
|
||||
"./int/**.c",
|
||||
"./**.s"
|
||||
]
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,480 @@
|
|||
/* ================================================================================================== */
|
||||
/* BRIEF : Startup - Startup file for FC7240 */
|
||||
/* PERIPHERAL : N/A */
|
||||
/* PLATFORM : Flagchip FC7240 */
|
||||
/* SOFTWARE VERSION : 0.1.0 */
|
||||
/* VENDOR : Flagchip */
|
||||
/* Copyright 2024 Flagchip Semiconductors Co., Ltd. */
|
||||
/* All Rights Reserved. */
|
||||
/* ================================================================================================== */
|
||||
/* ================================================================================================== */
|
||||
/* Revision History */
|
||||
/* Version Date Initials CR# Descriptions */
|
||||
/* --------- ---------- ------------- ---------- --------------- */
|
||||
/* 0.1.0 2024-01-12 qxw0030 N/A Initial version */
|
||||
/* ================================================================================================== */
|
||||
|
||||
.syntax unified
|
||||
.arch armv7-m
|
||||
|
||||
.extern __StackTop
|
||||
.extern __StackLimit
|
||||
|
||||
/* ================================================================================================== */
|
||||
/* Set vector table */
|
||||
/* ================================================================================================== */
|
||||
.section .isr_vector
|
||||
.align 2
|
||||
.globl __isr_vector
|
||||
|
||||
/* vector table */
|
||||
__isr_vector:
|
||||
.long __StackTop /* Top of Stack */
|
||||
.long Reset_Handler /* Reset Handler */
|
||||
.long NMI_Handler /* NMI Handler */
|
||||
.long HardFault_Handler /* Hard Fault Handler */
|
||||
.long MemManage_Handler /* MPU Fault Handler */
|
||||
.long BusFault_Handler /* Bus Fault Handler */
|
||||
.long UsageFault_Handler /* Usage Fault Handler */
|
||||
.long 0 /* Reserved */
|
||||
.long 0 /* Reserved */
|
||||
.long 0 /* Reserved */
|
||||
.long 0 /* Reserved */
|
||||
.long SVC_Handler /* SVCall Handler */
|
||||
.long DebugMon_Handler /* Debug Monitor Handler */
|
||||
.long 0 /* Reserved */
|
||||
.long PendSV_Handler /* PendSV Handler */
|
||||
.long SysTick_Handler /* SysTick Handler */
|
||||
|
||||
/* External Interrupts*/
|
||||
.long DMA0_IRQHandler /* DMA channel 0 transfer complete */
|
||||
.long DMA1_IRQHandler /* DMA channel 1 transfer complete */
|
||||
.long DMA2_IRQHandler /* DMA channel 2 transfer complete */
|
||||
.long DMA3_IRQHandler /* DMA channel 3 transfer complete */
|
||||
.long DMA4_IRQHandler /* DMA channel 4 transfer complete */
|
||||
.long DMA5_IRQHandler /* DMA channel 5 transfer complete */
|
||||
.long DMA6_IRQHandler /* DMA channel 6 transfer complete */
|
||||
.long DMA7_IRQHandler /* DMA channel 7 transfer complete */
|
||||
.long DMA8_IRQHandler /* DMA channel 8 transfer complete */
|
||||
.long DMA9_IRQHandler /* DMA channel 9 transfer complete */
|
||||
.long DMA10_IRQHandler /* DMA channel 10 transfer complete */
|
||||
.long DMA11_IRQHandler /* DMA channel 11 transfer complete */
|
||||
.long DMA12_IRQHandler /* DMA channel 12 transfer complete */
|
||||
.long DMA13_IRQHandler /* DMA channel 13 transfer complete */
|
||||
.long DMA14_IRQHandler /* DMA channel 14 transfer complete */
|
||||
.long DMA15_IRQHandler /* DMA channel 15 transfer complete */
|
||||
.long DMA_Error_IRQHandler /* DMA error interrupt channels 0-31 */
|
||||
.long CPM_IRQHandler /* FPU etc. interrupt */
|
||||
.long FC_IRQHandler /* FC Command complete */
|
||||
.long PMC_IRQHandler /* HVD/LVD etc. interrupt */
|
||||
.long TMU_IRQHandler /* Temperature Monitor Unit interrupt */
|
||||
.long WDOG0_IRQHandler /* interrupt request out before wdg reset out */
|
||||
.long WDOG1_IRQHandler /* interrupt request out before wdg reset out */
|
||||
.long FCSMU0_IRQHandler /* Fault Control and Safety Manage Unit */
|
||||
.long STCU0_IRQHandler /* Safety Control Unit interrupt */
|
||||
.long ERM_fault_IRQHandler /* ERM single/double bit error correction */
|
||||
.long MAM0_IRQHandler /* Matrix Access Monitor interrupt */
|
||||
.long RGM_Pre_IRQHandler /* RGM pre-reset Interrupt */
|
||||
.long INTM0_IRQHandler /* INTM alarm interrupt */
|
||||
.long ISM0_IRQHandler /* ISM0 interrupt */
|
||||
.long MB_IRQHandler /* Mail Box interrupt */
|
||||
.long SCG_IRQHandler /* SCG bus interrupt request */
|
||||
.long CMU0_IRQHandler /* CMU0 interrupt */
|
||||
.long CMU1_IRQHandler /* CMU1 interrupt */
|
||||
.long CMU2_IRQHandler /* CMU2 interrupt */
|
||||
.long CMU3_IRQHandler /* CMU3 interrupt */
|
||||
.long CMU4_IRQHandler /* CMU4 interrupt */
|
||||
.long TSTMP0_IRQHandler /* TimerStamp0 interrupt */
|
||||
.long TSTMP1_IRQHandler /* TimerStamp1 interrupt */
|
||||
.long CORDIC_IRQHandler /* CORDIC Accelerator interrupt */
|
||||
.long HSM0_IRQHandler /* HSM error interrupt */
|
||||
.long FCPIT0_IRQHandler /* FCPIT0 interrupt */
|
||||
.long RTC_IRQHandler /* RTC alarm or seconds interrupt */
|
||||
.long AONTIMER_IRQHandler /* AONTIMER interrupt request */
|
||||
.long SWI_IRQHandler /* Software interrupt */
|
||||
.long FREQM_IRQHandler /* FREQM interrupt */
|
||||
.long ADC0_IRQHandler /* ADC0 interrupt request. */
|
||||
.long ADC1_IRQHandler /* ADC1 interrupt request. */
|
||||
.long PTIMER0_IRQHandler /* PTIMER0 interrupt */
|
||||
.long PTIMER1_IRQHandler /* PTIMER1 interrupt */
|
||||
.long CAN0_IRQHandler /* CAN0 Interrupt */
|
||||
.long CAN1_IRQHandler /* CAN1 Interrupt */
|
||||
.long CAN2_IRQHandler /* CAN2 Interrupt */
|
||||
.long CAN3_IRQHandler /* CAN3 Interrupt */
|
||||
.long FCIIC0_IRQHandler /* FCIIC0 Interrupt */
|
||||
.long FCIIC1_IRQHandler /* FCIIC1 Interrupt */
|
||||
.long FCSPI0_IRQHandler /* FCSPI0 Interrupt */
|
||||
.long FCSPI1_IRQHandler /* FCSPI1 Interrupt */
|
||||
.long FCSPI2_IRQHandler /* FCSPI2 Interrupt */
|
||||
.long FCSPI3_IRQHandler /* FCSPI3 Interrupt */
|
||||
.long FCSPI4_IRQHandler /* FCSPI4 Interrupt */
|
||||
.long FCSPI5_IRQHandler /* FCSPI5 Interrupt */
|
||||
.long FCUART0_RxTx_IRQHandler /* FCUART0 Transmit / Receive Interrupt */
|
||||
.long FCUART1_RxTx_IRQHandler /* FCUART1 Transmit / Receive Interrupt */
|
||||
.long FCUART2_RxTx_IRQHandler /* FCUART2 Transmit / Receive Interrupt */
|
||||
.long FCUART3_RxTx_IRQHandler /* FCUART3 Transmit / Receive Interrupt */
|
||||
.long FCUART4_RxTx_IRQHandler /* FCUART4 Transmit / Receive Interrupt */
|
||||
.long FCUART5_RxTx_IRQHandler /* FCUART5 Transmit / Receive Interrupt */
|
||||
.long FCUART6_RxTx_IRQHandler /* FCUART6 Transmit / Receive Interrupt */
|
||||
.long FCUART7_RxTx_IRQHandler /* FCUART7 Transmit / Receive Interrupt */
|
||||
.long FTU0_IRQHandler /* FTU0 all source interrupt */
|
||||
.long FTU1_IRQHandler /* FTU1 all source interrupt */
|
||||
.long FTU2_IRQHandler /* FTU2 all source interrupt */
|
||||
.long FTU3_IRQHandler /* FTU3 all source interrupt */
|
||||
.long FTU4_IRQHandler /* FTU4 all source interrupt */
|
||||
.long FTU5_IRQHandler /* FTU5 all source interrupt */
|
||||
.long FTU6_IRQHandler /* FTU6 all source interrupt */
|
||||
.long FTU7_IRQHandler /* FTU7 all source interrupt */
|
||||
.long CMP0_IRQHandler /* CMP0 interrupt request */
|
||||
.long CMP1_IRQHandler /* CMP1 interrupt request */
|
||||
.long PORTA_IRQHandler /* Port A pin detect interrupt */
|
||||
.long PORTB_IRQHandler /* Port B pin detect interrupt */
|
||||
.long PORTC_IRQHandler /* Port C pin detect interrupt */
|
||||
.long PORTD_IRQHandler /* Port D pin detect interrupt */
|
||||
.long PORTE_IRQHandler /* Port E pin detect interrupt */
|
||||
.long MSC0_IRQHandler /* MSC interrupt */
|
||||
.long SENT0_IRQHandler /* SENT all interrupt (fast or slow) */
|
||||
.long TPU0_CH0_7_IRQHandler /* TPU0 CH0-7 interrupt */
|
||||
.long TPU0_CH8_15_IRQHandler /* TPU0 CH8-15 interrupt */
|
||||
.long TPU0_CH16_23_IRQHandler /* TPU0 CH16-23 interrupt */
|
||||
.long TPU0_CH24_31_IRQHandler /* TPU0 CH24-31 interrupt */
|
||||
.long HSM0_CRYPTO_IRQHandler /* HSM crypto interrupt */
|
||||
.long DefaultISR /* 108 */
|
||||
.long DefaultISR /* 109 */
|
||||
.long DefaultISR /* 110 */
|
||||
.long DefaultISR /* 111 */
|
||||
.long DefaultISR /* 112 */
|
||||
.long DefaultISR /* 113 */
|
||||
.long DefaultISR /* 114 */
|
||||
.long DefaultISR /* 115 */
|
||||
.long DefaultISR /* 116 */
|
||||
.long DefaultISR /* 117 */
|
||||
.long DefaultISR /* 118 */
|
||||
.long DefaultISR /* 119 */
|
||||
.long DefaultISR /* 120 */
|
||||
.long DefaultISR /* 121 */
|
||||
.long DefaultISR /* 122 */
|
||||
.long DefaultISR /* 123 */
|
||||
.long DefaultISR /* 124 */
|
||||
.long DefaultISR /* 125 */
|
||||
.long DefaultISR /* 126 */
|
||||
.long DefaultISR /* 127 */
|
||||
.long DefaultISR /* 128 */
|
||||
.long DefaultISR /* 129 */
|
||||
.long DefaultISR /* 130 */
|
||||
.long DefaultISR /* 131 */
|
||||
.long DefaultISR /* 132 */
|
||||
.long DefaultISR /* 133 */
|
||||
.long DefaultISR /* 134 */
|
||||
.long DefaultISR /* 135 */
|
||||
.long DefaultISR /* 136 */
|
||||
.long DefaultISR /* 137 */
|
||||
.long DefaultISR /* 138 */
|
||||
.long DefaultISR /* 139 */
|
||||
.long DefaultISR /* 140 */
|
||||
.long DefaultISR /* 141 */
|
||||
.long DefaultISR /* 142 */
|
||||
.long DefaultISR /* 143 */
|
||||
.long DefaultISR /* 144 */
|
||||
.long DefaultISR /* 145 */
|
||||
.long DefaultISR /* 146 */
|
||||
.long DefaultISR /* 147 */
|
||||
.long DefaultISR /* 148 */
|
||||
.long DefaultISR /* 149 */
|
||||
.long DefaultISR /* 150 */
|
||||
.long DefaultISR /* 151 */
|
||||
.long DefaultISR /* 152 */
|
||||
.long DefaultISR /* 153 */
|
||||
.long DefaultISR /* 154 */
|
||||
.long DefaultISR /* 155 */
|
||||
.long DefaultISR /* 156 */
|
||||
.long DefaultISR /* 157 */
|
||||
.long DefaultISR /* 158 */
|
||||
.long DefaultISR /* 159 */
|
||||
.long DefaultISR /* 160 */
|
||||
.long DefaultISR /* 161 */
|
||||
.long DefaultISR /* 162 */
|
||||
.long DefaultISR /* 163 */
|
||||
.long DefaultISR /* 164 */
|
||||
.long DefaultISR /* 165 */
|
||||
.long DefaultISR /* 166 */
|
||||
.long DefaultISR /* 167 */
|
||||
.long DefaultISR /* 168 */
|
||||
.long DefaultISR /* 169 */
|
||||
.long DefaultISR /* 170 */
|
||||
.long DefaultISR /* 171 */
|
||||
.long DefaultISR /* 172 */
|
||||
.long DefaultISR /* 173 */
|
||||
.long DefaultISR /* 174 */
|
||||
.long DefaultISR /* 175 */
|
||||
.long DefaultISR /* 176 */
|
||||
.long DefaultISR /* 177 */
|
||||
.long DefaultISR /* 178 */
|
||||
.long DefaultISR /* 179 */
|
||||
.long DefaultISR /* 180 */
|
||||
.long DefaultISR /* 181 */
|
||||
.long DefaultISR /* 182 */
|
||||
.long DefaultISR /* 183 */
|
||||
.long DefaultISR /* 184 */
|
||||
.long DefaultISR /* 185 */
|
||||
.long DefaultISR /* 186 */
|
||||
.long DefaultISR /* 187 */
|
||||
.long DefaultISR /* 188 */
|
||||
.long DefaultISR /* 189 */
|
||||
.long DefaultISR /* 190 */
|
||||
.long DefaultISR /* 191 */
|
||||
.long DefaultISR /* 192 */
|
||||
.long DefaultISR /* 193 */
|
||||
.long DefaultISR /* 194 */
|
||||
.long DefaultISR /* 195 */
|
||||
.long DefaultISR /* 196 */
|
||||
.long DefaultISR /* 197 */
|
||||
.long DefaultISR /* 198 */
|
||||
.long DefaultISR /* 199 */
|
||||
.long DefaultISR /* 200 */
|
||||
.long DefaultISR /* 201 */
|
||||
.long DefaultISR /* 202 */
|
||||
.long DefaultISR /* 203 */
|
||||
.long DefaultISR /* 204 */
|
||||
.long DefaultISR /* 205 */
|
||||
.long DefaultISR /* 206 */
|
||||
.long DefaultISR /* 207 */
|
||||
.long DefaultISR /* 208 */
|
||||
.long DefaultISR /* 209 */
|
||||
.long DefaultISR /* 210 */
|
||||
.long DefaultISR /* 211 */
|
||||
.long DefaultISR /* 212 */
|
||||
.long DefaultISR /* 213 */
|
||||
.long DefaultISR /* 214 */
|
||||
.long DefaultISR /* 215 */
|
||||
.long DefaultISR /* 216 */
|
||||
.long DefaultISR /* 217 */
|
||||
.long DefaultISR /* 218 */
|
||||
.long DefaultISR /* 219 */
|
||||
.long DefaultISR /* 220 */
|
||||
.long DefaultISR /* 221 */
|
||||
.long DefaultISR /* 222 */
|
||||
.long DefaultISR /* 223 */
|
||||
.long DefaultISR /* 224 */
|
||||
.long DefaultISR /* 225 */
|
||||
.long DefaultISR /* 226 */
|
||||
.long DefaultISR /* 227 */
|
||||
.long DefaultISR /* 228 */
|
||||
.long DefaultISR /* 229 */
|
||||
.long DefaultISR /* 230 */
|
||||
.long DefaultISR /* 231 */
|
||||
.long DefaultISR /* 232 */
|
||||
.long DefaultISR /* 233 */
|
||||
.long DefaultISR /* 234 */
|
||||
.long DefaultISR /* 235 */
|
||||
.long DefaultISR /* 236 */
|
||||
.long DefaultISR /* 237 */
|
||||
.long DefaultISR /* 238 */
|
||||
.long DefaultISR /* 239 */
|
||||
.long DefaultISR /* 240 */
|
||||
.long DefaultISR /* 241 */
|
||||
.long DefaultISR /* 242 */
|
||||
.long DefaultISR /* 243 */
|
||||
.long DefaultISR /* 244 */
|
||||
.long DefaultISR /* 245 */
|
||||
.long DefaultISR /* 246 */
|
||||
.long DefaultISR /* 247 */
|
||||
.long DefaultISR /* 248 */
|
||||
.long DefaultISR /* 249 */
|
||||
.long DefaultISR /* 250 */
|
||||
.long DefaultISR /* 251 */
|
||||
.long DefaultISR /* 252 */
|
||||
.long DefaultISR /* 253 */
|
||||
.long DefaultISR /* 254 */
|
||||
.long 0xFFFFFFFF /* Reserved for user TRIM value */
|
||||
|
||||
.size __isr_vector, . - __isr_vector
|
||||
|
||||
|
||||
/**************************************************************/
|
||||
/************************ set other ***************************/
|
||||
.text
|
||||
.thumb
|
||||
|
||||
/* Reset Handler */
|
||||
|
||||
.thumb_func
|
||||
.align 2
|
||||
.globl Reset_Handler
|
||||
.weak Reset_Handler
|
||||
.type Reset_Handler, %function
|
||||
|
||||
Reset_Handler:
|
||||
cpsid i /* Mask interrupts */
|
||||
|
||||
/* Init the rest of the registers */
|
||||
ldr r1,=0
|
||||
ldr r2,=0
|
||||
ldr r3,=0
|
||||
ldr r4,=0
|
||||
ldr r5,=0
|
||||
ldr r6,=0
|
||||
ldr r7,=0
|
||||
mov r8,r7
|
||||
mov r9,r7
|
||||
mov r10,r7
|
||||
mov r11,r7
|
||||
mov r12,r7
|
||||
|
||||
ldr r0, =0xE000ED08
|
||||
ldr r1, =__vector_table
|
||||
str r1, [r0]
|
||||
|
||||
/* Initialize the stack pointer */
|
||||
ldr r0,=__StackTop
|
||||
mov sp,r0 ; sp=r13
|
||||
|
||||
/* Clear Stack */
|
||||
ldr r2, =__StackLimit
|
||||
ldr r4, =__StackTop
|
||||
movs r3, #0
|
||||
b LoopFillZero_STACK
|
||||
|
||||
FillZero_STACK:
|
||||
str r3, [r2]
|
||||
adds r2, r2, #4
|
||||
|
||||
LoopFillZero_STACK:
|
||||
cmp r2, r4
|
||||
bcc FillZero_STACK
|
||||
|
||||
/* System Initialization */
|
||||
ldr r0,=System_Init
|
||||
blx r0
|
||||
|
||||
/* Initialize .data and .bss sections */
|
||||
ldr r0,=Data_Init
|
||||
blx r0
|
||||
|
||||
cpsie i /* Unmask interrupts */
|
||||
bl main
|
||||
JumpToSelf:
|
||||
b JumpToSelf
|
||||
|
||||
.pool
|
||||
.size Reset_Handler, . - Reset_Handler
|
||||
|
||||
.align 1
|
||||
.thumb_func
|
||||
.weak DefaultISR
|
||||
.type DefaultISR, %function
|
||||
DefaultISR:
|
||||
b DefaultISR
|
||||
.size DefaultISR, . - DefaultISR
|
||||
|
||||
/* Macro to define default handlers. Default handler
|
||||
* will be weak symbol and just dead loops. They can be
|
||||
* overwritten by other handlers */
|
||||
.macro def_irq_handler handler_name
|
||||
.weak \handler_name
|
||||
.set \handler_name, DefaultISR
|
||||
.endm
|
||||
|
||||
/* Exception Handlers */
|
||||
def_irq_handler NMI_Handler
|
||||
def_irq_handler HardFault_Handler
|
||||
def_irq_handler MemManage_Handler
|
||||
def_irq_handler BusFault_Handler
|
||||
def_irq_handler UsageFault_Handler
|
||||
def_irq_handler SVC_Handler
|
||||
def_irq_handler DebugMon_Handler
|
||||
def_irq_handler PendSV_Handler
|
||||
def_irq_handler SysTick_Handler
|
||||
def_irq_handler DMA0_IRQHandler
|
||||
def_irq_handler DMA1_IRQHandler
|
||||
def_irq_handler DMA2_IRQHandler
|
||||
def_irq_handler DMA3_IRQHandler
|
||||
def_irq_handler DMA4_IRQHandler
|
||||
def_irq_handler DMA5_IRQHandler
|
||||
def_irq_handler DMA6_IRQHandler
|
||||
def_irq_handler DMA7_IRQHandler
|
||||
def_irq_handler DMA8_IRQHandler
|
||||
def_irq_handler DMA9_IRQHandler
|
||||
def_irq_handler DMA10_IRQHandler
|
||||
def_irq_handler DMA11_IRQHandler
|
||||
def_irq_handler DMA12_IRQHandler
|
||||
def_irq_handler DMA13_IRQHandler
|
||||
def_irq_handler DMA14_IRQHandler
|
||||
def_irq_handler DMA15_IRQHandler
|
||||
def_irq_handler DMA_Error_IRQHandler
|
||||
def_irq_handler CPM_IRQHandler
|
||||
def_irq_handler FC_IRQHandler
|
||||
def_irq_handler PMC_IRQHandler
|
||||
def_irq_handler TMU_IRQHandler
|
||||
def_irq_handler WDOG0_IRQHandler
|
||||
def_irq_handler WDOG1_IRQHandler
|
||||
def_irq_handler FCSMU0_IRQHandler
|
||||
def_irq_handler STCU0_IRQHandler
|
||||
def_irq_handler ERM_fault_IRQHandler
|
||||
def_irq_handler MAM0_IRQHandler
|
||||
def_irq_handler RGM_Pre_IRQHandler
|
||||
def_irq_handler INTM0_IRQHandler
|
||||
def_irq_handler ISM0_IRQHandler
|
||||
def_irq_handler MB_IRQHandler
|
||||
def_irq_handler SCG_IRQHandler
|
||||
def_irq_handler CMU0_IRQHandler
|
||||
def_irq_handler CMU1_IRQHandler
|
||||
def_irq_handler CMU2_IRQHandler
|
||||
def_irq_handler CMU3_IRQHandler
|
||||
def_irq_handler CMU4_IRQHandler
|
||||
def_irq_handler TSTMP0_IRQHandler
|
||||
def_irq_handler TSTMP1_IRQHandler
|
||||
def_irq_handler CORDIC_IRQHandler
|
||||
def_irq_handler HSM0_IRQHandler
|
||||
def_irq_handler FCPIT0_IRQHandler
|
||||
def_irq_handler RTC_IRQHandler
|
||||
def_irq_handler AONTIMER_IRQHandler
|
||||
def_irq_handler SWI_IRQHandler
|
||||
def_irq_handler FREQM_IRQHandler
|
||||
def_irq_handler ADC0_IRQHandler
|
||||
def_irq_handler ADC1_IRQHandler
|
||||
def_irq_handler PTIMER0_IRQHandler
|
||||
def_irq_handler PTIMER1_IRQHandler
|
||||
def_irq_handler CAN0_IRQHandler
|
||||
def_irq_handler CAN1_IRQHandler
|
||||
def_irq_handler CAN2_IRQHandler
|
||||
def_irq_handler CAN3_IRQHandler
|
||||
def_irq_handler FCIIC0_IRQHandler
|
||||
def_irq_handler FCIIC1_IRQHandler
|
||||
def_irq_handler FCSPI0_IRQHandler
|
||||
def_irq_handler FCSPI1_IRQHandler
|
||||
def_irq_handler FCSPI2_IRQHandler
|
||||
def_irq_handler FCSPI3_IRQHandler
|
||||
def_irq_handler FCSPI4_IRQHandler
|
||||
def_irq_handler FCSPI5_IRQHandler
|
||||
def_irq_handler FCUART0_RxTx_IRQHandler
|
||||
def_irq_handler FCUART1_RxTx_IRQHandler
|
||||
def_irq_handler FCUART2_RxTx_IRQHandler
|
||||
def_irq_handler FCUART3_RxTx_IRQHandler
|
||||
def_irq_handler FCUART4_RxTx_IRQHandler
|
||||
def_irq_handler FCUART5_RxTx_IRQHandler
|
||||
def_irq_handler FCUART6_RxTx_IRQHandler
|
||||
def_irq_handler FCUART7_RxTx_IRQHandler
|
||||
def_irq_handler FTU0_IRQHandler
|
||||
def_irq_handler FTU1_IRQHandler
|
||||
def_irq_handler FTU2_IRQHandler
|
||||
def_irq_handler FTU3_IRQHandler
|
||||
def_irq_handler FTU4_IRQHandler
|
||||
def_irq_handler FTU5_IRQHandler
|
||||
def_irq_handler FTU6_IRQHandler
|
||||
def_irq_handler FTU7_IRQHandler
|
||||
def_irq_handler CMP0_IRQHandler
|
||||
def_irq_handler CMP1_IRQHandler
|
||||
def_irq_handler PORTA_IRQHandler
|
||||
def_irq_handler PORTB_IRQHandler
|
||||
def_irq_handler PORTC_IRQHandler
|
||||
def_irq_handler PORTD_IRQHandler
|
||||
def_irq_handler PORTE_IRQHandler
|
||||
def_irq_handler MSC0_IRQHandler
|
||||
def_irq_handler SENT0_IRQHandler
|
||||
def_irq_handler TPU0_CH0_7_IRQHandler
|
||||
def_irq_handler TPU0_CH8_15_IRQHandler
|
||||
def_irq_handler TPU0_CH16_23_IRQHandler
|
||||
def_irq_handler TPU0_CH24_31_IRQHandler
|
||||
def_irq_handler HSM0_CRYPTO_IRQHandler
|
||||
.end
|
||||
|
|
@ -0,0 +1,75 @@
|
|||
#if (defined(__ICCARM__))
|
||||
|
||||
#elif defined(__ARMCC_VERSION)
|
||||
|
||||
#elif defined __GNUC__
|
||||
#include "sys/types.h"
|
||||
#include "sys/stat.h"
|
||||
#endif
|
||||
|
||||
static uint32_t s_u32Current_heap_end;
|
||||
|
||||
#if (defined(__ICCARM__))
|
||||
extern uint32_t __HeapBegin[1]; // Defined by the linker.
|
||||
extern uint32_t __HeapLimit[1]; // Defined by the linker.
|
||||
#elif defined __GNUC__
|
||||
extern uint32_t __HeapBegin[1]; // Defined by the linker.
|
||||
extern uint32_t __HeapLimit[1]; // Defined by the linker.
|
||||
#endif
|
||||
|
||||
|
||||
#if (defined(__ICCARM__))
|
||||
/**
|
||||
* TODO: something can be done to make sure the start address used in heap is defined heap start
|
||||
*/
|
||||
#elif defined(__ARMCC_VERSION)
|
||||
|
||||
#elif defined __GNUC__
|
||||
extern caddr_t _sbrk(int incr);
|
||||
|
||||
/**
|
||||
* \brief Replacement of C library of _sbrk
|
||||
*/
|
||||
caddr_t _sbrk(int incr)
|
||||
{
|
||||
if (s_u32Current_heap_end == 0U)
|
||||
{
|
||||
#if (defined(__ICCARM__))
|
||||
s_u32Current_heap_end = (uint32_t)__HeapBegin;
|
||||
#elif defined __GNUC__
|
||||
s_u32Current_heap_end = (uint32_t)__HeapBegin;
|
||||
#endif
|
||||
}
|
||||
|
||||
// Need to align heap to word boundary, else will get
|
||||
// hard faults on Cortex-M0. So we assume that heap starts on
|
||||
// word boundary, hence make sure we always add a multiple of
|
||||
// 4 to it.
|
||||
incr = (incr + 3) & (~3); // align value to 4
|
||||
#if (defined(__ICCARM__))
|
||||
if ( (s_u32Current_heap_end + incr) > (uint32_t)__HeapLimit )
|
||||
#elif defined __GNUC__
|
||||
if ( (s_u32Current_heap_end + incr) > (uint32_t)__HeapLimit )
|
||||
#endif
|
||||
{
|
||||
// Some of the libstdc++-v3 tests rely upon detecting
|
||||
// out of memory errors, so do not abort here.
|
||||
#if 0
|
||||
extern void abort(void);
|
||||
|
||||
_write(1, "_sbrk: Heap and stack collision\n", 32);
|
||||
|
||||
abort();
|
||||
#else
|
||||
return (caddr_t) - 1;
|
||||
#endif
|
||||
}
|
||||
else
|
||||
{
|
||||
s_u32Current_heap_end+= incr;
|
||||
}
|
||||
|
||||
return (caddr_t) s_u32Current_heap_end;
|
||||
}
|
||||
|
||||
#endif
|
||||
|
|
@ -0,0 +1,212 @@
|
|||
/**
|
||||
* @file system_init.c
|
||||
* @author Flagchip
|
||||
* @brief interrupt configuration
|
||||
* @version 0.1.0
|
||||
* @date 2024-01-12
|
||||
*
|
||||
* @copyright Copyright (c) 2024 Flagchip Semiconductors Co., Ltd.
|
||||
*
|
||||
*/
|
||||
|
||||
/* ********************************************************************************
|
||||
* Revision History:
|
||||
*
|
||||
* Version Date Author Descriptions
|
||||
* --------- ---------- ------------ ---------------
|
||||
* 0.1.0 2024-01-12 Flagchip038 First version for gcc, iar, keil, ghs data init
|
||||
******************************************************************************** */
|
||||
|
||||
|
||||
#include "system_init.h"
|
||||
#include "fc7xxx_driver_fpu.h"
|
||||
|
||||
static void data_clear(uint32_t u32StartAddr, uint32_t u32EndAddr);
|
||||
static void data_copy(uint32_t u32SourceAddr, uint32_t u32DestAddr, uint32_t u32DestEndAddr);
|
||||
|
||||
|
||||
#define REG_VAL(addr) (*(volatile uint32 *)(addr))
|
||||
#define REG_VAL_OFF(addr,offset) (*(volatile uint32 *)((addr)+(offset)))
|
||||
#define WDOG0_BASE_ADDR 0x40022000U
|
||||
#define WDOG1_BASE_ADDR 0x40433000U
|
||||
#define SMC_STANDBY_CFG_ADDR 0x40045010U
|
||||
#define SCM_BASE_ADDR 0x40072000U
|
||||
#define RGM_BASE_ADDR 0x40046000U
|
||||
#define PCC_STCU_ADDR 0x400241FCU
|
||||
#define STCU_BASE_ADDR 0x4007F000U
|
||||
|
||||
#define DWT_CYCCNT_ADDR 0xE0001004U
|
||||
#define DEMCR_ADDR 0xE000EDFCU
|
||||
|
||||
#define CPACR_ADDR 0xE000ED88U
|
||||
|
||||
static void wdog_disable(uint32 wdog_base)
|
||||
{
|
||||
uint32 u32ttt = 128;
|
||||
uint32 u32First = 1;
|
||||
/* if it is not first time configure wdog, unlock status only pending for 128 bus clock */
|
||||
do {
|
||||
/* check unlock active */
|
||||
if (0U == (0x800u & REG_VAL(wdog_base)))
|
||||
{
|
||||
/* if unlock statue turn to 0, means not first time configuring wdog */
|
||||
u32First = 0;
|
||||
break;
|
||||
}
|
||||
} while (u32ttt--);
|
||||
|
||||
if (u32First == 0U)
|
||||
{
|
||||
/* only unlock=0, reconfig=1, can unlock wdog*/
|
||||
|
||||
/* waiting reconfiguration successful */
|
||||
while (0U == (0x400u & REG_VAL(wdog_base)));
|
||||
|
||||
/* unlock wdog */
|
||||
REG_VAL_OFF(wdog_base, 4) = 0x08181982;
|
||||
/* waiting unlock active */
|
||||
while (0U == (0x800u & REG_VAL(wdog_base)));
|
||||
|
||||
}
|
||||
REG_VAL(wdog_base) = 0x2920;
|
||||
REG_VAL_OFF(wdog_base, 8) = 0xF000;
|
||||
/* waiting reconfiguration successful */
|
||||
while (0U == (0x400u & REG_VAL(wdog_base)));
|
||||
}
|
||||
|
||||
/**
|
||||
* \brief System Initialization
|
||||
*
|
||||
*/
|
||||
void System_Init(void)
|
||||
{
|
||||
// disable wdog 0
|
||||
*(volatile uint32 *)0x40022004 = 0x08181982;
|
||||
while (0U == (0x800u & *(volatile uint32 *)0x40022000));
|
||||
*(volatile uint32 *)0x40022000 = 0x2920;
|
||||
*(volatile uint32 *)0x40022008 = 0xF000;
|
||||
while (0U == (0x400u & *(volatile uint32 *)0x40022000));
|
||||
|
||||
// disable wdog 1
|
||||
*(volatile uint32 *)0x40433004 = 0x08181982;
|
||||
while (0U == (0x800u & *(volatile uint32 *)0x40433000));
|
||||
*(volatile uint32 *)0x40433000 = 0x2920;
|
||||
*(volatile uint32 *)0x40433008 = 0xF000;
|
||||
while (0U == (0x400u & *(volatile uint32 *)0x40433000));
|
||||
|
||||
#if ((__FPU_PRESENT == 1) && (__FPU_USED == 1))
|
||||
FPU_Enable(); // Enable FPU
|
||||
#endif
|
||||
}
|
||||
|
||||
void Data_Init(void)
|
||||
{
|
||||
#if defined (__ARMCC_VERSION) && (__ARMCC_VERSION >= 6010050)
|
||||
extern uint32_t Load$$RW_m_dtcm$$Base;
|
||||
extern uint32_t Image$$RW_m_dtcm$$Base;
|
||||
extern uint32_t Image$$RW_m_dtcm$$Limit;
|
||||
|
||||
extern uint32_t Image$$RW_m_dtcm$$ZI$$Limit;
|
||||
extern uint32_t Image$$RW_m_dtcm$$ZI$$Base;
|
||||
|
||||
extern uint32_t Image$$ARM_LIB_HEAP$$ZI$$Base;
|
||||
extern uint32_t Image$$ARM_LIB_HEAP$$ZI$$Limit;
|
||||
|
||||
/* data/bss/heap clear */
|
||||
data_clear((uint32_t)&Image$$RW_m_dtcm$$Base, (uint32_t)&Image$$RW_m_dtcm$$Limit);
|
||||
data_clear((uint32_t)&Image$$RW_m_dtcm$$ZI$$Base, (uint32_t)&Image$$RW_m_dtcm$$ZI$$Limit);
|
||||
data_clear((uint32_t)&Image$$ARM_LIB_HEAP$$ZI$$Base, (uint32_t)&Image$$ARM_LIB_HEAP$$ZI$$Limit);
|
||||
|
||||
/* data */
|
||||
data_copy((uint32_t)&Load$$RW_m_dtcm$$Base, (uint32_t)&Image$$RW_m_dtcm$$Base, (uint32_t)&Image$$RW_m_dtcm$$Limit);
|
||||
|
||||
#elif defined(__GNUC__) || defined(__ghs__)
|
||||
extern uint32 __rom_data_start[];
|
||||
extern uint32 __ram_data_start[];
|
||||
extern uint32 __ram_data_end[];
|
||||
extern uint32 __bss_start[];
|
||||
extern uint32 __bss_end[];
|
||||
extern uint32 __rom_ncache_data_start[];
|
||||
extern uint32 __ram_ncache_data_start[];
|
||||
extern uint32 __ram_ncache_data_end[];
|
||||
extern uint32 __ncache_bss_start[];
|
||||
extern uint32 __ncache_bss_end[];
|
||||
|
||||
extern uint32_t __itcm_start[];
|
||||
extern uint32_t __itcm_end[];
|
||||
|
||||
|
||||
extern uint32_t __xcp_start[];
|
||||
extern uint32_t __xcp_end[];
|
||||
|
||||
|
||||
/* data clear */
|
||||
data_clear((uint32_t)__ram_data_start, (uint32_t)__ram_data_end);
|
||||
data_clear((uint32_t)__bss_start, (uint32_t)__bss_end);
|
||||
// data_clear((uint32_t)__ram_ncache_data_start, (uint32_t)__ram_ncache_data_end);
|
||||
// data_clear((uint32_t)__ncache_bss_start, (uint32_t)__ncache_bss_end);
|
||||
|
||||
// data_clear((uint32_t)__itcm_start, (uint32_t)__itcm_end);
|
||||
// data_clear((uint32_t)__xcp_start, (uint32_t)__xcp_end);
|
||||
|
||||
/* data copy */
|
||||
data_copy((uint32_t)__rom_data_start, (uint32_t)__ram_data_start, (uint32_t)__ram_data_end);
|
||||
// data_copy((uint32_t)__rom_ncache_data_start, (uint32_t)__ram_ncache_data_start, (uint32_t)__ram_ncache_data_end);
|
||||
|
||||
#elif defined(__ICCARM__)
|
||||
#pragma section=".data"
|
||||
#pragma section=".data_init"
|
||||
#pragma section=".ncsram"
|
||||
#pragma section=".ncsram_init"
|
||||
#pragma section=".bss"
|
||||
#pragma section="RAM_VECTOR"
|
||||
#pragma section=".intvec"
|
||||
|
||||
data_clear((uint32_t)__section_begin(".bss"), (uint32_t)__section_end(".bss"));
|
||||
|
||||
data_copy((uint32_t)__section_begin(".data_init"), (uint32_t)__section_begin(".data"), (uint32_t)__section_end(".data"));
|
||||
|
||||
data_copy((uint32_t)__section_begin(".ncsram_init"), (uint32_t)__section_begin(".ncsram"), (uint32_t)__section_end(".ncsram"));
|
||||
|
||||
#endif
|
||||
}
|
||||
|
||||
/* to avoid ecc issue, FC7240 clear ram with 64bits once after power on reset */
|
||||
static void data_clear(uint32_t u32StartAddr, uint32_t u32EndAddr)
|
||||
{
|
||||
/* 64 bits align */
|
||||
uint32_t u32AlignStart = u32StartAddr & 0xFFFFFFF8;
|
||||
uint32_t u32AlignEnd = (u32EndAddr - u32AlignStart);
|
||||
volatile uint64_t *pData = (uint64_t *)u32AlignStart;
|
||||
|
||||
/* 32 word Align */
|
||||
uint32_t u32LeftCount = u32AlignEnd & 0x1Fu;
|
||||
u32AlignEnd = u32EndAddr - u32LeftCount;
|
||||
|
||||
while ((uint32_t)pData < u32AlignEnd)
|
||||
{
|
||||
*pData++ = 0u;
|
||||
*pData++ = 0u;
|
||||
*pData++ = 0u;
|
||||
*pData++ = 0u;
|
||||
}
|
||||
|
||||
while ((uint32_t)pData < u32EndAddr)
|
||||
{
|
||||
*pData++ = 0u;
|
||||
}
|
||||
}
|
||||
|
||||
static void data_copy(uint32_t u32SourceAddr, uint32_t u32DestAddr, uint32_t u32DestEndAddr)
|
||||
{
|
||||
uint32_t *pSource = (uint32_t *)u32SourceAddr;
|
||||
uint32_t *pDest = (uint32_t *)u32DestAddr;
|
||||
|
||||
while ((uint32_t)pDest < u32DestEndAddr)
|
||||
{
|
||||
*pDest = *pSource;
|
||||
pDest++;
|
||||
pSource++;
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -0,0 +1,32 @@
|
|||
/**
|
||||
* @file system_init.h
|
||||
* @author Flagchip
|
||||
* @brief interrupt configuration
|
||||
* @version 0.1.0
|
||||
* @date 2024-01-12
|
||||
*
|
||||
* @copyright Copyright (c) 2024 Flagchip Semiconductors Co., Ltd.
|
||||
*
|
||||
*/
|
||||
#if !defined(SYSTEM_INIT_H)
|
||||
#define SYSTEM_INIT_H
|
||||
|
||||
|
||||
#if defined(__cplusplus)
|
||||
extern "C" {
|
||||
#endif /* __cplusplus*/
|
||||
|
||||
|
||||
#include "device_header.h"
|
||||
|
||||
void System_Init(void);
|
||||
|
||||
void Data_Init(void);
|
||||
|
||||
#if defined(__cplusplus)
|
||||
}
|
||||
#endif /* __cplusplus*/
|
||||
|
||||
|
||||
|
||||
#endif /* SYSTEM_INIT_H */
|
||||
|
|
@ -0,0 +1,28 @@
|
|||
.cals_data(NOLOAD) :
|
||||
{
|
||||
__itcm_start = .;
|
||||
|
||||
/* Резервируем ровно 20K для .caldata */
|
||||
.caldata : {
|
||||
KEEP(*(.caldata))
|
||||
. = ALIGN(4);
|
||||
} > ITCM
|
||||
|
||||
/* Проверяем размер и заполняем до 20K */
|
||||
__caldata_end = .;
|
||||
__caldata_start = ADDR(.caldata);
|
||||
__caldata_size = SIZEOF(.caldata);
|
||||
|
||||
/* Если .caldata меньше 20K, добавляем пустое пространство */
|
||||
. = __caldata_start + 20K;
|
||||
|
||||
/* Проверяем, что не превысили размер */
|
||||
ASSERT((. - __caldata_start) >= 20K, "Зарезервировано менее 20K для .caldata");
|
||||
ASSERT(__caldata_size <= 20K, "Раздел .caldata превышает 20K!");
|
||||
|
||||
KEEP(*(.nvmdata))
|
||||
. = ALIGN(4);
|
||||
*Model_actuator.c.obj(.bss .bss*)
|
||||
__itcm_end = .;
|
||||
. = ALIGN(4);
|
||||
} > ITCM
|
||||
|
|
@ -0,0 +1,134 @@
|
|||
#-- Service --------------------------------------------------------------------
|
||||
SET(CMAKE_TOOLCHAIN_FILE ${CMAKE_SOURCE_DIR}/MODULES/CmakeConfig_GCC_CortexM7/gcc_cm7f.cmake)
|
||||
ENABLE_LANGUAGE(ASM)
|
||||
CMAKE_MINIMUM_REQUIRED(VERSION 3.8.0)
|
||||
|
||||
set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -O0")
|
||||
set(CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG} -O0")
|
||||
|
||||
IF (${CMAKE_SOURCE_DIR} STREQUAL ${CMAKE_BINARY_DIR})
|
||||
MESSAGE(
|
||||
FATAL_ERROR
|
||||
"In-source builds not allowed.
|
||||
Please make a new directory (called a build directory) and run CMake from there.
|
||||
You may need to remove CMakeCache.txt."
|
||||
)
|
||||
ENDIF ()
|
||||
|
||||
SET(CMAKE_EXPORT_COMPILE_COMMANDS ON)
|
||||
#-- Project config -------------------------------------------------------------
|
||||
PROJECT(HVAC_M7_CLIMATIC) # Project name
|
||||
|
||||
|
||||
SET(INTERNAL_HW_YEAR 0x26)
|
||||
SET(INTERNAL_HW_MONTH 0x02)
|
||||
SET(INTERNAL_HW_DAY 0x24)
|
||||
SET(INTERNAL_HW_REV 0x01)
|
||||
|
||||
SET(INTERNAL_SW_YEAR 0x26)
|
||||
SET(INTERNAL_SW_MONTH 0x02)
|
||||
SET(INTERNAL_SW_DAY 0x24)
|
||||
SET(INTERNAL_SW_REV 0x01)
|
||||
|
||||
SET(FINGER_MODULE 0x01)
|
||||
SET(FINGER_YEAR 0x26)
|
||||
SET(FINGER_MONTH 0x02)
|
||||
SET(FINGER_DAY 0x24)
|
||||
SET(FINGER_TESTER_SERIAL \"M\")
|
||||
|
||||
|
||||
SET(VECT_TAB_OFFSET "0x00000")
|
||||
|
||||
|
||||
|
||||
#-- Defines --------------------------------------------------------------------
|
||||
|
||||
|
||||
ADD_DEFINITIONS(-DINTERNAL_HW_YEAR=${INTERNAL_HW_YEAR})
|
||||
ADD_DEFINITIONS(-DINTERNAL_HW_MONTH=${INTERNAL_HW_MONTH})
|
||||
ADD_DEFINITIONS(-DINTERNAL_HW_DAY=${INTERNAL_HW_DAY})
|
||||
ADD_DEFINITIONS(-DINTERNAL_HW_REV=${INTERNAL_HW_REV})
|
||||
|
||||
ADD_DEFINITIONS(-DINTERNAL_SW_YEAR=${INTERNAL_SW_YEAR})
|
||||
ADD_DEFINITIONS(-DINTERNAL_SW_MONTH=${INTERNAL_SW_MONTH})
|
||||
ADD_DEFINITIONS(-DINTERNAL_SW_DAY=${INTERNAL_SW_DAY})
|
||||
ADD_DEFINITIONS(-DINTERNAL_SW_REV=${INTERNAL_SW_REV})
|
||||
|
||||
ADD_DEFINITIONS(-DFINGER_MODULE=${FINGER_MODULE})
|
||||
ADD_DEFINITIONS(-DFINGER_YEAR=${FINGER_YEAR})
|
||||
ADD_DEFINITIONS(-DFINGER_MONTH=${FINGER_MONTH})
|
||||
ADD_DEFINITIONS(-DFINGER_DAY=${FINGER_DAY})
|
||||
ADD_DEFINITIONS(-DFINGER_TESTER_SERIAL=${FINGER_TESTER_SERIAL})
|
||||
|
||||
ADD_DEFINITIONS(-DUSING_OS_FREERTOS)
|
||||
|
||||
ADD_DEFINITIONS(-DVERSION_SEDANL_Y=25)
|
||||
ADD_DEFINITIONS(-DVERSION_SEDANL_M=10)
|
||||
ADD_DEFINITIONS(-DVERSION_SEDANL_D=29)
|
||||
|
||||
ADD_DEFINITIONS(-DVERSION_SEDANH_Y=25)
|
||||
ADD_DEFINITIONS(-DVERSION_SEDANH_M=10)
|
||||
ADD_DEFINITIONS(-DVERSION_SEDANH_D=29)
|
||||
|
||||
ADD_DEFINITIONS(-DVERSION_LIMO_Y=25)
|
||||
ADD_DEFINITIONS(-DVERSION_LIMO_M=10)
|
||||
ADD_DEFINITIONS(-DVERSION_LIMO_D=29)
|
||||
|
||||
ADD_DEFINITIONS(-DVERSION_SUV_Y=25)
|
||||
ADD_DEFINITIONS(-DVERSION_SUV_M=10)
|
||||
ADD_DEFINITIONS(-DVERSION_SUV_D=29)
|
||||
|
||||
ADD_DEFINITIONS(-DVERSION_MPV_Y=25)
|
||||
ADD_DEFINITIONS(-DVERSION_MPV_M=10)
|
||||
ADD_DEFINITIONS(-DVERSION_MPV_D=29)
|
||||
|
||||
ADD_DEFINITIONS(-DVECT_TAB_OFFSET=${VECT_TAB_OFFSET})
|
||||
ADD_DEFINITIONS(-DHEXT_VALUE=${HEXT_VALUE})
|
||||
ADD_DEFINITIONS(-DCMSIS_device_header="interrupt_manager.h")
|
||||
|
||||
ADD_DEFINITIONS(-DFLASH_PAGE_D_SIZE=2048)
|
||||
ADD_DEFINITIONS(-DFLASH_PAGE_P_SIZE=4096)
|
||||
ADD_DEFINITIONS(-DCOM_INT_BIG_BUFFERS)
|
||||
ADD_DEFINITIONS(-DVARIABLE_TABLE_WITH_ID)
|
||||
ADD_DEFINITIONS(-DLFS_THREADSAFE=1)
|
||||
ADD_DEFINITIONS(-DHALF_DUPLEX_NO_DELAY=1)
|
||||
ADD_DEFINITIONS(-DACCESS_ADC=1)
|
||||
ADD_DEFINITIONS(-DACCESS_RTC=1)
|
||||
ADD_DEFINITIONS(-DSTORAGE_ARTERY_CHECK_CLEAR=1)
|
||||
|
||||
#ADD_DEFINITIONS(-DSTORAGE_ARTERY_CHECK_WRITE_SECTORS=1) # Включение записи по секторам (Тестово, закоментированно)
|
||||
|
||||
#-- Project paths, Include dirs, Sources list ---------------------------------
|
||||
#ADD_FILES(SOURCES "MODULES/DeviceStartup_ARTERY_AT32F437ZMT7/ld/startup_at32f435_437.s")
|
||||
include(modular.cmake)
|
||||
|
||||
|
||||
#-- Options --------------------------------------------------------------------
|
||||
#IF (PRINTF_FLOAT STREQUAL "1")
|
||||
SET(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -u_printf_float")
|
||||
#ENDIF ()
|
||||
IF (SCANF_FLOAT STREQUAL "1")
|
||||
SET(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -u_scanf_float")
|
||||
ENDIF ()
|
||||
|
||||
#-- Linker script --------------------------------------------------------------
|
||||
SET(LDSCRIPT ${CMAKE_SOURCE_DIR}/APP/FC7240_flash.ld)
|
||||
SET(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -T ${LDSCRIPT} -Wl,-Map=${CMAKE_BINARY_DIR}/${PROJECT_NAME}.map -Wl,--print-memory-usage")
|
||||
|
||||
#-- Random BuildId Generation ------------------------------------------------------------
|
||||
SET(RANDOM_BUILD_ID_GEN_FILE ${CMAKE_SOURCE_DIR}/MODULES/CmakeConfig_RandomBuildIdGenerator/version.cmake)
|
||||
add_custom_target(GEN_RANDOM_BUILD_ID)
|
||||
ADD_CUSTOM_COMMAND(TARGET GEN_RANDOM_BUILD_ID POST_BUILD
|
||||
COMMAND ${CMAKE_COMMAND} -P ${RANDOM_BUILD_ID_GEN_FILE})
|
||||
|
||||
#-- Project linking ------------------------------------------------------------
|
||||
ADD_EXECUTABLE(${PROJECT_NAME}.elf ${SOURCES})
|
||||
TARGET_LINK_LIBRARIES(${PROJECT_NAME}.elf m)
|
||||
add_dependencies(${PROJECT_NAME}.elf GEN_RANDOM_BUILD_ID)
|
||||
|
||||
#-- Custom commands ------------------------------------------------------------
|
||||
ADD_CUSTOM_COMMAND(TARGET ${PROJECT_NAME}.elf POST_BUILD
|
||||
COMMAND ${CMAKE_OBJCOPY} "-Oihex" ${PROJECT_NAME}.elf ${CMAKE_BINARY_DIR}/${PROJECT_NAME}.hex
|
||||
COMMAND ${CMAKE_OBJCOPY} "-Obinary" ${PROJECT_NAME}.elf ${CMAKE_BINARY_DIR}/${PROJECT_NAME}.bin
|
||||
# COMMAND ${CMAKE_OBJDUMP} "-DS" ${PROJECT_NAME}.elf > ${CMAKE_BINARY_DIR}/${PROJECT_NAME}.dasm
|
||||
COMMAND ${CMAKE_SIZE} ${PROJECT_NAME}.elf)
|
||||
|
|
@ -0,0 +1,46 @@
|
|||
{
|
||||
"dep": [
|
||||
|
||||
{
|
||||
"type": "git",
|
||||
"provider": "HVAC_M7",
|
||||
"repo": "CmakeConfig_GCC_CortexM7"
|
||||
},
|
||||
|
||||
{
|
||||
"type": "git",
|
||||
"provider": "HVAC_M7",
|
||||
"repo": "CmakeConfig_RandomBuildIdGenerator"
|
||||
},
|
||||
|
||||
{
|
||||
"type": "git",
|
||||
"provider": "HVAC_M7",
|
||||
"repo": "HwA_Flagchip_FC7240"
|
||||
},
|
||||
|
||||
{
|
||||
"type": "git",
|
||||
"provider": "HVAC_M7",
|
||||
"repo": "PeripheralDriver_Flagchip_FC7240"
|
||||
},
|
||||
|
||||
{
|
||||
"type": "git",
|
||||
"provider": "HVAC_M7",
|
||||
"repo": "Device_Flagchip_FC7240"
|
||||
},
|
||||
|
||||
{
|
||||
"type": "git",
|
||||
"provider": "HVAC_M7",
|
||||
"repo": "GpioPin_Flagchip_FC7240"
|
||||
},
|
||||
|
||||
{
|
||||
"type": "local",
|
||||
"dir": "APP"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
|
|
@ -0,0 +1,666 @@
|
|||
#!/usr/bin/python3
|
||||
import subprocess
|
||||
import sys
|
||||
import argparse
|
||||
import os
|
||||
import json
|
||||
import platform
|
||||
import re
|
||||
import shutil
|
||||
from datetime import datetime
|
||||
|
||||
|
||||
def get_git_revision_hash(path=None) -> str:
|
||||
if path:
|
||||
# git -C <path> <command>
|
||||
# Runs the command as if git was started in <path> instead of the current working directory.
|
||||
# return subprocess.check_output(['git', '-C', path, 'rev-parse', 'HEAD']).decode('ascii').strip()
|
||||
stdout = subprocess.run(['git', '-C', path, 'rev-parse', 'HEAD'],
|
||||
check=True, capture_output=True, text=True).stdout.strip()
|
||||
return stdout
|
||||
else:
|
||||
# return subprocess.check_output(['git', 'rev-parse', 'HEAD']).decode('ascii').strip()
|
||||
stdout = subprocess.run(['git', 'rev-parse', 'HEAD'],
|
||||
check=True, capture_output=True, text=True).stdout.strip()
|
||||
return stdout
|
||||
|
||||
|
||||
class DependencyType:
|
||||
local = 'local'
|
||||
git = 'git'
|
||||
|
||||
|
||||
class Module:
|
||||
# raw - это прочитанный json в виде словаря
|
||||
def __init__(self, raw=None):
|
||||
self.cmake = {'inc': [], 'src': [], 'inc_dirs': [], 'srcs': [], 'libs': [], 'uis': []}
|
||||
self.dep = [] # список из объектов Dependency
|
||||
self.raw = raw
|
||||
|
||||
if raw:
|
||||
if 'cmake' in raw:
|
||||
if 'inc_dirs' in raw['cmake']:
|
||||
self.cmake['inc_dirs'] = raw['cmake']['inc_dirs']
|
||||
if 'srcs' in raw['cmake']:
|
||||
self.cmake['srcs'] = raw['cmake']['srcs']
|
||||
if 'libs' in raw['cmake']:
|
||||
self.cmake['libs'] = raw['cmake']['libs']
|
||||
if 'uis' in raw['cmake']:
|
||||
self.cmake['uis'] = raw['cmake']['uis']
|
||||
if 'dep' in raw:
|
||||
self.dep = [Dependency(rawDep) for rawDep in raw['dep']]
|
||||
|
||||
def __str__(self):
|
||||
return str(self.cmake)
|
||||
|
||||
def __repr__(self):
|
||||
return self.__str__()
|
||||
|
||||
def __eq__(self, other):
|
||||
if not isinstance(other, type(self)):
|
||||
return False
|
||||
return self.cmake == other.cmake and self.dep == other.dep
|
||||
|
||||
|
||||
class Dependency:
|
||||
# raw - это словарь
|
||||
def __init__(self, raw):
|
||||
if raw:
|
||||
if raw['type'] == DependencyType.local:
|
||||
self.type = DependencyType.local
|
||||
self.dir = raw.get('dir', '')
|
||||
self.os = raw.get('os', '')
|
||||
elif raw['type'] == DependencyType.git:
|
||||
self.type = DependencyType.git
|
||||
self.provider = raw.get('provider', '')
|
||||
self.dir = raw.get('dir', '')
|
||||
self.repo = raw.get('repo', '')
|
||||
self.commit = raw.get('commit', '')
|
||||
self.os = raw.get('os', '')
|
||||
self.project = raw.get('project', 'false')
|
||||
else:
|
||||
raise ValueError('Unknown dependency ' + str(raw['type']))
|
||||
|
||||
def __eq__(self, other):
|
||||
if self.type != other.type:
|
||||
return False
|
||||
|
||||
if self.type == DependencyType.local:
|
||||
return self.dir == other.dir
|
||||
elif self.type == DependencyType.git:
|
||||
return self.repo == other.repo
|
||||
else:
|
||||
raise ValueError('Unknown dependency' + str(self.type))
|
||||
|
||||
def __str__(self):
|
||||
if self.type == DependencyType.local:
|
||||
return 'local ' + str(self.dir)
|
||||
elif self.type == DependencyType.git:
|
||||
return 'git ' + str(self.repo)
|
||||
else:
|
||||
raise ValueError('Unknown dependency' + str(self.type))
|
||||
|
||||
|
||||
class ModularProject:
|
||||
# получить домашнюю директорию и приклеить к ней путь к modular_builder/config.json
|
||||
userConfigFile = os.path.join(os.path.expanduser('~'), '.modular_builder', 'config.json')
|
||||
|
||||
def __init__(self):
|
||||
self.clear()
|
||||
self.initDir()
|
||||
self.loadConfigs()
|
||||
|
||||
def clear(self):
|
||||
self.loadedModules = []
|
||||
self.rules = {}
|
||||
|
||||
def initDir(self):
|
||||
if not os.path.exists('MODULES'):
|
||||
print('No MODULES folder, creating...')
|
||||
os.mkdir('MODULES')
|
||||
print('Done')
|
||||
|
||||
def loadConfigs(self):
|
||||
if os.path.exists(self.userConfigFile):
|
||||
print('Has config file at ' + str(self.userConfigFile) + ', loading...')
|
||||
self.loadConfig(self.userConfigFile)
|
||||
print('Done')
|
||||
else:
|
||||
print('No config file at ' + str(self.userConfigFile))
|
||||
|
||||
# в config.json лежит примерно это:
|
||||
# {
|
||||
# "git_providers:" {
|
||||
# "rospron_modules": "http"//git...blabla.../rosprom_modules"
|
||||
# }
|
||||
# }
|
||||
def loadConfig(self, config_path):
|
||||
config = json.load(open(config_path, encoding='utf-8'))
|
||||
self.gitProviders = config['git_providers']
|
||||
|
||||
def loadJsonAtPath(self, path): # path - путь до modular.json
|
||||
print('loading json', path)
|
||||
try:
|
||||
with open(path, encoding='utf-8') as f:
|
||||
result = Module(json.load(f))
|
||||
return result
|
||||
except json.JSONDecodeError:
|
||||
print('Error while reading json file at path:', path, file=sys.stderr)
|
||||
print('Try fixing JSON file and run modular.py again', file=sys.stderr)
|
||||
raise json.JSONDecodeError
|
||||
|
||||
def downloadableModulePath(self, dependency):
|
||||
if dependency.type == DependencyType.git:
|
||||
if dependency.project == 'true':
|
||||
return dependency.repo
|
||||
else:
|
||||
return os.path.join('MODULES', dependency.repo)
|
||||
raise ValueError('UnknownDependency')
|
||||
|
||||
def isGitModuleCloned(self, dependency):
|
||||
return os.path.exists(self.downloadableModulePath(dependency))
|
||||
|
||||
def isModuleSystemAppropriate(self, dependency):
|
||||
if not dependency.os: # если ОС не указана для модуля, то грузим его всегда
|
||||
return True
|
||||
elif dependency.os.lower() == 'windows':
|
||||
print('Module only for Windows')
|
||||
return platform.system().lower() == 'windows'
|
||||
elif dependency.os.lower() == 'linux':
|
||||
print('Module only for Linux')
|
||||
return platform.system().lower() == 'linux'
|
||||
else:
|
||||
print('Unknown OS:', dependency.os)
|
||||
print('Dependency will be uploaded anyway')
|
||||
return True
|
||||
|
||||
def cloneGitDependency(self, dependency):
|
||||
path = self.downloadableModulePath(dependency)
|
||||
clone_cmd = 'git clone ' + str(self.gitProviders[dependency.provider]) + '/' + str(dependency.repo) + ' ' + str(
|
||||
path)
|
||||
print('Clone with', clone_cmd)
|
||||
os.system(clone_cmd) # выполняет любые поддерживаемые команды в командной строке
|
||||
|
||||
if dependency.commit:
|
||||
checkout_cmd = f'git -C {path} checkout {dependency.commit}'
|
||||
# git -C <path> <command>
|
||||
# Runs the command as if git was started in <path> instead of the current working directory.
|
||||
print(f'Checkout with {checkout_cmd}')
|
||||
os.system(checkout_cmd) # выполняет любые поддерживаемые команды в командной строке
|
||||
|
||||
def loadDependency(self, dependency):
|
||||
if self.checkDependencyCollision(dependency):
|
||||
return []
|
||||
print('\nLoading module', dependency)
|
||||
if dependency.type == DependencyType.local:
|
||||
return self.loadDependencyFromLocal(dependency)
|
||||
elif dependency.type == DependencyType.git:
|
||||
return self.loadDependencyFromGit(dependency)
|
||||
else:
|
||||
raise ValueError('Unknown module')
|
||||
|
||||
def loadDependencyFromLocal(self, dependency):
|
||||
if self.isModuleSystemAppropriate(dependency):
|
||||
return self.loadDependencyFromDir(dependency.dir)
|
||||
|
||||
def loadDependencyFromGit(self, dependency):
|
||||
if self.isModuleSystemAppropriate(dependency):
|
||||
if not self.isGitModuleCloned(dependency):
|
||||
self.cloneGitDependency(dependency)
|
||||
return self.loadDependencyFromDir(self.downloadableModulePath(dependency))
|
||||
|
||||
def loadDependencyFromDir(self, modular_dir):
|
||||
modular_json_path = os.path.join(modular_dir, 'modular.json')
|
||||
|
||||
if not os.path.exists(modular_json_path):
|
||||
print('Directory in not a module:', modular_dir)
|
||||
return []
|
||||
|
||||
# module_relative - объект класса Module, внутри него в списке dep хранятся прочитанные из json объекты Dependency
|
||||
module_relative = self.loadJsonAtPath(modular_json_path)
|
||||
project_relative = Module()
|
||||
|
||||
print('module_relative:', module_relative)
|
||||
print(module_relative.cmake)
|
||||
|
||||
result_inc_dirs = self.addRootToPaths(modular_dir, module_relative.cmake.get('inc_dirs', ''))
|
||||
project_relative.cmake['inc_dirs'] = result_inc_dirs
|
||||
result_srcs = self.addRootToPaths(modular_dir, module_relative.cmake.get('srcs', ''))
|
||||
project_relative.cmake['srcs'] = result_srcs
|
||||
result_libs = self.addRootToPaths(modular_dir, module_relative.cmake.get('libs', ''))
|
||||
project_relative.cmake['libs'] = result_libs
|
||||
result_uis = self.addRootToPaths(modular_dir, module_relative.cmake.get('uis', ''))
|
||||
project_relative.cmake['uis'] = result_uis
|
||||
|
||||
# После выполнения строки ниже в project_relative.dep окажется просто
|
||||
# список Dependency, который и был в module_relative.dep.
|
||||
# (Это список модулей, от которых текущий модуль зависит. Их надо будет докачать)
|
||||
project_relative.dep = self.addRootToDeps(modular_dir, module_relative.dep)
|
||||
|
||||
sub_modules = []
|
||||
for dependency in project_relative.dep:
|
||||
loaded_dependencies = self.loadDependency(dependency)
|
||||
if loaded_dependencies:
|
||||
# sub_modules.extend(loaded_dependencies)
|
||||
# чтобы не было повторений
|
||||
for dep_loaded in loaded_dependencies:
|
||||
if dep_loaded not in sub_modules:
|
||||
sub_modules.append(dep_loaded)
|
||||
else:
|
||||
print('Nothing to download, continuing')
|
||||
|
||||
sub_modules.append(project_relative)
|
||||
print('sub_modules', sub_modules)
|
||||
return sub_modules
|
||||
|
||||
def addRootToPaths(self, root, paths):
|
||||
if not paths:
|
||||
return []
|
||||
result = []
|
||||
for pth in paths:
|
||||
if os.path.isabs(pth): # если путь абсолютный
|
||||
result.append(pth)
|
||||
else:
|
||||
if pth.startswith('./'): # если текущий путь начинается с текущей папки, то убери ее
|
||||
pth = pth[2:]
|
||||
result.append(os.path.join(root, pth))
|
||||
return result
|
||||
|
||||
# эта функция возвращает просто список объектов Dependency
|
||||
def addRootToDeps(self, root, deps):
|
||||
result = []
|
||||
for dep in deps:
|
||||
if dep.type == DependencyType.local:
|
||||
if not os.path.isabs(dep.dir):
|
||||
dep.dir = os.path.join(root, dep.dir)
|
||||
result.append(dep)
|
||||
return result
|
||||
|
||||
def download(self):
|
||||
# self.modules - это список из объектов Dependency
|
||||
self.modules = self.loadDependency(Dependency({'type': 'local', 'dir': './'}))
|
||||
|
||||
print('modules: ')
|
||||
print(self.modules)
|
||||
|
||||
def replace_slashes(self, path):
|
||||
return path.replace('\\', '/')
|
||||
|
||||
def genCmake(self):
|
||||
cmakeText = '''function(add_sources FILE_LIST FILES_PATH)
|
||||
file(GLOB_RECURSE ADD_FILES_LIST ${FILES_PATH})
|
||||
list(APPEND ${FILE_LIST} ${ADD_FILES_LIST})
|
||||
set(${FILE_LIST} ${${FILE_LIST}} PARENT_SCOPE)
|
||||
endfunction()\n\n'''
|
||||
|
||||
for module in self.modules:
|
||||
for inc in module.cmake['inc_dirs']:
|
||||
cmakeText += 'include_directories("' + str(inc) + '")\n'
|
||||
cmakeText += '\n'
|
||||
|
||||
for module in self.modules:
|
||||
for src in module.cmake['srcs']:
|
||||
cmakeText += 'add_sources(SOURCES "' + str(src) + '")\n'
|
||||
cmakeText += '\n'
|
||||
|
||||
for module in self.modules:
|
||||
for lib in module.cmake['libs']:
|
||||
cmakeText += 'add_sources(LIBRARIES "' + str(lib) + '")\n'
|
||||
cmakeText += '\n'
|
||||
|
||||
for module in self.modules:
|
||||
for ui in module.cmake['uis']:
|
||||
cmakeText += 'add_sources(UIS "' + str(ui) + '")\n'
|
||||
cmakeText += '\n'
|
||||
|
||||
# заменяем обратный слеш на прямой, так как винда склеивает своими слешами, но их не поинмает компилятор:
|
||||
cmakeText = self.replace_slashes(cmakeText)
|
||||
print(cmakeText)
|
||||
with open('modular.cmake', 'w', encoding='utf-8') as file:
|
||||
file.write(cmakeText)
|
||||
|
||||
def genCmakeForLibrify(self):
|
||||
other_path, project_name = os.path.split(os.getcwd())
|
||||
cmakeText = '''cmake_minimum_required(VERSION 3.17)
|
||||
project(''' + project_name + ''')
|
||||
set(CMAKE_C_STANDARD 11)
|
||||
|
||||
function(add_sources FILE_LIST FILES_PATH)
|
||||
file(GLOB ADD_FILES_LIST ${FILES_PATH})
|
||||
list(APPEND ${FILE_LIST} ${ADD_FILES_LIST})
|
||||
set(${FILE_LIST} ${${FILE_LIST}} PARENT_SCOPE)
|
||||
endfunction()\n\n'''
|
||||
|
||||
for module in self.modules:
|
||||
for inc in module.cmake['inc_dirs']:
|
||||
cmakeText += 'include_directories("' + str(inc) + '")\n'
|
||||
cmakeText += '\n'
|
||||
|
||||
module = self.modules[-1] # берем только главный (корневой) модуль
|
||||
for src in module.cmake['srcs']:
|
||||
cmakeText += 'add_sources(SOURCES "' + str(src) + '")\n'
|
||||
cmakeText += '\n'
|
||||
|
||||
for module in self.modules:
|
||||
for lib in module.cmake['libs']:
|
||||
cmakeText += 'add_sources(LIBRARIES "' + str(lib) + '")\n'
|
||||
cmakeText += '\n'
|
||||
|
||||
for module in self.modules:
|
||||
for ui in module.cmake['uis']:
|
||||
cmakeText += 'add_sources(UIS "' + str(ui) + '")\n'
|
||||
cmakeText += '\n'
|
||||
|
||||
cmakeText += 'add_library(' + project_name + ' ${SOURCES})\n'
|
||||
|
||||
# заменяем обратный слеш на прямой, так как винда склеивает своими слешами, но их не поинмает компилятор:
|
||||
cmakeText = self.replace_slashes(cmakeText)
|
||||
print(cmakeText)
|
||||
with open('modular.cmake', 'w', encoding='utf-8') as file:
|
||||
file.write(cmakeText)
|
||||
|
||||
def checkDependencyCollision(self, dependency):
|
||||
"""Возвращает True, если зависимость dependency уже есть среди загруженных модулей"""
|
||||
# TODO проверка не работает, в self.loadedModules ничего не добавляется, коллизии происходят, ну и пофиг...
|
||||
return any([loaded == dependency for loaded in self.loadedModules])
|
||||
|
||||
# def genEclipseXmlPart(self) - эта функция использоваться не будет
|
||||
# def genExp32Cmake(self) - эта функция использоваться не будет
|
||||
|
||||
def load_rules(self, config_path):
|
||||
try:
|
||||
rules = json.load(open(config_path, encoding='utf-8'))
|
||||
except json.JSONDecodeError:
|
||||
print('Error while reading json file at path:', config_path, file=sys.stderr)
|
||||
print('Try fixing JSON file and run modular.py again', file=sys.stderr)
|
||||
raise json.JSONDecodeError
|
||||
if 'replacements' not in rules:
|
||||
rules['replacements'] = {}
|
||||
if 'filetypes' not in rules:
|
||||
rules['filetypes'] = [".c", ".cpp", ".h"] # если типы файлов не указали, будем менять только в этих
|
||||
if 'remove_comments' not in rules:
|
||||
rules['remove_comments'] = False
|
||||
if 'librify' not in rules:
|
||||
rules['librify'] = []
|
||||
if 'ignore' not in rules:
|
||||
rules['ignore'] = []
|
||||
|
||||
self.rules = rules
|
||||
|
||||
def replacements_and_comments_deletion(self):
|
||||
project_path = '.'
|
||||
|
||||
def remove_comments_in_text(string):
|
||||
pattern = r"(\".*?\"|\'.*?\')|(/\*.*?\*/|//[^\r\n]*$)"
|
||||
# первая группа захватывает строки в кавычках (двойных или одинарных)
|
||||
# вторая группа захватывает комментарии (
|
||||
regex = re.compile(pattern, re.MULTILINE | re.DOTALL)
|
||||
|
||||
def _replacer(match):
|
||||
# если вторая группа (захватывающая комменты) не None,
|
||||
# значит, мы захватили не закавыченные (нормальные) комменты
|
||||
if match.group(2) is not None:
|
||||
return "" # возвращаем пустую строку для удаления коммента
|
||||
else: # иначе возвращаем 1-ую группу
|
||||
return match.group(1) # поймали "закавыченную" строку
|
||||
|
||||
return regex.sub(_replacer, string)
|
||||
|
||||
def remove_comments_in_file(filename):
|
||||
with open(filename, 'r') as f:
|
||||
content = f.read()
|
||||
content_new = remove_comments_in_text(content)
|
||||
with open(filename, 'w') as f:
|
||||
f.write(content_new)
|
||||
|
||||
def should_exclude_folder(project_path, dirpath, rules):
|
||||
folder_fullpath = os.path.normpath(dirpath)
|
||||
return any([folder_fullpath == os.path.normpath(os.path.join(project_path, ignore_path))
|
||||
for ignore_path in rules['ignore']])
|
||||
|
||||
def replace_occurrences_in_file(filename, rules):
|
||||
with open(filename, 'r') as f:
|
||||
content = f.read()
|
||||
content_new = content
|
||||
for (old_name, new_name) in rules['replacements'].items():
|
||||
content_new = re.sub(old_name, new_name, content_new)
|
||||
with open(filename, 'w') as f:
|
||||
f.write(content_new)
|
||||
|
||||
for (dirpath, dirnames, filenames) in os.walk(project_path):
|
||||
# print('*****', dirpath, dirnames, filenames)
|
||||
if should_exclude_folder(project_path, dirpath, self.rules):
|
||||
# если папка входит в игнорируемые, то пропускаем
|
||||
print('Исключена папка:', dirpath)
|
||||
continue
|
||||
for file in filenames:
|
||||
filename, file_extension = os.path.splitext(file)
|
||||
if file_extension not in self.rules['filetypes']:
|
||||
# если расширение не входит в список заданных, то пропускаем этот файт
|
||||
continue
|
||||
fullpath = os.path.join(dirpath, file)
|
||||
print(fullpath)
|
||||
if self.rules['remove_comments']:
|
||||
remove_comments_in_file(fullpath)
|
||||
replace_occurrences_in_file(fullpath, self.rules)
|
||||
|
||||
def libraryfication(self):
|
||||
initial_wd = os.getcwd()
|
||||
"""Собирает библиотеки из модулей в папках, указанных в self.rules["librify"] """
|
||||
if not os.path.exists('SHRINK'):
|
||||
print('No SHRINK folder, creating...')
|
||||
os.mkdir('SHRINK')
|
||||
print('Done')
|
||||
else:
|
||||
print(
|
||||
'SHRINK folder already exists. Stopping. \n(If you want to generate libs, delete SHRINK folder first)')
|
||||
return
|
||||
|
||||
cmake_lists_text = '''include(../arch.cmake)
|
||||
|
||||
function(add_sources FILE_LIST FILES_PATH)
|
||||
file(GLOB_RECURSE ADD_FILES_LIST ${FILES_PATH})
|
||||
list(APPEND ${FILE_LIST} ${ADD_FILES_LIST})
|
||||
endfunction()
|
||||
|
||||
include(modular.cmake)
|
||||
'''
|
||||
|
||||
for directory in self.rules["librify"]:
|
||||
if not os.path.exists(directory):
|
||||
print('Error! Directory from shrink.json does not exists:', directory)
|
||||
raise FileNotFoundError
|
||||
os.chdir(directory) # переходим в папку к этому модулю
|
||||
|
||||
library_name = directory.split('/')[-1]
|
||||
|
||||
config = json.load(open('modular.json', encoding='utf-8'))
|
||||
for src in config['cmake']['srcs']:
|
||||
cmake_lists_text += f'add_sources({library_name}_SOURCES "' + '../MODULES/' + library_name + '/' + src + '")\n'
|
||||
|
||||
cmake_lists_text += 'add_library(' + library_name + ' ${' + library_name + '_SOURCES})'
|
||||
os.chdir(initial_wd) # в конце не забываем вернуться в корневую папку проекта
|
||||
|
||||
os.chdir('SHRINK')
|
||||
with open('CMakeLists.txt', 'w', encoding='utf-8') as file:
|
||||
file.write(cmake_lists_text)
|
||||
|
||||
with open('modular.json', 'w') as new_modular:
|
||||
modular_text = '''{
|
||||
"dep": [
|
||||
{
|
||||
"type": "local",
|
||||
"dir": "../"
|
||||
}
|
||||
]
|
||||
}'''
|
||||
new_modular.write(modular_text)
|
||||
result_run = subprocess.run(["modular.py", "-c"])
|
||||
os.mkdir('build')
|
||||
os.chdir('build')
|
||||
result_run = subprocess.run(["cmake", ".."])
|
||||
if result_run.returncode != 0:
|
||||
print('cmake not successful. Stop')
|
||||
raise RuntimeError('Previous cmake not successful. Stop')
|
||||
result_run = subprocess.run(["make"])
|
||||
if result_run.returncode != 0:
|
||||
print('make not successful. Stop')
|
||||
raise RuntimeError('Previous make not successful. Stop')
|
||||
# print('Result code of cmake:', result_run.returncode)
|
||||
os.chdir('..')
|
||||
os.chdir(initial_wd)
|
||||
self.copy_all_libs_to_libs_folder()
|
||||
|
||||
def copy_all_libs_to_libs_folder(self):
|
||||
current_wd = os.path.abspath(os.getcwd())
|
||||
try:
|
||||
if os.path.exists('libs'):
|
||||
print('libs already exists')
|
||||
else:
|
||||
os.mkdir('libs')
|
||||
dest_path = os.path.join(current_wd, 'libs')
|
||||
os.chdir('SHRINK')
|
||||
os.chdir('build')
|
||||
|
||||
for (dirpath, dirnames, filenames) in os.walk('.'):
|
||||
for file in filenames:
|
||||
if file.endswith(".a"):
|
||||
source_file_path = os.path.join(dirpath, file)
|
||||
shutil.copy(source_file_path, dest_path)
|
||||
|
||||
except FileNotFoundError as e:
|
||||
print('Couldn\'t copy .a libs, error occurred!')
|
||||
print(e)
|
||||
os.chdir(current_wd) # возвращаемся в исходную папку
|
||||
|
||||
def delete_sources_of_libraries(self):
|
||||
current_wd = os.path.abspath(os.getcwd())
|
||||
for module_directory in self.rules["librify"]:
|
||||
if not os.path.exists(module_directory):
|
||||
print('Error! Directory from shrink.json does not exists:', module_directory)
|
||||
raise FileNotFoundError
|
||||
os.chdir(module_directory)
|
||||
config = json.load(open('modular.json', encoding='utf-8'))
|
||||
needed_dirs = config['cmake']['inc_dirs']
|
||||
all_dirs_files = [name for name in os.listdir(os.getcwd()) if
|
||||
os.path.isdir(os.path.join(os.getcwd(), name))]
|
||||
print('all files:', all_dirs_files)
|
||||
for dir in all_dirs_files:
|
||||
if dir not in needed_dirs:
|
||||
print(f'remove dir {dir} in {os.path.join(current_wd, module_directory)}')
|
||||
shutil.rmtree(dir)
|
||||
os.chdir(current_wd)
|
||||
|
||||
def delete_all_modular_json_files(self):
|
||||
print('Starting to delete all modular.json...')
|
||||
for (dirpath, dirnames, filenames) in os.walk('.'):
|
||||
for file in filenames:
|
||||
if str(file) == 'modular.json':
|
||||
os.remove(os.path.join(dirpath, file))
|
||||
print('All modular.json files deleted from the project!')
|
||||
|
||||
def shrink(self):
|
||||
print('Start shrinking...')
|
||||
self.load_rules('shrink.json')
|
||||
self.replacements_and_comments_deletion()
|
||||
self.libraryfication()
|
||||
self.delete_sources_of_libraries()
|
||||
self.delete_all_modular_json_files()
|
||||
|
||||
print('Done shrinking')
|
||||
|
||||
def create_release(self, tag=None):
|
||||
"""
|
||||
Сохраняет информацию о текущих версиях каждого из модулей в качестве релиза.
|
||||
В результате в корне проекта создается файл с именем <dd.mm.yyyy_hh.mm[_tag]_release>
|
||||
:param tag:
|
||||
:return:
|
||||
"""
|
||||
# without_duplicates = []
|
||||
# for module in self.modules:
|
||||
# if module not in without_duplicates:
|
||||
# without_duplicates.append(module)
|
||||
# print(without_duplicates)
|
||||
dependencies_without_duplicated = []
|
||||
for module in self.modules:
|
||||
if module.dep:
|
||||
for dep in module.dep:
|
||||
if dep not in dependencies_without_duplicated:
|
||||
dependencies_without_duplicated.append(dep)
|
||||
# print(dependencies_without_duplicated)
|
||||
|
||||
all_dependencies_for_project = {"dep": []}
|
||||
for dep in dependencies_without_duplicated:
|
||||
try:
|
||||
path = os.path.join('MODULES', dep.repo)
|
||||
commit_hash = get_git_revision_hash(path)
|
||||
dep_json = {
|
||||
"type": dep.type,
|
||||
"provider": dep.provider,
|
||||
"repo": dep.repo,
|
||||
"commit": commit_hash
|
||||
}
|
||||
all_dependencies_for_project['dep'].append(dep_json)
|
||||
except AttributeError as e:
|
||||
pass # игнорим: 'Dependency' object has no attribute 'repo' (dep=local ./APP)
|
||||
except Exception as e:
|
||||
print(f'Случилось испключение: {e} (dep={dep})')
|
||||
# print(all_dependencies_for_project)
|
||||
|
||||
release_file_name = datetime.today().strftime('%d.%m.%Y_%H.%M') # <dd.mm.yyyy_hh.mm_release[_tag]>
|
||||
if tag:
|
||||
release_file_name += '_' + tag
|
||||
release_file_name += '_release.json'
|
||||
with open(release_file_name, 'w', encoding='utf-8') as output_file:
|
||||
json.dump(all_dependencies_for_project, output_file, ensure_ascii=False, indent=2)
|
||||
print(f'Создан файл релиза: {release_file_name}')
|
||||
|
||||
def checkout_release(self, json_name):
|
||||
# with open(json_name, encoding='utf-8') as f:
|
||||
# release_json = json.load(f)
|
||||
print('Начинаем переход на указанные коммиты в релизе...')
|
||||
module = self.loadJsonAtPath(json_name)
|
||||
for dependency in module.dep:
|
||||
if dependency.commit:
|
||||
path = self.downloadableModulePath(dependency)
|
||||
checkout_cmd = f'git -C {path} checkout {dependency.commit}'
|
||||
# git -C <path> <command>
|
||||
# Runs the command as if git was started in <path> instead of the current working directory.
|
||||
print(f'Checkout with {checkout_cmd}')
|
||||
os.system(checkout_cmd) # выполняет любые поддерживаемые команды в командной строке
|
||||
print(f'Вернули состояние проекта к релизной версии {json_name}')
|
||||
|
||||
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument('-c', '--cmake', action='store_true', help='require generate cmake from modules')
|
||||
parser.add_argument('-s', '--shrink', action='store_true',
|
||||
help='Согласно правилам из shrink.json выполняет замены по RegEx и при "remove_comments": true удаляет все комментарии из кода')
|
||||
parser.add_argument('-d', '--download', action='store_true', help='require download submodules')
|
||||
parser.add_argument('wdir', help='path to working directory', type=str, default='./', nargs='?')
|
||||
parser.add_argument('-r', '--release', action='store_true',
|
||||
help='Отмечает текущее состояние проекта как релизное, создает соответствующий состоянию json')
|
||||
parser.add_argument('--checkout', type=str,
|
||||
help='Переходит в указанный релиз (выполняет checkout). Для релиза должен быть заранее создан релизный json')
|
||||
argv = parser.parse_args()
|
||||
|
||||
print('working directory', argv.wdir)
|
||||
|
||||
os.chdir(argv.wdir) # изменить текущую рабочую директорию
|
||||
|
||||
project = ModularProject()
|
||||
|
||||
if argv.download or argv.cmake or argv.shrink:
|
||||
project.download()
|
||||
if argv.cmake:
|
||||
project.genCmake()
|
||||
if argv.shrink:
|
||||
project.shrink()
|
||||
if argv.release:
|
||||
print('release')
|
||||
project.download()
|
||||
project.create_release()
|
||||
if argv.checkout:
|
||||
project.download()
|
||||
project.checkout_release(argv.checkout)
|
||||
# TODO: после checkout проекты будут в состоянии detached HEAH (оторванный указатель HEAD),
|
||||
# и надо уметь какой-то командой возвращаться в исходную позицию (с учитыванием commit, указанного в самом проекте...)
|
||||
|
|
@ -0,0 +1,27 @@
|
|||
#
|
||||
# This is an STM32F429 discovery board with a single STM32F429ZI chip.
|
||||
# http://www.st.com/web/catalog/tools/FM116/SC959/SS1532/PF259090
|
||||
#
|
||||
|
||||
source [find interface/atlink.cfg]
|
||||
|
||||
#transport select hla_swd
|
||||
|
||||
source [find target/flagchip/fc7240/fc7240f2m.cfg]
|
||||
|
||||
#reset_config trst_only
|
||||
#reset_config srst_only
|
||||
#reset_config trst_and_srst
|
||||
#reset_config srst_pulls_trst
|
||||
#reset_config combined
|
||||
#reset_config srst_gates_jtag
|
||||
#reset_config trst_push_pull
|
||||
#reset_config trst_push_pull
|
||||
|
||||
reset_config none
|
||||
|
||||
#reset_config [none|trst_only|srst_only|trst_and_srst]
|
||||
#[srst_pulls_trst|trst_pulls_srst|combined|separate]
|
||||
#[srst_gates_jtag|srst_nogate] [trst_push_pull|trst_open_drain]
|
||||
#[srst_push_pull|srst_open_drain]
|
||||
#[connect_deassert_srst|connect_assert_srst]
|
||||
Loading…
Reference in New Issue