Browse Source

Merge branch '4G_PingFeng' into 4G_ZK

# Conflicts:
#	.cproject
#	.settings/language.settings.xml
#	.vscode/c_cpp_properties.json
#	Project_Settings/Debugger/S32K146_4G_Debug_FLASH_PNE.launch
#	RTD/src/Lpuart_Uart_Ip.c
#	code/app/AppTaskGps.c
#	code/app/AppTaskUart0.h
#	code/app/Hal_Fls.c
#	code/app/Hal_Fls.h
#	code/app/USER_CONFIG.h
#	code/driver/SL_Sc7a20_Driver.h
#	code/main.c
#	generate/src/IntCtrl_Ip_Cfg.c
#	src/AppGlobalVar.c
#	src/AppGlobalVar.h
#	src/AppTaskCan.c
#	src/AppTaskMain.c
#	src/AppTaskUart0.c
#	src/AppTaskUart1.c
#	src/AppTaskUart1.h
#	src/UDSTask.h
#	src/hal_adapter.c
#	src/hal_adapter.h
LAPTOP-KB7QFH2U\ChenJie-PC 2 years ago
parent
commit
91c735dd10
70 changed files with 15661 additions and 294 deletions
  1. 32 75
      .cproject
  2. 1 0
      .settings/com.freescale.s32ds.cross.sdk.support.prefs
  3. 4 4
      .settings/language.settings.xml
  4. 0 2
      .vscode/c_cpp_properties.json
  5. 2 0
      FreeRTOS/Source/include/FreeRTOS.h
  6. 6 2
      FreeRTOS/Source/include/FreeRTOSConfig.h
  7. 28 2
      FreeRTOS/Source/tasks.c
  8. 14 0
      Project_Settings/Linker_Files/linker_flash_s32k146.ldota
  9. 1 2
      Project_Settings/Startup_Code/exceptions.c
  10. 1 1
      RTD/src/Lpuart_Uart_Ip.c
  11. 107 0
      code/app/AppGlobalVar.c
  12. 119 0
      code/app/AppGlobalVar.h
  13. 456 0
      code/app/AppTaskCan.c
  14. 8 7
      code/app/AppTaskCan.h
  15. 26 26
      code/app/AppTaskGps.c
  16. 8 5
      code/app/AppTaskGps.h
  17. 72 0
      code/app/AppTaskMain.c
  18. 19 0
      code/app/AppTaskMain.h
  19. 250 0
      code/app/AppTaskUart0.c
  20. 15 0
      code/app/AppTaskUart0.h
  21. 1653 0
      code/app/AppTaskUart1.c
  22. 207 0
      code/app/AppTaskUart1.h
  23. 1 1
      code/app/UDSTask.c
  24. 45 0
      code/app/UDSTask.h
  25. 1 1
      code/app/USER_CONFIG.h
  26. 39 46
      code/app/lib/AppFuncLib.c
  27. 13 19
      code/app/lib/AppFuncLib.h
  28. 113 0
      code/debug/SEGGER/Global.h
  29. 248 0
      code/debug/SEGGER/SEGGER.h
  30. 2095 0
      code/debug/SEGGER/SEGGER_RTT.c
  31. 492 0
      code/debug/SEGGER/SEGGER_RTT.h
  32. 428 0
      code/debug/SEGGER/SEGGER_RTT_Conf.h
  33. 124 0
      code/debug/SEGGER/SEGGER_RTT_Syscalls_GCC.c
  34. 119 0
      code/debug/SEGGER/SEGGER_RTT_Syscalls_IAR.c
  35. 393 0
      code/debug/SEGGER/SEGGER_RTT_Syscalls_KEIL.c
  36. 251 0
      code/debug/SEGGER/SEGGER_RTT_Syscalls_SES.c
  37. 504 0
      code/debug/SEGGER/SEGGER_RTT_printf.c
  38. 3102 0
      code/debug/SEGGER/SEGGER_SYSVIEW.c
  39. 370 0
      code/debug/SEGGER/SEGGER_SYSVIEW.h
  40. 85 0
      code/debug/SEGGER/SEGGER_SYSVIEW_Conf.h
  41. 579 0
      code/debug/SEGGER/SEGGER_SYSVIEW_ConfDefaults.h
  42. 104 0
      code/debug/SEGGER/SEGGER_SYSVIEW_Config_FreeRTOS.c
  43. 252 0
      code/debug/SEGGER/SEGGER_SYSVIEW_FreeRTOS.c
  44. 334 0
      code/debug/SEGGER/SEGGER_SYSVIEW_FreeRTOS.h
  45. 99 0
      code/debug/SEGGER/SEGGER_SYSVIEW_Int.h
  46. 8 0
      code/debug/cm_backtrace/Languages/README.md
  47. 71 0
      code/debug/cm_backtrace/Languages/en-US/cmb_en_US.h
  48. 71 0
      code/debug/cm_backtrace/Languages/zh-CN/cmb_zh_CN.h
  49. 71 0
      code/debug/cm_backtrace/Languages/zh-CN/cmb_zh_CN_UTF8.h
  50. 666 0
      code/debug/cm_backtrace/cm_backtrace.c
  51. 48 0
      code/debug/cm_backtrace/cm_backtrace.h
  52. 46 0
      code/debug/cm_backtrace/cmb_cfg.h
  53. 417 0
      code/debug/cm_backtrace/cmb_def.h
  54. 43 0
      code/debug/cm_backtrace/fault_handler/gcc/cmb_fault.S
  55. 47 0
      code/debug/cm_backtrace/fault_handler/iar/cmb_fault.S
  56. 48 0
      code/debug/cm_backtrace/fault_handler/keil/cmb_fault.S
  57. 0 0
      code/driver/SL_Sc7a20_Driver.c
  58. 33 33
      code/driver/SL_Sc7a20_Driver.h
  59. 17 4
      code/hal/Hal_Fls.c
  60. 3 2
      code/hal/Hal_Fls.h
  61. 1 1
      code/hal/Hal_Var.c
  62. 1 1
      code/hal/Hal_Var.h
  63. 0 0
      code/hal/Hal_Wdg.c
  64. 1 1
      code/hal/Hal_Wdg.h
  65. 963 0
      code/hal/hal_adapter.c
  66. 250 0
      code/hal/hal_adapter.h
  67. 25 19
      code/main.c
  68. 11 11
      generate/src/Power_Ip_VS_0_PBcfg.c
  69. 0 16
      src/AppTaskMain.h
  70. 0 13
      src/AppTaskUart0.h

+ 32 - 75
.cproject

@@ -13,29 +13,39 @@
 				</extensions>
 			</storageModule>
 			<storageModule moduleId="cdtBuildSystem" version="4.0.0">
-				<configuration artifactExtension="elf" artifactName="${ProjName}" buildArtefactType="com.nxp.s32ds.cle.arm.mbs.arm32.bare.buildArtefact.exe" buildProperties="org.eclipse.cdt.build.core.buildArtefactType=com.nxp.s32ds.cle.arm.mbs.arm32.bare.buildArtefact.exe,org.eclipse.cdt.build.core.buildType=org.eclipse.cdt.build.core.buildType.debug" description="" errorParsers="org.eclipse.cdt.core.GASErrorParser;org.eclipse.cdt.core.GmakeErrorParser;com.freescale.s32ds.cdt.core.errorParsers.S32DSGNULinkerErrorParser;org.eclipse.cdt.core.GCCErrorParser" id="com.nxp.s32ds.cle.arm.mbs.arm32.bare.gnu.9.2.exe.debug.222968549" name="Debug_FLASH" parent="com.nxp.s32ds.cle.arm.mbs.arm32.bare.gnu.9.2.exe.debug">
+				<configuration artifactExtension="elf" artifactName="${ProjName}" buildArtefactType="com.nxp.s32ds.cle.arm.mbs.arm32.bare.buildArtefact.exe" buildProperties="org.eclipse.cdt.build.core.buildArtefactType=com.nxp.s32ds.cle.arm.mbs.arm32.bare.buildArtefact.exe,org.eclipse.cdt.build.core.buildType=org.eclipse.cdt.build.core.buildType.debug" description="" id="com.nxp.s32ds.cle.arm.mbs.arm32.bare.gnu.9.2.exe.debug.222968549" name="Debug_FLASH" parent="com.nxp.s32ds.cle.arm.mbs.arm32.bare.gnu.9.2.exe.debug">
 					<folderInfo id="com.nxp.s32ds.cle.arm.mbs.arm32.bare.gnu.9.2.exe.debug.222968549." name="/" resourcePath="">
 						<toolChain id="com.nxp.s32ds.cle.arm.mbs.arm32.bare.gnu.9.2.toolchain.debug.1669149124" name="NXP GCC 9.2 for Arm 32-bit Bare-Metal" superClass="com.nxp.s32ds.cle.arm.mbs.arm32.bare.gnu.9.2.toolchain.debug">
 							<option defaultValue="true" id="com.nxp.s32ds.cle.arm.mbs.arm32.bare.option.addtools.printsize.1799663837" name="Print size" superClass="com.nxp.s32ds.cle.arm.mbs.arm32.bare.option.addtools.printsize" useByScannerDiscovery="false" valueType="boolean"/>
 							<option id="com.nxp.s32ds.cle.arm.mbs.arm32.bare.gnu.9.2.option.compiler.path.434372331" name="Path" superClass="com.nxp.s32ds.cle.arm.mbs.arm32.bare.gnu.9.2.option.compiler.path" useByScannerDiscovery="false" value="${S32DS_K1_ARM32_GNU_9_2_TOOLCHAIN_DIR}" valueType="string"/>
-							<option id="com.nxp.s32ds.cle.arm.mbs.arm32.bare.gnu.9.2.option.target.libraries.933777928" name="Libraries support" superClass="com.nxp.s32ds.cle.arm.mbs.arm32.bare.gnu.9.2.option.target.libraries" useByScannerDiscovery="false" value="com.nxp.s32ds.cle.arm.mbs.arm32.bare.gnu.9.2.option.target.libraries.newlib_nano_noio" valueType="enumerated"/>
+							<option id="com.nxp.s32ds.cle.arm.mbs.arm32.bare.gnu.9.2.option.target.libraries.933777928" name="Libraries support" superClass="com.nxp.s32ds.cle.arm.mbs.arm32.bare.gnu.9.2.option.target.libraries" useByScannerDiscovery="false" value="com.nxp.s32ds.cle.arm.mbs.arm32.bare.gnu.9.2.option.target.libraries.newlib_hosted" valueType="enumerated"/>
 							<option id="com.nxp.s32ds.cle.arm.mbs.arm32.bare.option.target.mcpu.912012235" name="Arm family" superClass="com.nxp.s32ds.cle.arm.mbs.arm32.bare.option.target.mcpu" useByScannerDiscovery="false" value="com.nxp.s32ds.cle.arm.mbs.arm32.bare.option.target.mcpu.cortex-m4" valueType="enumerated"/>
 							<option id="com.nxp.s32ds.cle.arm.mbs.arm32.bare.option.target.instructionset.775672044" name="Instruction set" superClass="com.nxp.s32ds.cle.arm.mbs.arm32.bare.option.target.instructionset" useByScannerDiscovery="false" value="com.nxp.s32ds.cle.arm.mbs.arm32.bare.option.target.instructionset.thumb" valueType="enumerated"/>
 							<option id="com.nxp.s32ds.cle.arm.mbs.arm32.bare.option.target.endianness.823522198" name="Endianness" superClass="com.nxp.s32ds.cle.arm.mbs.arm32.bare.option.target.endianness" useByScannerDiscovery="false" value="com.nxp.s32ds.cle.arm.mbs.arm32.bare.option.target.endianness.little" valueType="enumerated"/>
 							<option id="com.nxp.s32ds.cle.arm.mbs.arm32.bare.option.target.fpu.abi.2049331992" name="Float ABI" superClass="com.nxp.s32ds.cle.arm.mbs.arm32.bare.option.target.fpu.abi" useByScannerDiscovery="false" value="com.nxp.s32ds.cle.arm.mbs.arm32.bare.option.target.fpu.abi.hard" valueType="enumerated"/>
 							<option id="com.nxp.s32ds.cle.arm.mbs.arm32.bare.option.target.fpu.unit.515607088" name="FPU Type" superClass="com.nxp.s32ds.cle.arm.mbs.arm32.bare.option.target.fpu.unit" useByScannerDiscovery="false" value="com.nxp.s32ds.cle.arm.mbs.arm32.bare.option.target.fpu.unit.fpv4spd16" valueType="enumerated"/>
-							<option id="com.nxp.s32ds.cle.arm.mbs.arm32.bare.option.addtools.createflash.118878663" name="Create flash image" superClass="com.nxp.s32ds.cle.arm.mbs.arm32.bare.option.addtools.createflash" useByScannerDiscovery="false" value="true" valueType="boolean"/>
+							<option id="com.nxp.s32ds.cle.arm.mbs.arm32.bare.option.target.unalignedaccess.721888033" name="Unaligned access" superClass="com.nxp.s32ds.cle.arm.mbs.arm32.bare.option.target.unalignedaccess" useByScannerDiscovery="false" value="com.nxp.s32ds.cle.arm.mbs.arm32.bare.option.target.unalignedaccess.default" valueType="enumerated"/>
+							<option id="com.nxp.s32ds.cle.arm.mbs.arm32.bare.option.addtools.createflash.1857588641" name="Create flash image" superClass="com.nxp.s32ds.cle.arm.mbs.arm32.bare.option.addtools.createflash" useByScannerDiscovery="false" value="true" valueType="boolean"/>
+							<option id="com.nxp.s32ds.cle.arm.mbs.arm32.bare.option.addtools.createlisting.1015999347" name="Create extended listing" superClass="com.nxp.s32ds.cle.arm.mbs.arm32.bare.option.addtools.createlisting" useByScannerDiscovery="false" value="false" valueType="boolean"/>
 							<targetPlatform archList="all" binaryParser="org.eclipse.cdt.core.ELF" id="cdt.managedbuild.targetPlatform.gnu.cross.64147430" isAbstract="false" osList="all" superClass="cdt.managedbuild.targetPlatform.gnu.cross"/>
 							<builder buildPath="${workspace_loc:/S32K146_4G}/Debug_FLASH" id="com.freescale.s32ds.cross.gnu.builder.466747471" keepEnvironmentInBuildfile="false" managedBuildOn="true" name="FSL Make Builder" superClass="com.freescale.s32ds.cross.gnu.builder"/>
 							<tool id="com.nxp.s32ds.cle.arm.mbs.arm32.bare.gnu.9.2.tool.c.compiler.1980082058" name="Standard S32DS C Compiler" superClass="com.nxp.s32ds.cle.arm.mbs.arm32.bare.gnu.9.2.tool.c.compiler">
-								<option defaultValue="gnu.c.optimization.level.none" id="gnu.c.compiler.option.optimization.level.1168627068" name="Optimization Level" superClass="gnu.c.compiler.option.optimization.level" useByScannerDiscovery="false" value="gnu.c.optimization.level.none" valueType="enumerated"/>
+								<option defaultValue="gnu.c.optimization.level.none" id="gnu.c.compiler.option.optimization.level.1168627068" name="Optimization Level" superClass="gnu.c.compiler.option.optimization.level" useByScannerDiscovery="false" value="gnu.c.optimization.level.size" valueType="enumerated"/>
 								<option defaultValue="gnu.c.debugging.level.max" id="gnu.c.compiler.option.debugging.level.1120041103" name="Debug Level" superClass="gnu.c.compiler.option.debugging.level" useByScannerDiscovery="false" value="gnu.c.debugging.level.max" valueType="enumerated"/>
 								<option id="com.freescale.s32ds.cross.gnu.tool.c.compiler.option.optimization.functionsections.1916093778" name="Function sections (-ffunction-sections)" superClass="com.freescale.s32ds.cross.gnu.tool.c.compiler.option.optimization.functionsections" useByScannerDiscovery="true" value="false" valueType="boolean"/>
 								<option id="com.freescale.s32ds.cross.gnu.tool.c.compiler.option.optimization.datasections.499071697" name="Data sections (-fdata-sections)" superClass="com.freescale.s32ds.cross.gnu.tool.c.compiler.option.optimization.datasections" useByScannerDiscovery="true" value="false" valueType="boolean"/>
 								<option id="com.freescale.s32ds.cross.gnu.tool.c.compiler.option.debugging.format.155687014" name="Debug format" superClass="com.freescale.s32ds.cross.gnu.tool.c.compiler.option.debugging.format" useByScannerDiscovery="true"/>
-								<option id="com.nxp.s32ds.cle.arm.mbs.arm32.bare.tool.c.compiler.option.target.libraries.334102120" name="Libraries support" superClass="com.nxp.s32ds.cle.arm.mbs.arm32.bare.tool.c.compiler.option.target.libraries" useByScannerDiscovery="false" value="com.nxp.s32ds.cle.arm.mbs.arm32.bare.tool.c.compiler.option.target.libraries.newlib_nano_noio" valueType="enumerated"/>
+								<option id="com.nxp.s32ds.cle.arm.mbs.arm32.bare.tool.c.compiler.option.target.libraries.334102120" name="Libraries support" superClass="com.nxp.s32ds.cle.arm.mbs.arm32.bare.tool.c.compiler.option.target.libraries" useByScannerDiscovery="false" value="com.nxp.s32ds.cle.arm.mbs.arm32.bare.tool.c.compiler.option.target.libraries.newlib_hosted" valueType="enumerated"/>
 								<option id="com.nxp.s32ds.cle.arm.mbs.arm32.bare.tool.c.compiler.option.target.sysroot.2141010934" name="Sysroot" superClass="com.nxp.s32ds.cle.arm.mbs.arm32.bare.tool.c.compiler.option.target.sysroot" useByScannerDiscovery="false" value="--sysroot=&quot;${S32DS_ARM32_NEWLIB_DIR}&quot;" valueType="string"/>
 								<option IS_BUILTIN_EMPTY="false" IS_VALUE_EMPTY="false" id="gnu.c.compiler.option.include.paths.203066772" name="Include paths (-I)" superClass="gnu.c.compiler.option.include.paths" useByScannerDiscovery="false" valueType="includePath">
+									<listOptionValue builtIn="false" value="&quot;${workspace_loc:/${ProjName}/code}&quot;"/>
+									<listOptionValue builtIn="false" value="&quot;${workspace_loc:/${ProjName}/code/app/lib}&quot;"/>
+									<listOptionValue builtIn="false" value="&quot;${workspace_loc:/${ProjName}/code/debug/SEGGER}&quot;"/>
+									<listOptionValue builtIn="false" value="&quot;${workspace_loc:/${ProjName}/code/debug/cm_backtrace}&quot;"/>
+									<listOptionValue builtIn="false" value="&quot;${workspace_loc:/${ProjName}/code/app}&quot;"/>
+									<listOptionValue builtIn="false" value="&quot;${workspace_loc:/${ProjName}/code/debug}&quot;"/>
+									<listOptionValue builtIn="false" value="&quot;${workspace_loc:/${ProjName}/code/driver}&quot;"/>
+									<listOptionValue builtIn="false" value="&quot;${workspace_loc:/${ProjName}/code/hal}&quot;"/>
 									<listOptionValue builtIn="false" value="../FreeRTOS/Source/include"/>
 									<listOptionValue builtIn="false" value="../RTD/include"/>
 									<listOptionValue builtIn="false" value="&quot;${workspace_loc:/${ProjName}/FreeRTOS/Source/portable/GCC/ARM_CM4F}&quot;"/>
@@ -44,7 +54,6 @@
 									<listOptionValue builtIn="false" value="${ProjDirPath}/generate/include"/>
 									<listOptionValue builtIn="false" value="${ProjDirPath}/RTD/include"/>
 									<listOptionValue builtIn="false" value="&quot;${ProjDirPath}/board&quot;"/>
-									<listOptionValue builtIn="false" value="&quot;${workspace_loc:/S32K146_4G/src}&quot;"/>
 									<listOptionValue builtIn="false" value="&quot;${PLATFORMSDK_S32K1_2021_08_S32K146_M4F_1.0.0_PATH}/SW32K1_RTD_4_4_1_0_0_D2108/Base_TS_T40D2M10I0R0/header&quot;"/>
 									<listOptionValue builtIn="false" value="&quot;${PLATFORMSDK_S32K1_2021_08_S32K146_M4F_1.0.0_PATH}/SW32K1_RTD_4_4_1_0_0_D2108/Base_TS_T40D2M10I0R0/include&quot;"/>
 									<listOptionValue builtIn="false" value="&quot;${PLATFORMSDK_S32K1_2021_08_S32K146_M4F_1.0.0_PATH}/SW32K1_RTD_4_4_1_0_0_D2108/Platform_TS_T40D2M10I0R0/include&quot;"/>
@@ -73,6 +82,7 @@
 								<option id="gnu.c.compiler.option.optimization.flags.667443811" name="Other optimization flags" superClass="gnu.c.compiler.option.optimization.flags" useByScannerDiscovery="false" value="-funsigned-char -fstack-usage -fdump-ipa-all -fomit-frame-pointer" valueType="string"/>
 								<option id="com.freescale.s32ds.cross.gnu.tool.c.compiler.option.warnings.other.92445213" name="Other warning flags" superClass="com.freescale.s32ds.cross.gnu.tool.c.compiler.option.warnings.other" useByScannerDiscovery="true" value="-Wstrict-prototypes -Wsign-compare -Werror=implicit-function-declaration -Wundef -Wdouble-promotion" valueType="string"/>
 								<option id="gnu.c.compiler.option.misc.other.1541295530" name="Other flags" superClass="gnu.c.compiler.option.misc.other" useByScannerDiscovery="false" value="-c -fno-short-enums" valueType="string"/>
+								<option id="com.nxp.s32ds.cle.arm.mbs.arm32.bare.tool.c.compiler.option.target.unalignedaccess.1102556800" name="Unaligned access" superClass="com.nxp.s32ds.cle.arm.mbs.arm32.bare.tool.c.compiler.option.target.unalignedaccess" useByScannerDiscovery="true" value="com.nxp.s32ds.cle.arm.mbs.arm32.bare.tool.c.compiler.option.target.unalignedaccess.default" valueType="enumerated"/>
 								<inputType id="cdt.managedbuild.tool.gnu.c.compiler.input.401747511" superClass="cdt.managedbuild.tool.gnu.c.compiler.input"/>
 							</tool>
 							<tool id="com.nxp.s32ds.cle.arm.mbs.arm32.bare.gnu.9.2.tool.cpp.compiler.1360480314" name="Standard S32DS C++ Compiler" superClass="com.nxp.s32ds.cle.arm.mbs.arm32.bare.gnu.9.2.tool.cpp.compiler">
@@ -81,7 +91,7 @@
 								<option id="com.freescale.s32ds.cross.gnu.tool.cpp.compiler.option.optimization.functionsections.685293854" name="Function sections (-ffunction-sections)" superClass="com.freescale.s32ds.cross.gnu.tool.cpp.compiler.option.optimization.functionsections" useByScannerDiscovery="true" value="true" valueType="boolean"/>
 								<option id="com.freescale.s32ds.cross.gnu.tool.cpp.compiler.option.optimization.datasections.605720632" name="Data sections (-fdata-sections)" superClass="com.freescale.s32ds.cross.gnu.tool.cpp.compiler.option.optimization.datasections" useByScannerDiscovery="true" value="true" valueType="boolean"/>
 								<option id="com.freescale.s32ds.cross.gnu.tool.cpp.compiler.option.debugging.format.1630021352" name="Debug format" superClass="com.freescale.s32ds.cross.gnu.tool.cpp.compiler.option.debugging.format" useByScannerDiscovery="true"/>
-								<option id="com.nxp.s32ds.cle.arm.mbs.arm32.bare.tool.cpp.compiler.option.target.libraries.992408870" name="Libraries support" superClass="com.nxp.s32ds.cle.arm.mbs.arm32.bare.tool.cpp.compiler.option.target.libraries" useByScannerDiscovery="false" value="com.nxp.s32ds.cle.arm.mbs.arm32.bare.tool.cpp.compiler.option.target.libraries.newlib_nano_noio" valueType="enumerated"/>
+								<option id="com.nxp.s32ds.cle.arm.mbs.arm32.bare.tool.cpp.compiler.option.target.libraries.992408870" name="Libraries support" superClass="com.nxp.s32ds.cle.arm.mbs.arm32.bare.tool.cpp.compiler.option.target.libraries" useByScannerDiscovery="false" value="com.nxp.s32ds.cle.arm.mbs.arm32.bare.tool.cpp.compiler.option.target.libraries.newlib_hosted" valueType="enumerated"/>
 								<option id="com.nxp.s32ds.cle.arm.mbs.arm32.bare.tool.cpp.compiler.option.target.sysroot.962316341" name="Sysroot" superClass="com.nxp.s32ds.cle.arm.mbs.arm32.bare.tool.cpp.compiler.option.target.sysroot" useByScannerDiscovery="false" value="--sysroot=&quot;${S32DS_ARM32_NEWLIB_DIR}&quot;" valueType="string"/>
 								<option IS_BUILTIN_EMPTY="false" IS_VALUE_EMPTY="false" id="gnu.cpp.compiler.option.include.paths.1429489325" name="Include paths (-I)" superClass="gnu.cpp.compiler.option.include.paths" useByScannerDiscovery="false" valueType="includePath">
 									<listOptionValue builtIn="false" value="&quot;${PLATFORMSDK_S32K1_2021_08_S32K146_M4F_1.0.0_PATH}/SW32K1_RTD_4_4_1_0_0_D2108/Base_TS_T40D2M10I0R0/header&quot;"/>
@@ -99,10 +109,11 @@
 								<option id="com.nxp.s32ds.cle.arm.mbs.arm32.bare.tool.cpp.compiler.option.target.endianness.746929375" name="Endianness" superClass="com.nxp.s32ds.cle.arm.mbs.arm32.bare.tool.cpp.compiler.option.target.endianness" useByScannerDiscovery="false" value="com.nxp.s32ds.cle.arm.mbs.arm32.bare.tool.cpp.compiler.option.target.endianness.little" valueType="enumerated"/>
 								<option id="com.nxp.s32ds.cle.arm.mbs.arm32.bare.tool.cpp.compiler.option.target.fpu.abi.876312129" name="Float ABI" superClass="com.nxp.s32ds.cle.arm.mbs.arm32.bare.tool.cpp.compiler.option.target.fpu.abi" useByScannerDiscovery="true" value="com.nxp.s32ds.cle.arm.mbs.arm32.bare.tool.cpp.compiler.option.target.fpu.abi.hard" valueType="enumerated"/>
 								<option id="com.nxp.s32ds.cle.arm.mbs.arm32.bare.tool.cpp.compiler.option.target.fpu.unit.237850730" name="FPU Type" superClass="com.nxp.s32ds.cle.arm.mbs.arm32.bare.tool.cpp.compiler.option.target.fpu.unit" useByScannerDiscovery="true" value="com.nxp.s32ds.cle.arm.mbs.arm32.bare.tool.cpp.compiler.option.target.fpu.unit.fpv4spd16" valueType="enumerated"/>
+								<option id="com.nxp.s32ds.cle.arm.mbs.arm32.bare.tool.cpp.compiler.option.target.unalignedaccess.973410709" name="Unaligned access" superClass="com.nxp.s32ds.cle.arm.mbs.arm32.bare.tool.cpp.compiler.option.target.unalignedaccess" useByScannerDiscovery="true" value="com.nxp.s32ds.cle.arm.mbs.arm32.bare.tool.cpp.compiler.option.target.unalignedaccess.default" valueType="enumerated"/>
 							</tool>
 							<tool id="com.nxp.s32ds.cle.arm.mbs.arm32.bare.gnu.9.2.tool.c.linker.1997644081" name="Standard S32DS C Linker" superClass="com.nxp.s32ds.cle.arm.mbs.arm32.bare.gnu.9.2.tool.c.linker">
 								<option id="com.freescale.s32ds.cross.gnu.tool.c.linker.option.gcsections.1484145597" name="Remove unused sections (-Xlinker --gc-sections)" superClass="com.freescale.s32ds.cross.gnu.tool.c.linker.option.gcsections" useByScannerDiscovery="false" value="false" valueType="boolean"/>
-								<option id="com.nxp.s32ds.cle.arm.mbs.arm32.bare.tool.c.linker.option.target.libraries.1478856746" name="Libraries support" superClass="com.nxp.s32ds.cle.arm.mbs.arm32.bare.tool.c.linker.option.target.libraries" useByScannerDiscovery="false" value="com.nxp.s32ds.cle.arm.mbs.arm32.bare.tool.c.linker.option.target.libraries.newlib_nano_noio" valueType="enumerated"/>
+								<option id="com.nxp.s32ds.cle.arm.mbs.arm32.bare.tool.c.linker.option.target.libraries.1478856746" name="Libraries support" superClass="com.nxp.s32ds.cle.arm.mbs.arm32.bare.tool.c.linker.option.target.libraries" useByScannerDiscovery="false" value="com.nxp.s32ds.cle.arm.mbs.arm32.bare.tool.c.linker.option.target.libraries.newlib_hosted" valueType="enumerated"/>
 								<option id="com.nxp.s32ds.cle.arm.mbs.arm32.bare.tool.c.linker.option.target.sysroot.87857832" name="Sysroot" superClass="com.nxp.s32ds.cle.arm.mbs.arm32.bare.tool.c.linker.option.target.sysroot" useByScannerDiscovery="false" value="--sysroot=&quot;${S32DS_ARM32_NEWLIB_DIR}&quot;" valueType="string"/>
 								<option id="com.nxp.s32ds.cle.arm.mbs.arm32.bare.tool.c.linker.option.target.mcpu.225477617" name="Arm family" superClass="com.nxp.s32ds.cle.arm.mbs.arm32.bare.tool.c.linker.option.target.mcpu" useByScannerDiscovery="false" value="com.nxp.s32ds.cle.arm.mbs.arm32.bare.tool.c.linker.option.target.mcpu.cortex-m4" valueType="enumerated"/>
 								<option IS_BUILTIN_EMPTY="false" IS_VALUE_EMPTY="false" id="com.freescale.s32ds.cross.gnu.tool.c.linker.option.scriptfile.1071620537" name="Script files (-T)" superClass="com.freescale.s32ds.cross.gnu.tool.c.linker.option.scriptfile" useByScannerDiscovery="false" valueType="stringList">
@@ -119,25 +130,25 @@
 									<listOptionValue builtIn="false" value="m"/>
 									<listOptionValue builtIn="false" value="gcc"/>
 								</option>
-								<option id="com.nxp.s32ds.cle.arm.mbs.arm32.bare.tool.c.linker.option.target.unalignedaccess.252706967" name="Unaligned access" superClass="com.nxp.s32ds.cle.arm.mbs.arm32.bare.tool.c.linker.option.target.unalignedaccess" useByScannerDiscovery="false" value="com.nxp.s32ds.cle.arm.mbs.arm32.bare.option.target.unalignedaccess.default" valueType="enumerated"/>
+								<option id="com.nxp.s32ds.cle.arm.mbs.arm32.bare.tool.c.linker.option.target.unalignedaccess.1492541325" name="Unaligned access" superClass="com.nxp.s32ds.cle.arm.mbs.arm32.bare.tool.c.linker.option.target.unalignedaccess" useByScannerDiscovery="false" value="com.nxp.s32ds.cle.arm.mbs.arm32.bare.tool.c.linker.option.target.unalignedaccess.default" valueType="enumerated"/>
 								<inputType id="com.freescale.s32ds.cross.gnu.tool.c.linker.inputType.scriptfile.223205338" superClass="com.freescale.s32ds.cross.gnu.tool.c.linker.inputType.scriptfile"/>
 							</tool>
 							<tool id="com.nxp.s32ds.cle.arm.mbs.arm32.bare.gnu.9.2.tool.cpp.linker.2010049876" name="Standard S32DS C++ Linker" superClass="com.nxp.s32ds.cle.arm.mbs.arm32.bare.gnu.9.2.tool.cpp.linker">
 								<option id="com.freescale.s32ds.cross.gnu.tool.cpp.linker.option.gcsections.261623701" name="Remove unused sections (-Xlinker --gc-sections)" superClass="com.freescale.s32ds.cross.gnu.tool.cpp.linker.option.gcsections" value="true" valueType="boolean"/>
-								<option id="com.nxp.s32ds.cle.arm.mbs.arm32.bare.tool.cpp.linker.option.target.libraries.2133622679" name="Libraries support" superClass="com.nxp.s32ds.cle.arm.mbs.arm32.bare.tool.cpp.linker.option.target.libraries" value="com.nxp.s32ds.cle.arm.mbs.arm32.bare.tool.cpp.linker.option.target.libraries.newlib_nano_noio" valueType="enumerated"/>
+								<option id="com.nxp.s32ds.cle.arm.mbs.arm32.bare.tool.cpp.linker.option.target.libraries.2133622679" name="Libraries support" superClass="com.nxp.s32ds.cle.arm.mbs.arm32.bare.tool.cpp.linker.option.target.libraries" value="com.nxp.s32ds.cle.arm.mbs.arm32.bare.tool.cpp.linker.option.target.libraries.newlib_hosted" valueType="enumerated"/>
 								<option id="com.nxp.s32ds.cle.arm.mbs.arm32.bare.tool.cpp.linker.option.target.sysroot.1660798688" name="Sysroot" superClass="com.nxp.s32ds.cle.arm.mbs.arm32.bare.tool.cpp.linker.option.target.sysroot" value="--sysroot=&quot;${S32DS_ARM32_NEWLIB_DIR}&quot;" valueType="string"/>
 								<option id="com.nxp.s32ds.cle.arm.mbs.arm32.bare.tool.cpp.linker.option.target.mcpu.1496913249" name="Arm family" superClass="com.nxp.s32ds.cle.arm.mbs.arm32.bare.tool.cpp.linker.option.target.mcpu" value="com.nxp.s32ds.cle.arm.mbs.arm32.bare.tool.cpp.linker.option.target.mcpu.cortex-m4" valueType="enumerated"/>
 								<option id="com.nxp.s32ds.cle.arm.mbs.arm32.bare.tool.cpp.linker.option.target.instructionset.1237595604" name="Instruction set" superClass="com.nxp.s32ds.cle.arm.mbs.arm32.bare.tool.cpp.linker.option.target.instructionset" value="com.nxp.s32ds.cle.arm.mbs.arm32.bare.tool.cpp.linker.option.target.instructionset.thumb" valueType="enumerated"/>
 								<option id="com.nxp.s32ds.cle.arm.mbs.arm32.bare.tool.cpp.linker.option.target.endianness.395475268" name="Endianness" superClass="com.nxp.s32ds.cle.arm.mbs.arm32.bare.tool.cpp.linker.option.target.endianness" value="com.nxp.s32ds.cle.arm.mbs.arm32.bare.tool.cpp.linker.option.target.endianness.little" valueType="enumerated"/>
 								<option id="com.nxp.s32ds.cle.arm.mbs.arm32.bare.tool.cpp.linker.option.target.fpu.abi.1916612348" name="Float ABI" superClass="com.nxp.s32ds.cle.arm.mbs.arm32.bare.tool.cpp.linker.option.target.fpu.abi" value="com.nxp.s32ds.cle.arm.mbs.arm32.bare.tool.cpp.linker.option.target.fpu.abi.hard" valueType="enumerated"/>
 								<option id="com.nxp.s32ds.cle.arm.mbs.arm32.bare.tool.cpp.linker.option.target.fpu.unit.437003658" name="FPU Type" superClass="com.nxp.s32ds.cle.arm.mbs.arm32.bare.tool.cpp.linker.option.target.fpu.unit" value="com.nxp.s32ds.cle.arm.mbs.arm32.bare.tool.cpp.linker.option.target.fpu.unit.fpv4spd16" valueType="enumerated"/>
-								<option id="com.nxp.s32ds.cle.arm.mbs.arm32.bare.tool.cpp.linker.option.target.unalignedaccess.945469418" name="Unaligned access" superClass="com.nxp.s32ds.cle.arm.mbs.arm32.bare.tool.cpp.linker.option.target.unalignedaccess" value="com.nxp.s32ds.cle.arm.mbs.arm32.bare.tool.cpp.linker.option.target.unalignedaccess.default" valueType="enumerated"/>
+								<option id="com.nxp.s32ds.cle.arm.mbs.arm32.bare.tool.cpp.linker.option.target.unalignedaccess.763111437" name="Unaligned access" superClass="com.nxp.s32ds.cle.arm.mbs.arm32.bare.tool.cpp.linker.option.target.unalignedaccess" value="com.nxp.s32ds.cle.arm.mbs.arm32.bare.tool.cpp.linker.option.target.unalignedaccess.default" valueType="enumerated"/>
 							</tool>
 							<tool id="com.nxp.s32ds.cle.arm.mbs.arm32.bare.tool.archiver.50914677" name="Standard S32DS Archiver" superClass="com.nxp.s32ds.cle.arm.mbs.arm32.bare.tool.archiver"/>
 							<tool id="com.nxp.s32ds.cle.arm.mbs.arm32.bare.tool.assembler.339533218" name="Standard S32DS Assembler" superClass="com.nxp.s32ds.cle.arm.mbs.arm32.bare.tool.assembler">
 								<option id="com.freescale.s32ds.cross.gnu.tool.assembler.usepreprocessor.608521688" name="Use preprocessor" superClass="com.freescale.s32ds.cross.gnu.tool.assembler.usepreprocessor" useByScannerDiscovery="false" value="true" valueType="boolean"/>
-								<option defaultValue="gnu.c.debugging.level.max" id="com.freescale.s32ds.cross.gnu.tool.assembler.option.debugging.level.935781758" name="Debug Level" superClass="com.freescale.s32ds.cross.gnu.tool.assembler.option.debugging.level" useByScannerDiscovery="false" value="gnu.c.debugging.level.max" valueType="enumerated"/>
-								<option id="com.nxp.s32ds.cle.arm.mbs.arm32.bare.tool.assembler.option.target.libraries.2115819142" name="Libraries support" superClass="com.nxp.s32ds.cle.arm.mbs.arm32.bare.tool.assembler.option.target.libraries" useByScannerDiscovery="false" value="com.nxp.s32ds.cle.arm.mbs.arm32.bare.tool.assembler.option.target.libraries.newlib_nano_noio" valueType="enumerated"/>
+								<option defaultValue="gnu.c.debugging.level.max" id="com.freescale.s32ds.cross.gnu.tool.assembler.option.debugging.level.935781758" name="Debug Level" superClass="com.freescale.s32ds.cross.gnu.tool.assembler.option.debugging.level" useByScannerDiscovery="false" valueType="enumerated"/>
+								<option id="com.nxp.s32ds.cle.arm.mbs.arm32.bare.tool.assembler.option.target.libraries.2115819142" name="Libraries support" superClass="com.nxp.s32ds.cle.arm.mbs.arm32.bare.tool.assembler.option.target.libraries" useByScannerDiscovery="false" value="com.nxp.s32ds.cle.arm.mbs.arm32.bare.tool.assembler.option.target.libraries.newlib_hosted" valueType="enumerated"/>
 								<option id="com.nxp.s32ds.cle.arm.mbs.arm32.bare.tool.assembler.option.target.sysroot.1519150514" name="Sysroot" superClass="com.nxp.s32ds.cle.arm.mbs.arm32.bare.tool.assembler.option.target.sysroot" useByScannerDiscovery="false" value="--sysroot=&quot;${S32DS_ARM32_NEWLIB_DIR}&quot;" valueType="string"/>
 								<option IS_BUILTIN_EMPTY="false" IS_VALUE_EMPTY="false" id="gnu.both.asm.option.include.paths.763521555" name="Include paths (-I)" superClass="gnu.both.asm.option.include.paths" useByScannerDiscovery="false" valueType="includePath">
 									<listOptionValue builtIn="false" value="../FreeRTOS/Source/include"/>
@@ -148,7 +159,6 @@
 									<listOptionValue builtIn="false" value="&quot;${ProjDirPath}/generate/include&quot;"/>
 									<listOptionValue builtIn="false" value="&quot;${ProjDirPath}/RTD/include&quot;"/>
 									<listOptionValue builtIn="false" value="&quot;${ProjDirPath}/board&quot;"/>
-									<listOptionValue builtIn="false" value="&quot;${workspace_loc:/S32K146_4G/src}&quot;"/>
 									<listOptionValue builtIn="false" value="&quot;${PLATFORMSDK_S32K1_2021_08_S32K146_M4F_1.0.0_PATH}/SW32K1_RTD_4_4_1_0_0_D2108/Base_TS_T40D2M10I0R0/header&quot;"/>
 									<listOptionValue builtIn="false" value="&quot;${PLATFORMSDK_S32K1_2021_08_S32K146_M4F_1.0.0_PATH}/SW32K1_RTD_4_4_1_0_0_D2108/Base_TS_T40D2M10I0R0/include&quot;"/>
 									<listOptionValue builtIn="false" value="&quot;${PLATFORMSDK_S32K1_2021_08_S32K146_M4F_1.0.0_PATH}/SW32K1_RTD_4_4_1_0_0_D2108/Platform_TS_T40D2M10I0R0/include&quot;"/>
@@ -159,12 +169,12 @@
 								<option id="com.nxp.s32ds.cle.arm.mbs.arm32.bare.tool.assembler.option.target.endianness.246218978" name="Endianness" superClass="com.nxp.s32ds.cle.arm.mbs.arm32.bare.tool.assembler.option.target.endianness" useByScannerDiscovery="false" value="com.nxp.s32ds.cle.arm.mbs.arm32.bare.tool.assembler.option.target.endianness.little" valueType="enumerated"/>
 								<option id="com.nxp.s32ds.cle.arm.mbs.arm32.bare.tool.assembler.option.target.fpu.abi.1586904906" name="Float ABI" superClass="com.nxp.s32ds.cle.arm.mbs.arm32.bare.tool.assembler.option.target.fpu.abi" useByScannerDiscovery="true" value="com.nxp.s32ds.cle.arm.mbs.arm32.bare.tool.assembler.option.target.fpu.abi.hard" valueType="enumerated"/>
 								<option id="com.nxp.s32ds.cle.arm.mbs.arm32.bare.tool.assembler.option.target.fpu.unit.1665512193" name="FPU Type" superClass="com.nxp.s32ds.cle.arm.mbs.arm32.bare.tool.assembler.option.target.fpu.unit" useByScannerDiscovery="true" value="com.nxp.s32ds.cle.arm.mbs.arm32.bare.tool.assembler.option.target.fpu.unit.fpv4spd16" valueType="enumerated"/>
-								<option id="com.nxp.s32ds.cle.arm.mbs.arm32.bare.tool.assembler.option.target.unalignedaccess.1904480425" name="Unaligned access" superClass="com.nxp.s32ds.cle.arm.mbs.arm32.bare.tool.assembler.option.target.unalignedaccess" useByScannerDiscovery="true" value="com.nxp.s32ds.cle.arm.mbs.arm32.bare.option.target.unalignedaccess.default" valueType="enumerated"/>
+								<option id="com.nxp.s32ds.cle.arm.mbs.arm32.bare.tool.assembler.option.target.unalignedaccess.423767230" name="Unaligned access" superClass="com.nxp.s32ds.cle.arm.mbs.arm32.bare.tool.assembler.option.target.unalignedaccess" useByScannerDiscovery="true" value="com.nxp.s32ds.cle.arm.mbs.arm32.bare.tool.assembler.option.target.unalignedaccess.default" valueType="enumerated"/>
 								<inputType id="cdt.managedbuild.tool.gnu.assembler.input.1966293971" superClass="cdt.managedbuild.tool.gnu.assembler.input"/>
 								<inputType id="com.freescale.s32ds.cross.gnu.tool.assembler.inputType.asmfile.1184782747" superClass="com.freescale.s32ds.cross.gnu.tool.assembler.inputType.asmfile"/>
 							</tool>
 							<tool id="com.nxp.s32ds.cle.arm.mbs.arm32.bare.tool.createflash.655082520" name="Standard S32DS Create Flash Image" superClass="com.nxp.s32ds.cle.arm.mbs.arm32.bare.tool.createflash">
-								<option id="com.freescale.s32ds.cross.gnu.option.createflash.choice.1356908850" name="Output file format (-O)" superClass="com.freescale.s32ds.cross.gnu.option.createflash.choice" useByScannerDiscovery="false" value="com.freescale.s32ds.cross.gnu.option.createflash.choice.binary" valueType="enumerated"/>
+								<option id="com.freescale.s32ds.cross.gnu.option.createflash.choice.1410567734" name="Output file format (-O)" superClass="com.freescale.s32ds.cross.gnu.option.createflash.choice" useByScannerDiscovery="false" value="com.freescale.s32ds.cross.gnu.option.createflash.choice.ihex" valueType="enumerated"/>
 							</tool>
 							<tool id="com.freescale.s32ds.cross.gnu.tool.createlisting.958717661" name="Standard S32DS Create Listing" superClass="com.freescale.s32ds.cross.gnu.tool.createlisting">
 								<option id="com.freescale.s32ds.cross.gnu.option.createlisting.source.623943954" name="Display source (--source|-S)" superClass="com.freescale.s32ds.cross.gnu.option.createlisting.source" value="true" valueType="boolean"/>
@@ -175,60 +185,13 @@
 							</tool>
 							<tool id="com.nxp.s32ds.cle.arm.mbs.arm32.bare.tool.printsize.1466716249" name="Standard S32DS Print Size" superClass="com.nxp.s32ds.cle.arm.mbs.arm32.bare.tool.printsize">
 								<option id="com.freescale.s32ds.cross.gnu.option.printsize.format.1897015732" name="Size format" superClass="com.freescale.s32ds.cross.gnu.option.printsize.format" useByScannerDiscovery="false"/>
-								<option id="com.freescale.s32ds.cross.gnu.option.printsize.hex.949405547" name="Hex" superClass="com.freescale.s32ds.cross.gnu.option.printsize.hex" useByScannerDiscovery="false" value="true" valueType="boolean"/>
+								<option id="com.freescale.s32ds.cross.gnu.option.printsize.hex.1120668054" name="Hex" superClass="com.freescale.s32ds.cross.gnu.option.printsize.hex" useByScannerDiscovery="false" value="true" valueType="boolean"/>
 							</tool>
 							<tool id="com.freescale.s32ds.cross.gnu.c.preprocessor.179719808" name="Standard S32DS C Preprocessor" superClass="com.freescale.s32ds.cross.gnu.c.preprocessor"/>
 							<tool id="com.freescale.s32ds.cross.gnu.cpp.preprocessor.2124652268" name="Standard S32DS C++ Preprocessor" superClass="com.freescale.s32ds.cross.gnu.cpp.preprocessor"/>
 							<tool id="com.freescale.s32ds.cross.gnu.disassembler.1213150737" name="Standard S32DS Disassembler" superClass="com.freescale.s32ds.cross.gnu.disassembler"/>
 						</toolChain>
 					</folderInfo>
-					<folderInfo id="com.nxp.s32ds.cle.arm.mbs.arm32.bare.gnu.9.2.exe.debug.222968549.184026838" name="/" resourcePath="src">
-						<toolChain id="com.nxp.s32ds.cle.arm.mbs.arm32.bare.gnu.9.2.toolchain.debug.1721512136" name="NXP GCC 9.2 for Arm 32-bit Bare-Metal" superClass="com.nxp.s32ds.cle.arm.mbs.arm32.bare.gnu.9.2.toolchain.debug" unusedChildren="">
-							<option id="com.nxp.s32ds.cle.arm.mbs.arm32.bare.option.addtools.printsize.1799663837.1215154337" name="Print size" superClass="com.nxp.s32ds.cle.arm.mbs.arm32.bare.option.addtools.printsize.1799663837"/>
-							<option id="com.nxp.s32ds.cle.arm.mbs.arm32.bare.gnu.9.2.option.compiler.path.434372331.1976093501" name="Path" superClass="com.nxp.s32ds.cle.arm.mbs.arm32.bare.gnu.9.2.option.compiler.path.434372331"/>
-							<option id="com.nxp.s32ds.cle.arm.mbs.arm32.bare.gnu.9.2.option.target.libraries.933777928.1579286097" name="Libraries support" superClass="com.nxp.s32ds.cle.arm.mbs.arm32.bare.gnu.9.2.option.target.libraries.933777928"/>
-							<option id="com.nxp.s32ds.cle.arm.mbs.arm32.bare.option.target.mcpu.912012235.1037033989" name="Arm family" superClass="com.nxp.s32ds.cle.arm.mbs.arm32.bare.option.target.mcpu.912012235"/>
-							<option id="com.nxp.s32ds.cle.arm.mbs.arm32.bare.option.target.instructionset.775672044.1366867053" name="Instruction set" superClass="com.nxp.s32ds.cle.arm.mbs.arm32.bare.option.target.instructionset.775672044"/>
-							<option id="com.nxp.s32ds.cle.arm.mbs.arm32.bare.option.target.endianness.823522198.621636790" name="Endianness" superClass="com.nxp.s32ds.cle.arm.mbs.arm32.bare.option.target.endianness.823522198"/>
-							<option id="com.nxp.s32ds.cle.arm.mbs.arm32.bare.option.target.fpu.abi.2049331992.1277828703" name="Float ABI" superClass="com.nxp.s32ds.cle.arm.mbs.arm32.bare.option.target.fpu.abi.2049331992"/>
-							<option id="com.nxp.s32ds.cle.arm.mbs.arm32.bare.option.target.fpu.unit.515607088.1728449705" name="FPU Type" superClass="com.nxp.s32ds.cle.arm.mbs.arm32.bare.option.target.fpu.unit.515607088"/>
-							<option id="com.nxp.s32ds.cle.arm.mbs.arm32.bare.option.addtools.createflash.118878663.1453625427" name="Create flash image" superClass="com.nxp.s32ds.cle.arm.mbs.arm32.bare.option.addtools.createflash.118878663"/>
-							<option defaultValue="true" id="com.nxp.s32ds.cle.arm.mbs.arm32.bare.option.addtools.printsize.536059321" name="Print size" superClass="com.nxp.s32ds.cle.arm.mbs.arm32.bare.option.addtools.printsize" valueType="boolean"/>
-							<targetPlatform archList="all" binaryParser="org.eclipse.cdt.core.ELF" id="cdt.managedbuild.targetPlatform.gnu.cross" isAbstract="false" osList="all" superClass="cdt.managedbuild.targetPlatform.gnu.cross"/>
-							<tool id="com.nxp.s32ds.cle.arm.mbs.arm32.bare.gnu.9.2.tool.c.compiler.560052675" name="Standard S32DS C Compiler" superClass="com.nxp.s32ds.cle.arm.mbs.arm32.bare.gnu.9.2.tool.c.compiler.1980082058">
-								<option IS_BUILTIN_EMPTY="false" IS_VALUE_EMPTY="false" id="gnu.c.compiler.option.include.paths.1843278825" name="Include paths (-I)" superClass="gnu.c.compiler.option.include.paths" useByScannerDiscovery="false" valueType="includePath">
-									<listOptionValue builtIn="false" value="../FreeRTOS/Source/include"/>
-									<listOptionValue builtIn="false" value="&quot;${workspace_loc:/${ProjName}/src}&quot;"/>
-									<listOptionValue builtIn="false" value="../RTD/include"/>
-									<listOptionValue builtIn="false" value="&quot;${workspace_loc:/${ProjName}/FreeRTOS/Source/portable/GCC/ARM_CM4F}&quot;"/>
-									<listOptionValue builtIn="false" value="&quot;${workspace_loc:/${ProjName}/FreeRTOS/Source/portable/MemMang}&quot;"/>
-									<listOptionValue builtIn="false" value="&quot;${workspace_loc:/${ProjName}/FreeRTOS/Source/portable}&quot;"/>
-									<listOptionValue builtIn="false" value="${ProjDirPath}/generate/include"/>
-									<listOptionValue builtIn="false" value="${ProjDirPath}/RTD/include"/>
-									<listOptionValue builtIn="false" value="&quot;${ProjDirPath}/board&quot;"/>
-									<listOptionValue builtIn="false" value="&quot;${PLATFORMSDK_S32K1_2021_08_S32K146_M4F_1.0.0_PATH}/SW32K1_RTD_4_4_1_0_0_D2108/Base_TS_T40D2M10I0R0/header&quot;"/>
-									<listOptionValue builtIn="false" value="&quot;${PLATFORMSDK_S32K1_2021_08_S32K146_M4F_1.0.0_PATH}/SW32K1_RTD_4_4_1_0_0_D2108/Base_TS_T40D2M10I0R0/include&quot;"/>
-									<listOptionValue builtIn="false" value="&quot;${PLATFORMSDK_S32K1_2021_08_S32K146_M4F_1.0.0_PATH}/SW32K1_RTD_4_4_1_0_0_D2108/Platform_TS_T40D2M10I0R0/include&quot;"/>
-									<listOptionValue builtIn="false" value="&quot;${PLATFORMSDK_S32K1_2021_08_S32K146_M4F_1.0.0_PATH}/SW32K1_RTD_4_4_1_0_0_D2108/Platform_TS_T40D2M10I0R0/startup/include&quot;"/>
-								</option>
-								<inputType id="cdt.managedbuild.tool.gnu.c.compiler.input.1039689634" superClass="cdt.managedbuild.tool.gnu.c.compiler.input"/>
-							</tool>
-							<tool id="com.nxp.s32ds.cle.arm.mbs.arm32.bare.gnu.9.2.tool.cpp.compiler.116130597" name="Standard S32DS C++ Compiler" superClass="com.nxp.s32ds.cle.arm.mbs.arm32.bare.gnu.9.2.tool.cpp.compiler.1360480314"/>
-							<tool id="com.nxp.s32ds.cle.arm.mbs.arm32.bare.gnu.9.2.tool.c.linker.487159850" name="Standard S32DS C Linker" superClass="com.nxp.s32ds.cle.arm.mbs.arm32.bare.gnu.9.2.tool.c.linker.1997644081"/>
-							<tool id="com.nxp.s32ds.cle.arm.mbs.arm32.bare.gnu.9.2.tool.cpp.linker.145111749" name="Standard S32DS C++ Linker" superClass="com.nxp.s32ds.cle.arm.mbs.arm32.bare.gnu.9.2.tool.cpp.linker.2010049876"/>
-							<tool id="com.nxp.s32ds.cle.arm.mbs.arm32.bare.tool.archiver.2056636183" name="Standard S32DS Archiver" superClass="com.nxp.s32ds.cle.arm.mbs.arm32.bare.tool.archiver.50914677"/>
-							<tool id="com.nxp.s32ds.cle.arm.mbs.arm32.bare.tool.assembler.1627090927" name="Standard S32DS Assembler" superClass="com.nxp.s32ds.cle.arm.mbs.arm32.bare.tool.assembler.339533218">
-								<inputType id="cdt.managedbuild.tool.gnu.assembler.input.2076767160" superClass="cdt.managedbuild.tool.gnu.assembler.input"/>
-								<inputType id="com.freescale.s32ds.cross.gnu.tool.assembler.inputType.asmfile.1052826936" superClass="com.freescale.s32ds.cross.gnu.tool.assembler.inputType.asmfile"/>
-							</tool>
-							<tool id="com.nxp.s32ds.cle.arm.mbs.arm32.bare.tool.createflash.1595471512" name="Standard S32DS Create Flash Image" superClass="com.nxp.s32ds.cle.arm.mbs.arm32.bare.tool.createflash.655082520"/>
-							<tool id="com.freescale.s32ds.cross.gnu.tool.createlisting.793819864" name="Standard S32DS Create Listing" superClass="com.freescale.s32ds.cross.gnu.tool.createlisting.958717661"/>
-							<tool id="com.nxp.s32ds.cle.arm.mbs.arm32.bare.tool.printsize.1487533066" name="Standard S32DS Print Size" superClass="com.nxp.s32ds.cle.arm.mbs.arm32.bare.tool.printsize.1466716249"/>
-							<tool id="com.freescale.s32ds.cross.gnu.c.preprocessor.1332245918" name="Standard S32DS C Preprocessor" superClass="com.freescale.s32ds.cross.gnu.c.preprocessor.179719808"/>
-							<tool id="com.freescale.s32ds.cross.gnu.cpp.preprocessor.984895870" name="Standard S32DS C++ Preprocessor" superClass="com.freescale.s32ds.cross.gnu.cpp.preprocessor.2124652268"/>
-							<tool id="com.freescale.s32ds.cross.gnu.disassembler.1599794220" name="Standard S32DS Disassembler" superClass="com.freescale.s32ds.cross.gnu.disassembler.1213150737"/>
-						</toolChain>
-					</folderInfo>
 					<fileInfo id="com.nxp.s32ds.cle.arm.mbs.arm32.bare.gnu.9.2.exe.debug.222968549.Project_Settings/Debugger" name="Debugger" rcbsApplicability="disable" resourcePath="Project_Settings/Debugger" toolsToInvoke=""/>
 					<fileInfo id="com.nxp.s32ds.cle.arm.mbs.arm32.bare.gnu.9.2.exe.debug.222968549.Project_Settings/Linker_Files" name="Linker_Files" rcbsApplicability="disable" resourcePath="Project_Settings/Linker_Files" toolsToInvoke=""/>
 					<sourceEntries>
@@ -236,8 +199,8 @@
 						<entry excluding="Linker_Files|Debugger" flags="VALUE_WORKSPACE_PATH|RESOLVED" kind="sourcePath" name="Project_Settings"/>
 						<entry flags="VALUE_WORKSPACE_PATH|RESOLVED" kind="sourcePath" name="RTD"/>
 						<entry flags="VALUE_WORKSPACE_PATH|RESOLVED" kind="sourcePath" name="board"/>
+						<entry flags="VALUE_WORKSPACE_PATH|RESOLVED" kind="sourcePath" name="code"/>
 						<entry flags="VALUE_WORKSPACE_PATH|RESOLVED" kind="sourcePath" name="generate"/>
-						<entry excluding="USER_CONFIG1.h" flags="VALUE_WORKSPACE_PATH|RESOLVED" kind="sourcePath" name="src"/>
 					</sourceEntries>
 				</configuration>
 			</storageModule>
@@ -386,7 +349,6 @@
 									<listOptionValue builtIn="false" value="&quot;${ProjDirPath}/generate/include&quot;"/>
 									<listOptionValue builtIn="false" value="&quot;${ProjDirPath}/RTD/include&quot;"/>
 									<listOptionValue builtIn="false" value="&quot;${ProjDirPath}/board&quot;"/>
-									<listOptionValue builtIn="false" value="&quot;${workspace_loc:/S32K146_4G/src}&quot;"/>
 									<listOptionValue builtIn="false" value="&quot;${PLATFORMSDK_S32K1_2021_08_S32K146_M4F_1.0.0_PATH}/SW32K1_RTD_4_4_1_0_0_D2108/Base_TS_T40D2M10I0R0/header&quot;"/>
 									<listOptionValue builtIn="false" value="&quot;${PLATFORMSDK_S32K1_2021_08_S32K146_M4F_1.0.0_PATH}/SW32K1_RTD_4_4_1_0_0_D2108/Base_TS_T40D2M10I0R0/include&quot;"/>
 									<listOptionValue builtIn="false" value="&quot;${PLATFORMSDK_S32K1_2021_08_S32K146_M4F_1.0.0_PATH}/SW32K1_RTD_4_4_1_0_0_D2108/Platform_TS_T40D2M10I0R0/include&quot;"/>
@@ -419,12 +381,11 @@
 					<fileInfo id="com.nxp.s32ds.cle.arm.mbs.arm32.bare.gnu.9.2.exe.release.95203412.Project_Settings/Debugger" name="Debugger" rcbsApplicability="disable" resourcePath="Project_Settings/Debugger" toolsToInvoke=""/>
 					<fileInfo id="com.nxp.s32ds.cle.arm.mbs.arm32.bare.gnu.9.2.exe.release.95203412.Project_Settings/Linker_Files" name="Linker_Files" rcbsApplicability="disable" resourcePath="Project_Settings/Linker_Files" toolsToInvoke=""/>
 					<sourceEntries>
+						<entry flags="LOCAL|VALUE_WORKSPACE_PATH" kind="sourcePath" name="FreeRTOS"/>
 						<entry excluding="Linker_Files|Debugger" flags="VALUE_WORKSPACE_PATH|RESOLVED" kind="sourcePath" name="Project_Settings"/>
 						<entry flags="VALUE_WORKSPACE_PATH|RESOLVED" kind="sourcePath" name="RTD"/>
 						<entry flags="VALUE_WORKSPACE_PATH|RESOLVED" kind="sourcePath" name="board"/>
 						<entry flags="VALUE_WORKSPACE_PATH|RESOLVED" kind="sourcePath" name="generate"/>
-						<entry flags="VALUE_WORKSPACE_PATH|RESOLVED" kind="sourcePath" name="src"/>
-						<entry flags="LOCAL|VALUE_WORKSPACE_PATH" kind="sourcePath" name="FreeRTOS"/>
 					</sourceEntries>
 				</configuration>
 			</storageModule>
@@ -573,7 +534,6 @@
 									<listOptionValue builtIn="false" value="&quot;${ProjDirPath}/generate/include&quot;"/>
 									<listOptionValue builtIn="false" value="&quot;${ProjDirPath}/RTD/include&quot;"/>
 									<listOptionValue builtIn="false" value="&quot;${ProjDirPath}/board&quot;"/>
-									<listOptionValue builtIn="false" value="&quot;${workspace_loc:/S32K146_4G/src}&quot;"/>
 									<listOptionValue builtIn="false" value="&quot;${PLATFORMSDK_S32K1_2021_08_S32K146_M4F_1.0.0_PATH}/SW32K1_RTD_4_4_1_0_0_D2108/Base_TS_T40D2M10I0R0/header&quot;"/>
 									<listOptionValue builtIn="false" value="&quot;${PLATFORMSDK_S32K1_2021_08_S32K146_M4F_1.0.0_PATH}/SW32K1_RTD_4_4_1_0_0_D2108/Base_TS_T40D2M10I0R0/include&quot;"/>
 									<listOptionValue builtIn="false" value="&quot;${PLATFORMSDK_S32K1_2021_08_S32K146_M4F_1.0.0_PATH}/SW32K1_RTD_4_4_1_0_0_D2108/Platform_TS_T40D2M10I0R0/include&quot;"/>
@@ -606,12 +566,11 @@
 					<fileInfo id="com.nxp.s32ds.cle.arm.mbs.arm32.bare.gnu.9.2.exe.debug.ram.800707771.Project_Settings/Debugger" name="Debugger" rcbsApplicability="disable" resourcePath="Project_Settings/Debugger" toolsToInvoke=""/>
 					<fileInfo id="com.nxp.s32ds.cle.arm.mbs.arm32.bare.gnu.9.2.exe.debug.ram.800707771.Project_Settings/Linker_Files" name="Linker_Files" rcbsApplicability="disable" resourcePath="Project_Settings/Linker_Files" toolsToInvoke=""/>
 					<sourceEntries>
+						<entry flags="LOCAL|VALUE_WORKSPACE_PATH" kind="sourcePath" name="FreeRTOS"/>
 						<entry excluding="Linker_Files|Debugger" flags="VALUE_WORKSPACE_PATH|RESOLVED" kind="sourcePath" name="Project_Settings"/>
 						<entry flags="VALUE_WORKSPACE_PATH|RESOLVED" kind="sourcePath" name="RTD"/>
 						<entry flags="VALUE_WORKSPACE_PATH|RESOLVED" kind="sourcePath" name="board"/>
 						<entry flags="VALUE_WORKSPACE_PATH|RESOLVED" kind="sourcePath" name="generate"/>
-						<entry flags="VALUE_WORKSPACE_PATH|RESOLVED" kind="sourcePath" name="src"/>
-						<entry flags="LOCAL|VALUE_WORKSPACE_PATH" kind="sourcePath" name="FreeRTOS"/>
 					</sourceEntries>
 				</configuration>
 			</storageModule>
@@ -760,7 +719,6 @@
 									<listOptionValue builtIn="false" value="&quot;${ProjDirPath}/generate/include&quot;"/>
 									<listOptionValue builtIn="false" value="&quot;${ProjDirPath}/RTD/include&quot;"/>
 									<listOptionValue builtIn="false" value="&quot;${ProjDirPath}/board&quot;"/>
-									<listOptionValue builtIn="false" value="&quot;${workspace_loc:/S32K146_4G/src}&quot;"/>
 									<listOptionValue builtIn="false" value="&quot;${PLATFORMSDK_S32K1_2021_08_S32K146_M4F_1.0.0_PATH}/SW32K1_RTD_4_4_1_0_0_D2108/Base_TS_T40D2M10I0R0/header&quot;"/>
 									<listOptionValue builtIn="false" value="&quot;${PLATFORMSDK_S32K1_2021_08_S32K146_M4F_1.0.0_PATH}/SW32K1_RTD_4_4_1_0_0_D2108/Base_TS_T40D2M10I0R0/include&quot;"/>
 									<listOptionValue builtIn="false" value="&quot;${PLATFORMSDK_S32K1_2021_08_S32K146_M4F_1.0.0_PATH}/SW32K1_RTD_4_4_1_0_0_D2108/Platform_TS_T40D2M10I0R0/include&quot;"/>
@@ -793,12 +751,11 @@
 					<fileInfo id="com.nxp.s32ds.cle.arm.mbs.arm32.bare.gnu.9.2.exe.release.ram.883375570.Project_Settings/Debugger" name="Debugger" rcbsApplicability="disable" resourcePath="Project_Settings/Debugger" toolsToInvoke=""/>
 					<fileInfo id="com.nxp.s32ds.cle.arm.mbs.arm32.bare.gnu.9.2.exe.release.ram.883375570.Project_Settings/Linker_Files" name="Linker_Files" rcbsApplicability="disable" resourcePath="Project_Settings/Linker_Files" toolsToInvoke=""/>
 					<sourceEntries>
+						<entry flags="LOCAL|VALUE_WORKSPACE_PATH" kind="sourcePath" name="FreeRTOS"/>
 						<entry excluding="Linker_Files|Debugger" flags="VALUE_WORKSPACE_PATH|RESOLVED" kind="sourcePath" name="Project_Settings"/>
 						<entry flags="VALUE_WORKSPACE_PATH|RESOLVED" kind="sourcePath" name="RTD"/>
 						<entry flags="VALUE_WORKSPACE_PATH|RESOLVED" kind="sourcePath" name="board"/>
 						<entry flags="VALUE_WORKSPACE_PATH|RESOLVED" kind="sourcePath" name="generate"/>
-						<entry flags="VALUE_WORKSPACE_PATH|RESOLVED" kind="sourcePath" name="src"/>
-						<entry flags="LOCAL|VALUE_WORKSPACE_PATH" kind="sourcePath" name="FreeRTOS"/>
 					</sourceEntries>
 				</configuration>
 			</storageModule>
@@ -824,7 +781,7 @@
 		</scannerConfigBuildInfo>
 	</storageModule>
 	<storageModule moduleId="org.eclipse.cdt.core.LanguageSettingsProviders"/>
-	<storageModule moduleId="org.eclipse.embsys" parent_project="true" register_architecture="" register_board="---  none ---" register_chip="" register_core="" register_vendor=""/>
+	<storageModule moduleId="org.eclipse.embsys" parent_project="true" register_architecture="" register_board="---  none ---" register_chip="S32K146" register_core="CortexM4F" register_vendor=""/>
 	<storageModule moduleId="refreshScope" versionNumber="2">
 		<configuration configurationName="Release_FLASH">
 			<resource resourceType="PROJECT" workspacePath="/S32K146_4G"/>

+ 1 - 0
.settings/com.freescale.s32ds.cross.sdk.support.prefs

@@ -1,2 +1,3 @@
+FILTER_SDKs_SHOW_LATEST_VERSIONS=false
 com.freescale.s32ds.cross.sdk.support.attachedSDKs=PlatformSDK_S32K1_2021_08_S32K146_M4F_1.0.0_PATH|Debug_FLASH|Release_FLASH|Debug_RAM|Release_RAM
 eclipse.preferences.version=1

+ 4 - 4
.settings/language.settings.xml

@@ -5,7 +5,7 @@
 			<provider copy-of="extension" id="org.eclipse.cdt.ui.UserLanguageSettingsProvider"/>
 			<provider-reference id="org.eclipse.cdt.core.ReferencedProjectsLanguageSettingsProvider" ref="shared-provider"/>
 			<provider-reference id="org.eclipse.cdt.managedbuilder.core.MBSLanguageSettingsProvider" ref="shared-provider"/>
-			<provider class="com.freescale.s32ds.cross.gnu.CrossGCCBuiltinSpecsDetector" console="false" env-hash="1869165178597326029" id="com.freescale.s32ds.cross.gnu.CrossGCCBuiltinSpecsDetector" keep-relative-paths="false" name="CDT S32DS Built-in Compiler Settings" parameter="${COMMAND} ${FLAGS} -E -P -v -dD &quot;${INPUTS}&quot;" prefer-non-shared="true">
+			<provider class="com.freescale.s32ds.cross.gnu.CrossGCCBuiltinSpecsDetector" console="false" env-hash="-1225283376601702587" id="com.freescale.s32ds.cross.gnu.CrossGCCBuiltinSpecsDetector" keep-relative-paths="false" name="CDT S32DS Built-in Compiler Settings" parameter="${COMMAND} ${FLAGS} -E -P -v -dD &quot;${INPUTS}&quot;" prefer-non-shared="true">
 				<language-scope id="org.eclipse.cdt.core.gcc"/>
 				<language-scope id="org.eclipse.cdt.core.g++"/>
 			</provider>
@@ -16,7 +16,7 @@
 			<provider copy-of="extension" id="org.eclipse.cdt.ui.UserLanguageSettingsProvider"/>
 			<provider-reference id="org.eclipse.cdt.core.ReferencedProjectsLanguageSettingsProvider" ref="shared-provider"/>
 			<provider-reference id="org.eclipse.cdt.managedbuilder.core.MBSLanguageSettingsProvider" ref="shared-provider"/>
-			<provider class="com.freescale.s32ds.cross.gnu.CrossGCCBuiltinSpecsDetector" console="false" env-hash="1869165178597326029" id="com.freescale.s32ds.cross.gnu.CrossGCCBuiltinSpecsDetector" keep-relative-paths="false" name="CDT S32DS Built-in Compiler Settings" parameter="${COMMAND} ${FLAGS} -E -P -v -dD &quot;${INPUTS}&quot;" prefer-non-shared="true">
+			<provider class="com.freescale.s32ds.cross.gnu.CrossGCCBuiltinSpecsDetector" console="false" env-hash="-1225283376601702587" id="com.freescale.s32ds.cross.gnu.CrossGCCBuiltinSpecsDetector" keep-relative-paths="false" name="CDT S32DS Built-in Compiler Settings" parameter="${COMMAND} ${FLAGS} -E -P -v -dD &quot;${INPUTS}&quot;" prefer-non-shared="true">
 				<language-scope id="org.eclipse.cdt.core.gcc"/>
 				<language-scope id="org.eclipse.cdt.core.g++"/>
 			</provider>
@@ -27,7 +27,7 @@
 			<provider copy-of="extension" id="org.eclipse.cdt.ui.UserLanguageSettingsProvider"/>
 			<provider-reference id="org.eclipse.cdt.core.ReferencedProjectsLanguageSettingsProvider" ref="shared-provider"/>
 			<provider-reference id="org.eclipse.cdt.managedbuilder.core.MBSLanguageSettingsProvider" ref="shared-provider"/>
-			<provider class="com.freescale.s32ds.cross.gnu.CrossGCCBuiltinSpecsDetector" console="false" env-hash="1869165178597326029" id="com.freescale.s32ds.cross.gnu.CrossGCCBuiltinSpecsDetector" keep-relative-paths="false" name="CDT S32DS Built-in Compiler Settings" parameter="${COMMAND} ${FLAGS} -E -P -v -dD &quot;${INPUTS}&quot;" prefer-non-shared="true">
+			<provider class="com.freescale.s32ds.cross.gnu.CrossGCCBuiltinSpecsDetector" console="false" env-hash="-1225283376601702587" id="com.freescale.s32ds.cross.gnu.CrossGCCBuiltinSpecsDetector" keep-relative-paths="false" name="CDT S32DS Built-in Compiler Settings" parameter="${COMMAND} ${FLAGS} -E -P -v -dD &quot;${INPUTS}&quot;" prefer-non-shared="true">
 				<language-scope id="org.eclipse.cdt.core.gcc"/>
 				<language-scope id="org.eclipse.cdt.core.g++"/>
 			</provider>
@@ -38,7 +38,7 @@
 			<provider copy-of="extension" id="org.eclipse.cdt.ui.UserLanguageSettingsProvider"/>
 			<provider-reference id="org.eclipse.cdt.core.ReferencedProjectsLanguageSettingsProvider" ref="shared-provider"/>
 			<provider-reference id="org.eclipse.cdt.managedbuilder.core.MBSLanguageSettingsProvider" ref="shared-provider"/>
-			<provider class="com.freescale.s32ds.cross.gnu.CrossGCCBuiltinSpecsDetector" console="false" env-hash="1869165178597326029" id="com.freescale.s32ds.cross.gnu.CrossGCCBuiltinSpecsDetector" keep-relative-paths="false" name="CDT S32DS Built-in Compiler Settings" parameter="${COMMAND} ${FLAGS} -E -P -v -dD &quot;${INPUTS}&quot;" prefer-non-shared="true">
+			<provider class="com.freescale.s32ds.cross.gnu.CrossGCCBuiltinSpecsDetector" console="false" env-hash="-1225283376601702587" id="com.freescale.s32ds.cross.gnu.CrossGCCBuiltinSpecsDetector" keep-relative-paths="false" name="CDT S32DS Built-in Compiler Settings" parameter="${COMMAND} ${FLAGS} -E -P -v -dD &quot;${INPUTS}&quot;" prefer-non-shared="true">
 				<language-scope id="org.eclipse.cdt.core.gcc"/>
 				<language-scope id="org.eclipse.cdt.core.g++"/>
 			</provider>

+ 0 - 2
.vscode/c_cpp_properties.json

@@ -10,8 +10,6 @@
                 "UNICODE",
                 "_UNICODE"
             ],
-            "cStandard": "c17",
-            "cppStandard": "c++17",
             "intelliSenseMode": "windows-msvc-x64"
         }
     ],

+ 2 - 0
FreeRTOS/Source/include/FreeRTOS.h

@@ -1180,6 +1180,8 @@ typedef struct xSTATIC_TCB
     uint8_t ucDummy7[ configMAX_TASK_NAME_LEN ];
     #if ( ( portSTACK_GROWTH > 0 ) || ( configRECORD_STACK_HIGH_ADDRESS == 1 ) )
         void * pxDummy8;
+	#else
+        UBaseType_t     uxSizeOfStack;      /*< Support For CmBacktrace >*/
     #endif
     #if ( portCRITICAL_NESTING_IN_TCB == 1 )
         UBaseType_t uxDummy9;

+ 6 - 2
FreeRTOS/Source/include/FreeRTOSConfig.h

@@ -28,7 +28,11 @@
 
 #ifndef FREERTOS_CONFIG_H
 #define FREERTOS_CONFIG_H
-
+//#define SEGGER_SYSTEMVIEW //选择SYSTEM查看
+#define SEGGER_RTT_PRINTF //选择RTT打印
+#ifdef SEGGER_SYSTEMVIEW
+	#include "SEGGER_SYSVIEW_FreeRTOS.h"
+#endif
 /*-----------------------------------------------------------
  * Application specific definitions.
  *
@@ -72,7 +76,7 @@ PRIORITY THAN THIS! (higher priorities are lower numeric values. */
 /* Memory allocation related definitions. */
 #define configSUPPORT_STATIC_ALLOCATION             0
 #define configSUPPORT_DYNAMIC_ALLOCATION            1
-#define configTOTAL_HEAP_SIZE                       (( size_t ) 8192*4 )
+#define configTOTAL_HEAP_SIZE                       (( size_t ) 8192*8 )
 #define configAPPLICATION_ALLOCATED_HEAP            0
 
 /* Hook function related definitions. */

+ 28 - 2
FreeRTOS/Source/tasks.c

@@ -269,7 +269,9 @@ typedef struct tskTaskControlBlock       /* The old naming convention is used to
     #if ( ( portSTACK_GROWTH > 0 ) || ( configRECORD_STACK_HIGH_ADDRESS == 1 ) )
         StackType_t * pxEndOfStack; /*< Points to the highest valid address for the stack. */
     #endif
-
+	#if( portSTACK_GROWTH <= 0)
+        UBaseType_t     uxSizeOfStack;      /*< Support For CmBacktrace >*/
+ 	 #endif
     #if ( portCRITICAL_NESTING_IN_TCB == 1 )
         UBaseType_t uxCriticalNesting; /*< Holds the critical section nesting depth for ports that do not maintain their own count in the port layer. */
     #endif
@@ -861,7 +863,7 @@ static void prvInitialiseNewTask( TaskFunction_t pxTaskCode,
 
             /* Check the alignment of the calculated top of stack is correct. */
             configASSERT( ( ( ( portPOINTER_SIZE_TYPE ) pxTopOfStack & ( portPOINTER_SIZE_TYPE ) portBYTE_ALIGNMENT_MASK ) == 0UL ) );
-
+            pxNewTCB->uxSizeOfStack = ulStackDepth;
             #if ( configRECORD_STACK_HIGH_ADDRESS == 1 )
                 {
                     /* Also record the stack's high address, which may assist
@@ -5404,3 +5406,27 @@ static void prvAddCurrentTaskToDelayedList( TickType_t xTicksToWait,
     #endif
 
 #endif /* if ( configINCLUDE_FREERTOS_TASK_C_ADDITIONS_H == 1 ) */
+
+        /*-----------------------------------------------------------*/
+        /*< Support For CmBacktrace >*/
+        uint32_t * vTaskStackAddr()
+        {
+            return pxCurrentTCB->pxStack;
+        }
+
+
+        uint32_t vTaskStackSize()
+        {
+            #if ( portSTACK_GROWTH > 0 )
+            return (pxNewTCB->pxEndOfStack - pxNewTCB->pxStack + 1);
+            #else /* ( portSTACK_GROWTH > 0 )*/
+            return pxCurrentTCB->uxSizeOfStack;
+            #endif /* ( portSTACK_GROWTH > 0 )*/
+        }
+
+
+        char * vTaskName()
+        {
+            return pxCurrentTCB->pcTaskName;
+        }
+        /*-----------------------------------------------------------*/

+ 14 - 0
Project_Settings/Linker_Files/linker_flash_s32k146.ldota

@@ -33,12 +33,19 @@ MEMORY
 {         
     int_flash_interrupts    : ORIGIN = 0x00014200, LENGTH = 0x00000400    /* 1K */    /* Do not change this section */
    /* int_flash_config        : ORIGIN = 0x00000400, LENGTH = 0x00000010    /* 16bytes */ /* Do not change this section */
+<<<<<<<< HEAD:Project_Settings/Linker_Files/linker_flash_s32k146.ldota
      int_flash               : ORIGIN = 0x00014600, LENGTH = 0x000EBA00    /* ~1.0MB */ 
 /*	int_flash_interrupts    : ORIGIN = 0x00080200, LENGTH = 0x00000400	/**/
 /*	int_flash               : ORIGIN = 0x00080600, LENGTH = 0x0007FA00	/**/
 	
 	m_flexram				: ORIGIN = 0x14000000, LENGTH = 0x00001000	
 	
+========
+    int_flash               : ORIGIN = 0x00014600, LENGTH = 0x000EBA00    /* ~1.0MB */ 
+    
+    m_flexram        		: ORIGIN = 0x10000000, LENGTH = 0x00001000
+    
+>>>>>>>> 4G_PingFeng:Project_Settings/Linker_Files/linker_flash_s32k146.ld.bak2
     int_sram_results        : ORIGIN = 0x1FFF0000, LENGTH = 0x00000100    /* 256bytes */
     int_sram                : ORIGIN = 0x1FFF0100, LENGTH = 0x0001DF00    /* ~120K */
     int_sram_stack_c0       : ORIGIN = 0x2000E000, LENGTH = 0x00001000 - 0x10    /* 4K  */
@@ -53,10 +60,17 @@ ENTRY(Reset_Handler)
 
 SECTIONS
 {
+<<<<<<<< HEAD:Project_Settings/Linker_Files/linker_flash_s32k146.ldota
    .eeeprom (NOLOAD):		
    {						
     	*(.eeprom)			
     } >m_flexram			
+========
+	.eeeprom (NOLOAD):  
+    {      
+     	*(.eeprom)   
+    } >m_flexram 
+>>>>>>>> 4G_PingFeng:Project_Settings/Linker_Files/linker_flash_s32k146.ld.bak2
     
 	.flash_interrupts :
 	{

+ 1 - 2
Project_Settings/Startup_Code/exceptions.c

@@ -81,14 +81,13 @@ void SVC_Handler(void)
 }
 #endif
 #endif
-
-
 void NMI_Handler(void)
 {
     while(TRUE){};
 }
 void HardFault_Handler(void)
 {
+	ASM_KEYWORD("bx lr");
     while(TRUE){};
 }
 void MemManage_Handler(void)

+ 1 - 1
RTD/src/Lpuart_Uart_Ip.c

@@ -1144,7 +1144,7 @@ static void Lpuart_Uart_Ip_RxIdleIrqHandler(uint32 Instance)
     	UartUserCfg->Callback(Instance, LPUART_UART_IP_EVENT_RECV_IDLE,UartUserCfg->CallbackParam);
     }
     UartState->ReceiveStatus = LPUART_UART_IP_STATUS_SUCCESS;
-	Lpuart_Uart_Ip_CompleteReceiveUsingDma(Instance);
+    Lpuart_Uart_Ip_CompleteReceiveUsingDma(Instance);
 }
 
 /*FUNCTION**********************************************************************

+ 107 - 0
code/app/AppGlobalVar.c

@@ -0,0 +1,107 @@
+/*
+ * @Author: chenjie
+ * @Date: 2022-06-06
+ * @LastEditTime: 2022-10-27
+ * @LastEditors: chenjie
+ * @Description: 
+ * @FilePath: \S32K146_4G\code\app\AppGlobalVar.c
+ * Copyright (c) 2022 by chenjie, All Rights Reserved.
+ */
+
+/*
+ * AppGlobalVar.c
+ *应用层全局变量
+ *  Created on: 2022119
+ *      Author: QiXiang_CHENJIE
+ */
+#include "AppGlobalVar.h"
+
+#ifdef APP_RELEASE
+const char WebSiteName[] = "\"iotp.fast-fun.cn\"";
+uint16 WebSitePort = 8712;
+#else
+const char WebSiteName[] = "\"nas.fast-fun.cn\"";
+uint16 WebSitePort = 8812;
+#endif
+
+#define defaultSn "SPFPFL264S226D001"
+const uint32 AppSwVersion = 0x00000105;
+
+const uint8 DataModuleType = 0x02;//01=NB,02-4G
+const uint16 HwVersion = 0x001;
+const uint32 BlSwVersion = 0x00000001;
+const uint32 DrvSwVersion = 0x00000001;
+const uint8 BmsManuFacture = 0xff;
+const uint8 BmsInfo = 0xff;
+
+uint8 TcpbattSN[BATT_SN_LEN] = {0x31};
+volatile uint32 TimerCounter = 0; // ms单位
+uint8 Fota_update_flag = 0;
+uint8 Fota_error_flag = 0;
+/*GPS*/
+QueueHandle_t GpsDataQueueHandle;
+sint16 xyzData[3] = {0};
+/*Hal_Can*/
+uint8 CanIf_u8TxConfirmCnt = 0U;
+boolean CanIf_bTxFlag = false;
+uint8 CanIf_u8RxIndicationCnt = 0U;
+boolean CanIf_bRxFlag = false;
+QueueHandle_t CanRecvQueueHandle;
+
+/*TCP相关变量*/
+bool TcpSysReboot = 1; // tcp无法联网时,重启使能
+char ImeiNum[15] = {0};
+char IccidNum[20] = {0};
+uint8 CSQValue = 0;
+sint8 SocketId = -1; // 联网状态
+sint8 RegChkRet = 0; // 驻网状态
+char WebSiteIp[20] = {0};
+uint8 TcpWorkState = 0;
+
+#define EEP_START_SEC_VAR_INIT_8_NO_CACHEABLE
+#include "Eep_MemMap.h"
+AppConfigBody AppConfigInfo = {false, true, {defaultSn}, {0}};
+#define EEP_STOP_SEC_VAR_INIT_8_NO_CACHEABLE
+#include "Eep_MemMap.h"
+
+/*以下变量均为串口协议相关变量*/
+#ifdef APP_UART0_ENABLE
+AppDataBody AppDataInfo = {BMS_CELLNUM, BMS_TEMPNUM};
+uint16 avrgCellVol = 0; // 平均电压
+uint16 bmsHwVersion = 0;
+uint32 bmsSwVersion = 0;
+uint16 battCellU[BMS_CELLNUM]; // 电池电压
+uint16 battI = 10000;              // BMS电流(tcp上传)
+uint16 battPackVol = 0;        // bms电压
+uint16 maxCellVol = 0;         // 最大单体电压
+uint16 minCellVol = 0;         // 最小单体电压
+// uint16 socd_pct_vcuSoc = 0;		 // soc(tcp上传,精度0.1)
+// uint16 sohd_pct_bcuSoh = 0;		 // soh(tcp上传,精度0.1)
+uint32 battBalanceoInfo = 0;     //
+uint32 battProtectState = 0;     // bms保护状态
+uint32 battWarningState = 0;     // bms告警状态
+uint8 AvgBattTemp = 0;           // 平均单体温度
+uint8 battCellTemp[BMS_TEMPNUM]; // 电池温度
+uint8 Battdesigncap = 0;         // 电池包设计容量
+uint8 battHeatEnableState = 0;   // bms加热状态
+uint8 battMOSSwitchState = 0;    // bms mos开关状态
+uint8 battSOC = 0;               // bms发送soc
+uint8 battSOH = 0;               // bms发送soh
+uint8 battWorkState = 0;         // bms工作状态
+uint8 BmsOtherTemp = 0;          // BMS其他温度,没有其他温度,为0
+uint8 maxCellTemp = 0;           // 最大单体温度
+uint8 minCellTemp = 0;           // 最小单体温度
+uint8 OtherTemp = 0;             // 通讯模块其他温度
+uint8 battHeatState = 0;
+uint8 battFanState = 0;
+uint8 battRelayState = 0;
+uint8 battConverState = 0;
+uint8 battSeparateEnable = 0;
+uint8 battSeparateCtlState = 0;
+uint8 battSeparateState = 0;
+uint16 ErrorArray[5] = {0};
+uint32 meterAllPwr[2] = {0};
+uint32 meterPosPwr[2] = {0};
+uint32 meterNegPwr[2] = {0};
+uint32 BattTempR[4] = {0xFF};
+#endif

+ 119 - 0
code/app/AppGlobalVar.h

@@ -0,0 +1,119 @@
+/*** 
+ * @Author: chenjie
+ * @Date: 2022-06-06
+ * @LastEditTime: 2022-10-27
+ * @LastEditors: chenjie
+ * @Description: 
+ * @FilePath: \S32K146_4G\code\app\AppGlobalVar.h
+ * @Copyright (c) 2022 by chenjie, All Rights Reserved.
+ */
+
+#ifndef APPGLOBALVAR_H_
+#define APPGLOBALVAR_H_
+
+#define APP_UART0_ENABLE
+//#define APP_CAN_ENABLE
+
+#include "hal_adapter.h"
+#define BATT_SN_LEN 17
+extern const uint32 AppSwVersion;
+extern const uint8 DataModuleType;
+extern const uint16 HwVersion;
+extern const uint32 BlSwVersion;
+extern const uint32 DrvSwVersion;
+extern const uint8 BmsManuFacture;
+extern const uint8 BmsInfo;
+extern bool TcpSysReboot;
+extern uint8 TcpbattSN[BATT_SN_LEN];
+extern uint8 VIN[17];
+extern volatile uint32 TimerCounter;
+extern uint8 Fota_update_flag;
+extern uint8 Fota_error_flag;
+typedef struct
+{
+	uint8 RealLen;
+	uint8 *DataPtr;
+} QueueDataTrans_Type;
+/*GPS*/
+extern QueueHandle_t GpsDataQueueHandle;
+extern sint16 xyzData[3];
+/*Hal_Can*/
+extern uint8 CanIf_u8TxConfirmCnt;
+extern boolean CanIf_bTxFlag;
+extern uint8 CanIf_u8RxIndicationCnt;
+extern boolean CanIf_bRxFlag;
+extern QueueHandle_t CanRecvQueueHandle;
+
+extern uint8 CSQValue;
+extern sint8 SocketId;
+extern sint8 RegChkRet;
+extern char WebSiteIp[20];
+extern const char WebSiteName[];
+extern uint16 WebSitePort;
+extern char ImeiNum[15];
+extern char IccidNum[20];
+extern uint8 TcpWorkState;
+typedef struct _AppEppType
+{
+	uint32 battDischrgAccCap;  //单位maH
+	uint32 battDischrgAccEnrg; //单位wh
+	uint16 battCycleTimes;
+} AppEppBody;
+typedef struct _AppConfigType
+{
+	bool appSaveFlg;
+	bool eolFlg;
+	uint8 deviceSn[17];
+	AppEppBody AppDataInfo;
+	uint8 re[20];
+} AppConfigBody;
+extern AppConfigBody AppConfigInfo;
+#define BMS_CELLNUM 120
+#define BMS_TEMPNUM 40
+typedef struct _AppDataType
+{
+	uint8 BattCellCount;
+	uint8 BattTempCount;
+} AppDataBody;
+extern AppDataBody AppDataInfo;
+extern uint16 avrgCellVol;
+extern uint16 battCellU[BMS_CELLNUM];
+extern uint16 battI;
+extern uint16 bmsHwVersion;
+extern uint32 bmsSwVersion;
+extern uint16 battPackVol;
+extern uint16 maxCellVol;
+extern uint16 minCellVol;
+// extern uint16 socd_pct_vcuSoc;
+// extern uint16 sohd_pct_bcuSoh;
+extern uint32 battBalanceoInfo;
+extern uint32 battProtectState;
+extern uint32 battWarningState;
+extern uint8 AvgBattTemp;
+extern uint8 battCellTemp[BMS_TEMPNUM];
+extern uint8 Battdesigncap;
+extern uint8 battHeatEnableState;
+extern uint8 battMOSSwitchState;
+extern uint8 battSOC;
+extern uint8 battSOH;
+extern uint8 battWorkState;
+extern uint8 BmsOtherTemp;
+extern uint8 maxCellTemp;
+extern uint8 minCellTemp;
+extern uint8 OtherTemp;
+extern uint8 battHeatState;
+extern uint8 battFanState;
+extern uint8 battRelayState;
+extern uint8 battConverState;
+extern uint8 battSeparateEnable;
+extern uint8 battSeparateCtlState;
+extern uint8 battSeparateState;
+extern uint16 ErrorArray[5];
+extern uint32 meterAllPwr[2];
+extern uint32 meterPosPwr[2];
+extern uint32 meterNegPwr[2];
+extern uint32 BattTempR[4];
+extern uint32 battAccEnrg;
+extern uint32 battAccCap;
+extern uint16 battAccUseTimes;
+#endif /* APPGLOBALVAR_H_ */

+ 456 - 0
code/app/AppTaskCan.c

@@ -0,0 +1,456 @@
+/*
+ * @Author: chenjie
+ * @Date: 2022-06-06
+ * @LastEditTime: 2022-10-27
+ * @LastEditors: chenjie
+ * @Description: 
+ * @FilePath: \S32K146_4G\code\app\AppTaskCan.c
+ * Copyright (c) 2022 by chenjie, All Rights Reserved.
+ */
+#include "AppTaskCan.h"
+static uint8 BattSendFlg = 0;
+static void UDSAnsFunc(uint8 *rawData);
+static void UdsAns(bool PosFlg,uint8 UdsService,uint8 UdsSubService,uint8 Idx,uint8 *AnsData,uint8 AnsDataLen);
+static void BattSendFunc(void);
+static void vCanRxCallback(TimerHandle_t pxTimer)
+{
+	uint32 ulTimerID;
+	ulTimerID = (uint32)pvTimerGetTimerID(pxTimer);
+	if(ulTimerID==0)
+	{
+		Can_MainFunction_Read();
+	}
+}
+void CanTask(void *pvParameters)
+{
+	uint32 timerCounterNow = 0;
+	(void)pvParameters;
+	CanIf_bRxFlag = false;
+	Can_Msg_Type_Data CanRxMsg;
+	CanRecvQueueHandle = xQueueCreate(100, sizeof(Can_Msg_Type_Data));
+	TimerHandle_t monitorTimer1ms;
+	monitorTimer1ms = xTimerCreate("monitor1ms",1,pdTRUE,(void *)0,vCanRxCallback);
+	xTimerStart(monitorTimer1ms,0);
+	BaseType_t ret = pdFALSE;
+	GsensorInit();
+	while(1)
+	{
+		do
+		{
+			memset(&CanRxMsg, 0, sizeof(CanRxMsg));
+			ret = xQueueReceive(CanRecvQueueHandle, &CanRxMsg, 1);
+			if (ret == pdPASS)
+			{
+				if(IsJumptoBootloader(CanRxMsg.id, CanRxMsg.data))
+				{
+					DoRoutinePositiveAnswer();
+					RequestEnterBootloader();
+					SystemSoftwareReset();
+					break;
+				}
+				else
+				{
+					BcuDecodeFunction(CanRxMsg.id,CanRxMsg.data);//can协议解析
+				}
+			}
+		}while(ret == pdPASS);
+		SL_SC7A20_Read_XYZ_Data(xyzData);
+		if(BattSendFlg)
+		{
+			BattSendFunc();
+		}
+		if((TimerCounter - timerCounterNow)>=100)
+		{
+			timerCounterNow = TimerCounter;
+			//温度采集
+			ADC_ReadValue();
+		}
+	}
+}
+//注意解码超限问题
+void BcuDecodeFunction(uint32 ID, uint8 *rawData)
+{
+	switch(ID)
+		{
+		case 0x1C00EDEA:
+		{
+			UDSAnsFunc(rawData);
+			break;
+		}
+		}
+}
+static void UDSAnsFunc(uint8 *rawData)
+{
+	static uint8 UdsStates = 1;
+	uint8 Data[8] = {0};
+	memcpy(Data,rawData,8);
+	uint8 UdsService = 0;
+	uint8 UdsSubService = 0;
+	UdsService = Data[0];
+	UdsSubService = Data[1];
+	uint8 AnsData[24]={0};
+	static uint8 deviceSnRecvFlg = 0;
+	switch(UdsService)
+	{
+	case 0x10://模式切换
+	{
+		if(UdsSubService==0x01)
+		{
+			UdsStates = 0x01;//关闭UDS诊断
+			UdsAns(true,UdsService,UdsSubService,0x00,NULL,0);
+		}
+		else if(UdsSubService==0x02)
+		{
+			if(UdsStates==0x01||UdsStates==0x02)
+			{
+				UdsStates = 0x02;//打开UDS诊断
+				UdsAns(true,UdsService,UdsSubService,0x00,NULL,0);
+			}
+			else
+			{
+				UdsAns(false,UdsService,UdsSubService,0x00,NULL,0);
+			}
+		}
+		break;
+	}
+	case 0x11://控制
+	{
+		if(UdsStates==0x02)
+		{
+			switch(UdsSubService)
+			{
+				case 0x01://重启
+				{
+					AnsData[0] = AppSwVersion>>24;
+					AnsData[1] = AppSwVersion>>16;
+					AnsData[2] = AppSwVersion>>8;
+					AnsData[3] = AppSwVersion>>0;
+					UdsAns(true,UdsService,UdsSubService,0x00,AnsData,4);
+					AppConfigInfo.appSaveFlg = true;
+					vTaskDelay(pdMS_TO_TICKS(1000));
+					SystemSoftwareReset();
+					break;
+				}
+				default:
+				{
+					UdsAns(false,UdsService,UdsSubService,0x00,NULL,0);
+					break;
+				}
+			}
+		}
+		else
+		{
+			UdsAns(false,UdsService,UdsSubService,0x00,NULL,0);
+		}
+		break;
+	}
+	case 0x22://查询
+	{
+		if(UdsStates==0x02)
+		{
+			switch(UdsSubService)
+			{
+			case 0x01://版本号查询
+			{
+				AnsData[0] = AppSwVersion>>24;
+				AnsData[1] = AppSwVersion>>16;
+				AnsData[2] = AppSwVersion>>8;
+				AnsData[3] = AppSwVersion>>0;
+				UdsAns(true,UdsService,UdsSubService,0x00,AnsData,4);
+				break;
+			}
+			case 0x02://SN号码查询
+			{
+				memcpy(AnsData,AppConfigInfo.deviceSn,17);
+				for(uint8 i=0;i<5;i++)
+				{
+					UdsAns(true,UdsService,UdsSubService,i,&AnsData[i*4],4);
+				}
+				break;
+			}
+			case 0x03://ICCID查询
+			{
+				memcpy(AnsData,IccidNum,20);
+				for(uint8 i=0;i<5;i++)
+				{
+					UdsAns(true,UdsService,UdsSubService,i,&AnsData[i*4],4);
+				}
+				break;
+			}
+			case 0x04://IMEI查询
+			{
+				memcpy(AnsData,ImeiNum,15);
+				for(uint8 i=0;i<4;i++)
+				{
+					UdsAns(true,UdsService,UdsSubService,i,&AnsData[i*4],4);
+				}
+				break;
+			}
+			case 0x05://驻网状态查询
+			{
+				AnsData[0]= RegChkRet;
+				UdsAns(true,UdsService,UdsSubService,0x00,AnsData,1);
+				break;
+			}
+			case 0x06://联网状态查询
+			{
+				AnsData[0]= SocketId;
+				UdsAns(true,UdsService,UdsSubService,0x00,AnsData,1);
+				break;
+			}
+			case 0x07://定位信息查询
+			{
+				GPSInfo GpsRecvData;
+				if (xQueuePeek(GpsDataQueueHandle, &GpsRecvData, 0) == pdPASS)
+				{
+					AnsData[0] = GpsRecvData.locateMark;
+					AnsData[4] = GpsRecvData.longitude[0];
+					AnsData[5] = GpsRecvData.longitude[1];
+					AnsData[6] = GpsRecvData.longitude[2];
+					AnsData[7] = GpsRecvData.longitude[3];
+					AnsData[8] = GpsRecvData.latitude[0];
+					AnsData[9] = GpsRecvData.latitude[1];
+					AnsData[10] = GpsRecvData.latitude[2];
+					AnsData[11] = GpsRecvData.latitude[3];
+					AnsData[12] = GpsRecvData.altitude[0];
+					AnsData[13] = GpsRecvData.altitude[1];
+					AnsData[14] = GpsRecvData.satelliteNum;
+					for(uint8 i=0;i<4;i++)
+					{
+						UdsAns(true,UdsService,UdsSubService,i,&AnsData[i*4],4);
+					}
+					break;
+				}
+				else
+				{
+					AnsData[0]=0xFF;
+					UdsAns(true,UdsService,UdsSubService,0x00,AnsData,1);
+				}
+				break;
+			}
+			case 0x08://温度检测查询
+			{
+				UdsAns(true,UdsService,UdsSubService,0x00,AnsData,1);
+				break;
+			}
+			case 0x09://电池信息查询
+			{
+				UdsAns(true,UdsService,UdsSubService,0x00,AnsData,1);
+				BattSendFlg = 1;
+				break;
+			}
+			case 0x0A://三轴数据查询
+			{
+				AnsData[0] = xyzData[0]>>8;
+				AnsData[1] = xyzData[0]>>0;
+				AnsData[2] = xyzData[1]>>8;
+				AnsData[3] = xyzData[1]>>0;
+				AnsData[4] = xyzData[2]>>8;
+				AnsData[5] = xyzData[2]>>0;
+				for(uint8 i=0;i<2;i++)
+				{
+					UdsAns(true,UdsService,UdsSubService,i,&AnsData[i*4],4);
+				}
+				break;
+			}
+			}//switch
+		}//if
+		else
+		{
+			UdsAns(false,UdsService,UdsSubService,0x00,NULL,0);
+		}
+		break;
+	}
+	case 0x2E://写入
+	{
+		if(UdsStates==0x02)
+		{
+			switch(UdsSubService)
+			{
+			case 0x01:
+			{
+				setbit(deviceSnRecvFlg,Data[3]);
+				if(Data[3]<0x04)
+				{
+					memcpy(&AppConfigInfo.deviceSn[Data[3]*4],&Data[4],4);
+					UdsAns(true,UdsService,UdsSubService,0x00,&Data[3],1);
+				}
+				else if(Data[3]==0x04)
+				{
+					memcpy(&AppConfigInfo.deviceSn[Data[3]*4],&Data[4],1);
+					UdsAns(true,UdsService,UdsSubService,0x00,&Data[3],1);
+				}
+				if(deviceSnRecvFlg==0x1F)
+				{
+					deviceSnRecvFlg = 0;
+					AppConfigInfo.appSaveFlg = true;
+					AppConfigInfo.eolFlg=true;
+				}
+				break;
+			}
+			}
+		}
+		else
+		{
+			UdsAns(false,UdsService,UdsSubService,0x00,NULL,0);
+		}
+		break;
+	}
+	case 0x31://控制
+	{
+		if(UdsStates==0x02)
+		{
+
+		}
+		else
+		{
+			UdsAns(false,UdsService,UdsSubService,0x00,NULL,0);
+		}
+		break;
+	}
+	default:
+		break;
+	}
+	return;
+}
+static void UdsAns(bool PosFlg,uint8 UdsService,uint8 UdsSubService,uint8 Idx,uint8 *AnsData,uint8 AnsDataLen)
+{
+	Can_Msg_Type CanTxMsg;
+	uint32 CanAnsId = 0x1C00EAED;
+	uint8 SendData[8] = {0};
+	if(PosFlg)
+	{
+		SendData[0] = 0x78;
+		SendData[1] = UdsService;
+		SendData[2] = UdsSubService;
+		SendData[3] = Idx;
+		if(AnsData!=NULL&&AnsDataLen!=0x00)
+		{
+			memcpy(&SendData[4],AnsData,AnsDataLen);
+		}
+	}
+	else
+	{
+		SendData[0] = 0x7F;
+		SendData[1] = UdsService;
+		SendData[2] = UdsSubService;
+		SendData[3] = 0x00;
+	}
+	CanTxMsg.id = CanAnsId;
+	CanTxMsg.idFrame = CAN_EXTENDED_ID_TYPE;
+	CanTxMsg.sdu = SendData;
+	CanTxMsg.length = 8;
+	CanIf_SendMessage(CAN1, CanTxMsg);
+}
+static void BattSendFunc(void)
+{
+	Can_Msg_Type CanTxMsg;
+	uint32 CanAnsId = 0;
+	uint8 SendData[8] = {0};
+	static uint8 SendStep = 0;
+	static uint8 SendCounter = 0;
+	switch(SendStep)
+	{
+	case 0x00:
+	{
+		SendStep++;
+		break;
+	}
+	case 0x01:
+	{
+		CanAnsId = 0x1C01EAED;
+		SendData[0] =  battHeatState;
+		SendData[1] =  battFanState;
+		SendData[2] =  battRelayState;
+		SendData[3] =  battConverState;
+		SendStep++;
+		break;
+	}
+	case 0x02:
+	{
+		uint16 ErrorTemp ;
+		ErrorTemp = GetErrorNum(ErrorArray,sizeof(ErrorArray)/2);
+		CanAnsId = 0x1C09EAED;
+		SendData[0] =  battWorkState;
+		SendData[1] =  ErrorTemp>>8;
+		SendData[2] =  ErrorTemp;
+		SendData[3] =  0;
+		SendData[4] =  0;
+		SendData[5] =  0;
+		SendData[6] =  0;
+		SendData[7] =  0;
+		SendStep++;
+		break;
+	}
+	case 0x03:
+	{
+		CanAnsId = 0x1C0AEAED;
+		uint16 SocTemp = battSOC*10;
+		SendData[0] =  battI>>8;
+		SendData[1] =  battI;
+		SendData[2] =  battPackVol>>8;
+		SendData[3] =  battPackVol;
+		SendData[4] =  SocTemp>>8;
+		SendData[5] =  SocTemp;
+		SendData[6] =  battSOH;
+		SendData[7] =  battMOSSwitchState;
+		SendStep++;
+		break;
+	}
+	case 0x04:
+	{
+		CanAnsId = 0x1C10EAED + (SendCounter<<16);
+		if((SendCounter*8 + 7)>BMS_TEMPNUM)
+		{
+			SendCounter = 0;
+			SendStep++;
+			break;
+		}
+		else
+		{
+			SendData[0] =  battCellTemp[SendCounter*8 + 0];
+			SendData[1] =  battCellTemp[SendCounter*8 + 1];
+			SendData[2] =  battCellTemp[SendCounter*8 + 2];
+			SendData[3] =  battCellTemp[SendCounter*8 + 3];
+			SendData[4] =  battCellTemp[SendCounter*8 + 4];
+			SendData[5] =  battCellTemp[SendCounter*8 + 5];
+			SendData[6] =  battCellTemp[SendCounter*8 + 6];
+			SendData[7] =  battCellTemp[SendCounter*8 + 7];
+		}
+		break;
+	}
+	case 0x05:
+	{
+		CanAnsId = 0x1CA0EAED + (SendCounter<<16);
+		if((SendCounter*4 + 3)>BMS_CELLNUM)
+		{
+			SendCounter = 0;
+			SendStep++;
+			break;
+		}
+		else
+		{
+			SendData[0] =  battCellU[SendCounter*4 + 0]>>8;
+			SendData[1] =  battCellU[SendCounter*4 + 0];
+			SendData[2] =  battCellU[SendCounter*4 + 1]>>8;
+			SendData[3] =  battCellU[SendCounter*4 + 1];
+			SendData[4] =  battCellU[SendCounter*4 + 2]>>8;
+			SendData[5] =  battCellU[SendCounter*4 + 2];
+			SendData[6] =  battCellU[SendCounter*4 + 3]>>8;
+			SendData[7] =  battCellU[SendCounter*4 + 3];
+		}
+		break;
+	}
+	default:
+	{
+		SendStep = 0;
+		BattSendFlg = 0;
+		break;
+	}
+	}
+	CanTxMsg.id = CanAnsId;
+	CanTxMsg.idFrame = CAN_EXTENDED_ID_TYPE;
+	CanTxMsg.sdu = SendData;
+	CanTxMsg.length = 8;
+	CanIf_SendMessage(CAN1, CanTxMsg);
+}

+ 8 - 7
src/AppTaskCan.h → code/app/AppTaskCan.h

@@ -1,8 +1,11 @@
-/*
- * AppTaskCan.h
- *
- *  Created on: 2022Äê2ÔÂ13ÈÕ
- *      Author: QiXiang_CHENJIE
+/*** 
+ * @Author: chenjie
+ * @Date: 2022-06-06
+ * @LastEditTime: 2022-10-27
+ * @LastEditors: chenjie
+ * @Description: 
+ * @FilePath: \S32K146_4G\code\app\AppTaskCan.h
+ * @Copyright (c) 2022 by chenjie, All Rights Reserved.
  */
 
 #ifndef APPTASKCAN_H_
@@ -14,7 +17,5 @@
 #include "Hal_Wdg.h"
 #include "AppTaskGps.h"
 void BcuDecodeFunction(uint32 ID, uint8 *rawData);
-void BcuRxDiagnose(void);
-void BcuRxMsgSetInvalidValue(uint32 ID);
 void CanTask(void *pvParameters);
 #endif /* APPTASKCAN_H_ */

+ 26 - 26
src/AppTaskGps.c → code/app/AppTaskGps.c

@@ -1,32 +1,32 @@
 /*
- * AppTaskGps.c
- *
- *  Created on: 2022216
- *      Author: QiXiang_CHENJIE
+ * @Author: chenjie
+ * @Date: 2022-06-06
+ * @LastEditTime: 2022-10-27
+ * @LastEditors: chenjie
+ * @Description: 
+ * @FilePath: \undefinedd:\1_WorkFiles\1_Device\2_4G_G1\2_SW\workspace\S32K146_4G\code\app\AppTaskGps.c
+ * Copyright (c) 2022 by chenjie, All Rights Reserved.
  */
+
 #include "AppTaskGps.h"
 void strdel(char *str, char c);
 uint32 location_handle(char *in1);
 void GpsDataDecode(uint8 *msg);
+uint8 GpsRecvPtr[1024];
 void GpsTask(void *pvParameters)
 {
 	(void)pvParameters;
-	GpsDataQueueHandle = xQueueCreate(1, sizeof(GPSInfo));//酗僅峈1符褫眕埰勍葡迡
-	Dio_WriteChannel(DioConf_DioChannel_PTD1_GPIO_OUT_MCU_GPS_POW_EN, STD_ON);//GPS羲儂
+	GpsDataQueueHandle = xQueueCreate(1, sizeof(GPSInfo));//�踹漲銝�1�滚虾隞亙�霈貉���
+	Dio_WriteChannel(DioConf_DioChannel_PTD1_GPIO_OUT_MCU_GPS_POW_EN, STD_ON);//GPS撘���
 	uint16 pReadLen = 0;
-	uint8 *UartRecvPtr=NULL;
 	while(1)
 	{
-		vTaskDelay(pdMS_TO_TICKS(10));
-		UART_Receive_Data(UART_LPUART2,&UartRecvPtr,&pReadLen,1000);
+		vTaskDelay(pdMS_TO_TICKS(100));
+		memset(GpsRecvPtr,0,sizeof(GpsRecvPtr));
+		UART_Receive_Data(UART_LPUART2,GpsRecvPtr,&pReadLen,1000);
 		if(pReadLen>0)
 		{
-			GpsDataDecode(UartRecvPtr);
-			if(UartRecvPtr != NULL)
-			{
-				free(UartRecvPtr);
-			}
-			UartRecvPtr = NULL;
+			GpsDataDecode(GpsRecvPtr);
 		}
 	}
 }
@@ -44,10 +44,10 @@ void GpsDataDecode(uint8 *msg)
 	uint32 longitude;
 	uint16 direction;
 	memset((uint8 *)&GpsInfoData, 0x00, sizeof(GPSInfo));
-	p = strtok(msg, delim); //蔚陓洘輛俴煦賃
+	p = strtok(msg, delim); //撠�縑�航�銵����
 	p2 = strtok(NULL, delim);
-	p = strtok(p, ","); //硐龰菴1俴腔陓洘RMC
-	//p = strtok(temp,",");//耀攜聆彸
+	p = strtok(p, ","); //�芸�蝚�1銵𣬚�靽⊥�RMC
+	//p = strtok(temp,",");//璅⊥�瘚贝�
 	if (strcmp(p, "$GNRMC") == 0)
 	{
 		index = 0;
@@ -59,11 +59,11 @@ void GpsDataDecode(uint8 *msg)
 		}
 		if (index > 5 && strcmp(databuffer[2], "A") == 0)
 		{
-			GpsInfoData.locateMark = 0x01; //衄虴ㄛ陲冪ㄛ控帠迡隅
+			GpsInfoData.locateMark = 0x01; //�㗇�嚗䔶�蝏𧶏��㛖漪�坔�
 			strdel(databuffer[3], '.');
 			strdel(databuffer[5], '.');
 			strdel(databuffer[7], '.');
-			speedtemp = atol(databuffer[7]) * 1852 / 1e5; //誹遙呾等弇ㄛ1誹=1.852km藩苤奀
+			speedtemp = atol(databuffer[7]) * 1852 / 1e5; //��揢蝞堒�雿㵪�1��=1.852km瘥誩���
 			GpsInfoData.speed[0] = (speedtemp >> 8) & 0xFF;
 			GpsInfoData.speed[1] = speedtemp & 0xFF;
 			latitude = location_handle(databuffer[3]);
@@ -76,7 +76,7 @@ void GpsDataDecode(uint8 *msg)
 			GpsInfoData.longitude[1] = longitude >> 16;
 			GpsInfoData.longitude[2] = longitude >> 8;
 			GpsInfoData.longitude[3] = longitude;
-			if (speedtemp >= 50) //湮衾5km/h符怀堤源弇
+			if (speedtemp >= 50) //憭找�5km/h�滩��箸䲮雿�
 			{
 				direction = atol(databuffer[8]);
 				GpsInfoData.direction[0] = direction >> 8;
@@ -95,15 +95,15 @@ void GpsDataDecode(uint8 *msg)
 //				{
 //					AppDataInfo.AccMileage = 0;
 //				}
-//			}濛數爵最腔濛樓
+//			}蝝航恣�𣬚���敞��
 		}
 //		GpsInfoData.AccMileage[0] = AppDataInfo.AccMileage >> 24;
 //		GpsInfoData.AccMileage[1] = AppDataInfo.AccMileage >> 16;
 //		GpsInfoData.AccMileage[2] = AppDataInfo.AccMileage >> 8;
 //		GpsInfoData.AccMileage[3] = AppDataInfo.AccMileage;
 	}
-	p2 = strtok(p2, ","); //硐龰菴2俴腔陓洘GGA
-	memset(databuffer, 0x30, 20);
+	p2 = strtok(p2, ","); //�芸�蝚�2銵𣬚�靽⊥�GGA
+	memset(databuffer, 0x00, 20);
 	if (strcmp(p2, "$GNGGA") == 0)
 	{
 		index = 0;
@@ -115,11 +115,11 @@ void GpsDataDecode(uint8 *msg)
 		}
 		if (index > 9 && (strcmp(databuffer[6], "1") == 0 || strcmp(databuffer[6], "2") == 0))
 		{
-			GpsInfoData.satelliteNum = atol(databuffer[7]); //怹陎杅醴迡⻌
+			GpsInfoData.satelliteNum = atol(databuffer[7]); //�急��啁𤌍�坔�
 			strdel(databuffer[9], '.');
 			uint16 alt = 0;
 			alt = atol(databuffer[9]) / 10 + 1000;
-			GpsInfoData.altitude[0] = alt >> 8; //漆匿
+			GpsInfoData.altitude[0] = alt >> 8; //瘚瑟�
 			GpsInfoData.altitude[1] = alt;
 			strdel(databuffer[2], '.');
 			strdel(databuffer[4], '.');

+ 8 - 5
src/AppTaskGps.h → code/app/AppTaskGps.h

@@ -1,8 +1,11 @@
-/*
- * AppTaskGps.h
- *
- *  Created on: 2022Äê2ÔÂ16ÈÕ
- *      Author: QiXiang_CHENJIE
+/*** 
+ * @Author: chenjie
+ * @Date: 2022-06-06
+ * @LastEditTime: 2022-10-27
+ * @LastEditors: chenjie
+ * @Description: 
+ * @FilePath: \S32K146_4G\code\app\AppTaskGps.h
+ * @Copyright (c) 2022 by chenjie, All Rights Reserved.
  */
 
 #ifndef APPTASKGPS_H_

+ 72 - 0
code/app/AppTaskMain.c

@@ -0,0 +1,72 @@
+/*
+ * @Author: chenjie
+ * @Date: 2022-06-06
+ * @LastEditTime: 2022-10-27
+ * @LastEditors: chenjie
+ * @Description: 
+ * @FilePath: \S32K146_4G\code\app\AppTaskMain.c
+ * Copyright (c) 2022 by chenjie, All Rights Reserved.
+ */
+
+#include "AppTaskMain.h"
+#include "hal_fls.h"
+static void vTimerCallback(TimerHandle_t pxTimer);
+void MainTask(void *pvParameters)
+{
+	(void)pvParameters;
+	TimerHandle_t monitorTimer;
+	monitorTimer = xTimerCreate("monitor",10,pdTRUE,(void *)0,vTimerCallback);
+	xTimerStart(monitorTimer,0);
+	TimerHandle_t monitorTimer1ms;
+	monitorTimer1ms = xTimerCreate("monitor1ms",1,pdTRUE,(void *)0,vTimer1msCallback);
+	xTimerStart(monitorTimer1ms,0);
+	uint32 *eppromAddStart = 0x14000000;
+	if(*(uint8 *)(eppromAddStart)==0xff)
+	{
+		HAL_EEP_Write(0,(uint8 *)&AppConfigInfo,sizeof(AppConfigInfo));
+	}
+	HAL_EEP_Read(0,(uint8 *)&AppConfigInfo,sizeof(AppConfigInfo));
+	while(1)
+	{
+		vTaskDelay(pdMS_TO_TICKS(10));
+		if(HAL_Is100msTickTimeout())
+		{
+			if(IsFeedWdg == TRUE)
+			{
+				WATCHDOG_HAL_Feed();
+			}
+		}
+		if(TimerCounter%1000==0)
+		{
+			if(AppConfigInfo.eolFlg==true)
+			{
+				Dio_FlipChannel(DioConf_DioChannel_PTE9_GPIO_OUT_MCU_LED5);
+			}
+			else
+			{
+				Dio_WriteChannel(DioConf_DioChannel_PTE9_GPIO_OUT_MCU_LED5, STD_ON);
+			}
+		}
+		if(AppConfigInfo.appSaveFlg)
+		{
+			AppConfigInfo.appSaveFlg = false;
+			HAL_EEP_Write(0,(uint8 *)&AppConfigInfo,sizeof(AppConfigInfo));
+		}
+		if(Fota_update_flag || Fota_error_flag)//升级指令发出,进行重启,或者FTP服务器出现问题,进行重启
+		{
+			//重启前保存数据
+			AppConfigInfo.appSaveFlg = false;
+			HAL_EEP_Write(0,(uint8 *)&AppConfigInfo,sizeof(AppConfigInfo));
+			SystemSoftwareReset();
+		}
+	}
+}
+static void vTimerCallback(TimerHandle_t pxTimer)
+{
+	uint32 ulTimerID;
+	ulTimerID = (uint32)pvTimerGetTimerID(pxTimer);
+	if(ulTimerID==0)
+	{
+		TimerCounter = TimerCounter + 10;
+	}
+}

+ 19 - 0
code/app/AppTaskMain.h

@@ -0,0 +1,19 @@
+/*** 
+ * @Author: chenjie
+ * @Date: 2022-06-06
+ * @LastEditTime: 2022-10-27
+ * @LastEditors: chenjie
+ * @Description: 
+ * @FilePath: \S32K146_4G\code\app\AppTaskMain.h
+ * @Copyright (c) 2022 by chenjie, All Rights Reserved.
+ */
+
+#ifndef APPTASKMAIN_H_
+#define APPTASKMAIN_H_
+#include "hal_adapter.h"
+#include "AppFunclib.h"
+#include "AppGlobalVar.h"
+#include "Hal_Wdg.h"
+void MainTask(void *pvParameters);
+
+#endif /* APPTASKMAIN_H_ */

+ 250 - 0
code/app/AppTaskUart0.c

@@ -0,0 +1,250 @@
+/*
+ * @Author: chenjie
+ * @Date: 2022-06-06
+ * @LastEditTime: 2022-10-27
+ * @LastEditors: chenjie
+ * @Description: 
+ * @FilePath: \S32K146_4G\code\app\AppTaskUart0.c
+ * Copyright (c) 2022 by chenjie, All Rights Reserved.
+ */
+#include "AppTaskUart0.h"
+#ifdef APP_UART0_ENABLE
+static process_Uart0 gProcess_Uart0_Task = PROCESS_UART_STATE_IDLE;
+#define PROC_UART0_STATE_SWITCH(a) (gProcess_Uart0_Task = a)
+bool bmsCellInfoDecode(uint8 *dataPtr);
+bool bmsTempInfoDecode(uint8 *dataPtr);
+bool bmsOtherInfoDecode(uint8 *dataPtr);
+void UartBusReadDataFunc(uint16 RegAddrBegin, uint16 Reg_Num, bool (*decodeFunc)(uint8 *dataPtr));
+// void battDataCalFunc(void);
+static uint16 UartNoDataReadCounter = 0;
+void Uart0Task(void *pvParameters)
+{
+	(void)pvParameters;
+	UartAnsType UartAnsData;
+	uint16 pReadLen = 0;
+	static uint8 writecounter = 0;
+	while (1)
+	{
+		switch (gProcess_Uart0_Task)
+		{
+		case PROCESS_UART_STATE_IDLE:
+		{
+			vTaskDelay(pdMS_TO_TICKS(10));
+			if ((TimerCounter % 1000) == 0 && 1)
+			{
+				PROC_UART0_STATE_SWITCH(PROCESS_UART_STATE_READ);
+			}
+			else if (TimerCounter % 100 == 0)
+			{
+				PROC_UART0_STATE_SWITCH(PROCESS_UART_STATE_WRITE);
+			}
+			break;
+		}
+		case PROCESS_UART_STATE_READ:
+		{
+			/*01 04 00 01 00 38 A0 18
+			01 04 00 64 00 78 B1 F7
+			01 04 01 90 00 28 F1 C5 */
+			Dio_FlipChannel(DioConf_DioChannel_PTE1_GPIO_OUT_MCU_LED2);
+			//其他参数读取
+			UartBusReadDataFunc(0x01, 0x38, bmsOtherInfoDecode);
+			//电压读取
+			UartBusReadDataFunc(0x64, 120, bmsCellInfoDecode);
+			//温度读取
+			UartBusReadDataFunc(0x190, 40, bmsTempInfoDecode);
+			//没有读到数据时的默认值
+			if (UartNoDataReadCounter > 10)
+			{
+				memset((uint8 *)&UartAnsData, 0x00, sizeof(UartAnsData));
+				bmsCellInfoDecode(UartAnsData.Data);
+				bmsTempInfoDecode(UartAnsData.Data);
+				bmsOtherInfoDecode(UartAnsData.Data);
+				PutErrorNum(ErrorArray, sizeof(ErrorArray) / 2, 1);
+				vTaskDelay(pdMS_TO_TICKS(2000));
+			}
+			PROC_UART0_STATE_SWITCH(PROCESS_UART_STATE_IDLE);
+			break;
+		}
+		case PROCESS_UART_STATE_WRITE:
+		{
+			if (battSeparateEnable) //最多重新写5次
+			{
+				uint16 RegAddress = 0;
+				uint16 CRC_chk_buffer = 0;
+				uint8 WriteData[2] = {0x00, 0x00};
+				uint8 UartRecvBuffer[10];
+				if (!battSeparateCtlState)
+				{
+					WriteData[1] = 0x55;
+				}
+				else
+				{
+					WriteData[1] = 0xAA;
+				}
+				RegAddress = 100;
+				UartWriteMsgType Uart_Write_Msg;
+				Uart_Write_Msg.Bms_Address = BMS_ADDRESS_CODE;
+				Uart_Write_Msg.Bms_Funcode = UART_WRITE_CODE;
+				Uart_Write_Msg.Reg_Begin_H = RegAddress >> 8;
+				Uart_Write_Msg.Reg_Begin_L = RegAddress;
+				Uart_Write_Msg.Reg_Num_H = 0x00;
+				Uart_Write_Msg.Reg_Num_L = 0x01;
+				Uart_Write_Msg.Data_Count = 0x02; //要写入的字节数
+				memcpy(Uart_Write_Msg.Data, WriteData, 2);
+				CRC_chk_buffer = crc_chk((uint8 *)&Uart_Write_Msg, sizeof(Uart_Write_Msg) - 2);
+				Uart_Write_Msg.CRC_L = CRC_chk_buffer;
+				Uart_Write_Msg.CRC_H = CRC_chk_buffer >> 8;
+				UART_Query_Data(UART_LPUART0, UART_LPUART0, (uint8 *)&Uart_Write_Msg, sizeof(Uart_Write_Msg), UartRecvBuffer, &pReadLen, 500);
+				if (pReadLen > 3 && *(UartRecvBuffer + 1) == 0x10)
+				{
+					writecounter = 0;
+					battSeparateEnable = 0;
+				}
+				else
+				{
+					writecounter++;
+				}
+			}
+			if (writecounter >= 5)
+			{
+				battSeparateEnable = 0;
+				writecounter = 0;
+			}
+			PROC_UART0_STATE_SWITCH(PROCESS_UART_STATE_IDLE);
+			break;
+		}
+		case PROCESS_UART_STATE_SLEEP:
+		{
+			break;
+		}
+		default:
+			break;
+		}
+	}
+}
+bool bmsCellInfoDecode(uint8 *dataPtr) //电压数据解码
+{
+	for (uint8 i = 0; i < BMS_CELLNUM; i++)
+	{
+		battCellU[i] = ((dataPtr[(0x00 + i) * 2] << 8) | dataPtr[(0x00 + i) * 2 + 1]);
+	}
+	return true;
+}
+bool bmsTempInfoDecode(uint8 *dataPtr) //温度数据解码
+{
+	for (uint8 i = 0; i < BMS_TEMPNUM; i++)
+	{
+		battCellTemp[i] = dataPtr[(0x00 + i) * 2 + 1];
+	}
+	return true;
+}
+bool bmsOtherInfoDecode(uint8 *dataPtr) //其他数据解析
+{
+	uint16 Batt_current;
+	battPackVol = (dataPtr[(0x00) * 2]) << 8 | (dataPtr[(0x00) * 2 + 1]);
+	Batt_current = (dataPtr[(0x01) * 2] << 8) | (dataPtr[(0x01) * 2 + 1]);
+	if(battPackVol==0)
+	{
+		Batt_current=16000;
+	}
+	battI = Batt_current - 6000; //电流偏移量不同
+	battSOC = dataPtr[(0x02) * 2 + 1];
+	battSOH = dataPtr[(0x03) * 2 + 1];
+	battWorkState = (dataPtr[(0x06) * 2 + 1]) & 0x03; //电池状态(原始数据),3表示开路,2表示放电,1表示充电
+	switch (battWorkState)							  //电池状态(上传数据),0表示开路,1表示放电,2表示充电
+	{
+	case 0:
+		battWorkState = 0;
+		break;
+	case 1:
+		battWorkState = 2;
+		break;
+	case 2:
+		battWorkState = 1;
+		break;
+	case 3:
+		battWorkState = 0;
+		break;
+	default:
+		break;
+	}
+	maxCellVol = (dataPtr[(0x13) * 2] << 8) | dataPtr[(0x13) * 2 + 1];
+	minCellVol = (dataPtr[(0x16) * 2] << 8) | dataPtr[(0x16) * 2 + 1];
+	AppConfigInfo.AppDataInfo.battDischrgAccEnrg = (dataPtr[(0x34) * 2] << 8) | dataPtr[(0x34) * 2 + 1];
+	AppConfigInfo.AppDataInfo.battCycleTimes = AppConfigInfo.AppDataInfo.battDischrgAccEnrg / 49000;
+	return true;
+}
+void UartBusReadDataFunc(uint16 RegAddrBegin, uint16 Reg_Num, bool (*decodeFunc)(uint8 *dataPtr))
+{
+	// argv In
+	UartQueryType Uart0AskMsg;
+	uint16 ReadLen1 = 0;
+	uint16 ReadLenTar = 0;
+	uint8 ReadDelayCounter = 0;
+	uint16 CRC_chk_buffer = 0;
+	uint16 pReadLen;
+	UartAnsType UartAnsData;
+	uint8 UartDataRecv[256];
+	pReadLen = 0;
+	Uart0AskMsg.Bms_Address = BMS_ADDRESS_CODE;
+	Uart0AskMsg.Bms_Funcode = UART_READ_CODE;
+	Uart0AskMsg.Reg_Begin_H = RegAddrBegin >> 8;
+	Uart0AskMsg.Reg_Begin_L = RegAddrBegin;
+	Uart0AskMsg.Reg_Num_H = Reg_Num >> 8;
+	Uart0AskMsg.Reg_Num_L = Reg_Num;
+	CRC_chk_buffer = crc_chk((uint8 *)&Uart0AskMsg, 6);
+	Uart0AskMsg.CRC_L = CRC_chk_buffer;
+	Uart0AskMsg.CRC_H = CRC_chk_buffer >> 8;
+	UART_Send_Data(UART_LPUART0, (uint8 *)&Uart0AskMsg, sizeof(Uart0AskMsg), 1000);
+	ReadLenTar = (Reg_Num)*2 + 5;
+	memset((uint8 *)&UartAnsData, 0x00, sizeof(UartAnsData));
+	while (1)
+	{
+		UART_Receive_Data(UART_LPUART0, UartDataRecv, &pReadLen, 100);
+		if (pReadLen > 2)
+		{
+			memcpy((uint8 *)&UartAnsData + ReadLen1, UartDataRecv, pReadLen);
+			ReadLen1 = ReadLen1 + pReadLen;
+		}
+		else
+		{
+			ReadDelayCounter++;
+		}
+		if (ReadLen1 >= ReadLenTar)
+		{
+			ReadDelayCounter = 0;
+			pReadLen = ReadLen1;
+			ReadLen1 = 0;
+			break;
+		}
+		if (ReadDelayCounter >= 20)
+		{
+			ReadDelayCounter = 0;
+			pReadLen = 0;
+			ReadLen1 = 0;
+			break;
+		}
+	}
+	if (pReadLen > 0)
+	{
+		uint16 CrcChkGet = 0xffff;
+		uint16 CrcChkCal = 0x0000;
+		CrcChkCal = crc_chk((uint8 *)&UartAnsData, pReadLen - 2);
+		CrcChkGet = ((uint16)(UartAnsData.Data[pReadLen - 1 - 3]) << 8) | ((uint16)(UartAnsData.Data[pReadLen - 2 - 3]));
+		if (CrcChkCal == CrcChkGet)
+		{
+			decodeFunc(UartAnsData.Data);
+			UartNoDataReadCounter = 0;
+		}
+		else
+		{
+			UartNoDataReadCounter++;
+		}
+	}
+	else
+	{
+		UartNoDataReadCounter++;
+	}
+}
+
+#endif

+ 15 - 0
code/app/AppTaskUart0.h

@@ -0,0 +1,15 @@
+/*** 
+ * @Author: chenjie
+ * @Date: 2022-06-06
+ * @LastEditTime: 2022-10-27
+ * @LastEditors: chenjie
+ * @Description: 
+ * @FilePath: \undefinedd:\1_WorkFiles\1_Device\2_4G_G1\2_SW\workspace\S32K146_4G\code\app\AppTaskUart0.h
+ * @Copyright (c) 2022 by chenjie, All Rights Reserved.
+ */
+#ifndef APPTASKUART0_H_
+#define APPTASKUART0_H_
+#include "hal_adapter.h"
+#include "AppFunclib.h"
+#include "AppGlobalVar.h"
+#endif /* APPTASKUART0_H_ */

+ 1653 - 0
code/app/AppTaskUart1.c

@@ -0,0 +1,1653 @@
+/*
+ * @Author: chenjie
+ * @Date: 2022-06-06
+ * @LastEditTime: 2022-10-27
+ * @LastEditors: chenjie
+ * @Description: 
+ * @FilePath: \S32K146_4G\code\app\AppTaskUart1.c
+ * Copyright (c) 2022 by chenjie, All Rights Reserved.
+ */
+#include "AppTaskUart1.h"
+#include "hal_fls.h"
+
+const ATCmdFunc Atcmdfunc[] = {
+	{AT_CMD_TEST, "AT\r\n", at_callbackFunc},
+	{AT_ATE0, "ATE0\r\n", at_callbackFunc},
+	{AT_SIMREADY, "AT+CPIN?\r\n", at_callbackFunc},
+	{AT_GETICCID, "AT+CICCID\r\n", at_callbackFunc},
+	{AT_CGREG, "AT+CGREG?\r\n", at_callbackFunc},
+	{AT_CSQ, "AT+CSQ\r\n", at_callbackFunc},
+	{AT_NETOPEN, "AT+NETOPEN\r\n", at_callbackFunc},
+	{AT_CGIP, "AT+CDNSGIP=", at_callbackFunc},
+	//{AT_CONNECT, "AT+CIPOPEN=0,\"TCP\",\"120.26.68.165\",14319\r\n", at_callbackFunc},
+	{AT_CONNECT, "AT+CIPOPEN=", at_callbackFunc},
+	{AT_CONNECTCHK, "AT+CIPOPEN?\r\n", at_callbackFunc},
+	{AT_SEND, "AT+CIPSEND=", at_callbackFunc},
+	{AT_DISCON, "AT+CIPCLOSE=0\r\n", at_callbackFunc},
+	{AT_NETCLOSE, "AT+NETCLOSE\r\n", at_callbackFunc},
+	{AT_CGNSSPWR,"AT+CGNSSPWR=1\r\n",at_callbackFunc}};
+
+static process_Tcp gProcess_Tcp_Task = PROCESS_TCP_IDLE;
+#define PROC_TCP_STATE_SWITCH(a) (gProcess_Tcp_Task = a)
+void InitFunc(void);
+sint8 TcpConnectFunc(sint8 *ConnectId);
+sint8 TcpDataSendFunc(sint8 ConnectId);
+sint8 TcpRegisterChkFunc(void);
+void TcpDataEncode(uint32 *PtrSendAddr, uint16 *SendLen);
+void GetUtc8Time(UTC8TimeType *UTC8TimeTcp);
+static void AtcmdTransmit(sint8 CmdIdx, uint8 *SetValuePtr, uint16 SetValueLen, sint8 *retFunc,uint16 timeout);
+static void TcpDataInfoRecvHandle(uint8 *DataRecv, uint16 DataRecvLen);
+static void GetCSQValue(uint8 *out);
+void Fota_Ftp(uint8 *dataPtrIn);
+void tcpUdsFunc(uint8 *Ptr,uint8 *AnsPtr);
+static void vTimer1000msCallback(TimerHandle_t pxTimer);
+bool SendTimerFlg = false;
+static uint32 TcpSendTimeCounter = 0;
+void Uart_4G_Task(void *pvParameters)
+{
+	(void)pvParameters;
+	uint32 RecvTimerDelay = 0;
+	uint8 UartRecvPtr[512];
+	volatile uint16 tcpErrorCounter = 0;
+	uint16 pReadLen = 0;
+	// 4G开机
+	Dio_LevelType _4G_Status = 0; // 0-关机,1-开机
+	Dio_WriteChannel(DioConf_DioChannel_PTA6_GPIO_OUT_MCU_4G_POW_EN, STD_ON);
+	vTaskDelay(pdMS_TO_TICKS(50));
+	Dio_WriteChannel(DioConf_DioChannel_PTA7_GPIO_OUT_MCU_4G_PWRKEY, STD_ON);
+	vTaskDelay(pdMS_TO_TICKS(50));
+	AtcmdDelayRecvFunc(UART_LPUART1,(char *)("SMS DONE"),30000);
+	Dio_WriteChannel(DioConf_DioChannel_PTA7_GPIO_OUT_MCU_4G_PWRKEY, STD_OFF);
+	_4G_Status = Dio_ReadChannel(DioConf_DioChannel_PTB1_GPIO_IN_MCU_4G_STATUS);
+	InitFunc(); // 4G模块初始化,注:AT同步不通过,没有进行次数判定及跳转
+	TimerHandle_t monitorTimer1000ms;
+	monitorTimer1000ms = xTimerCreate("monitor1000ms",1000,pdTRUE,(void *)0,vTimer1000msCallback);
+	xTimerStart(monitorTimer1000ms,0);
+	for (;;)
+	{
+		switch (gProcess_Tcp_Task)
+		{
+		case PROCESS_TCP_IDLE: //空闲状态
+		{
+			UART_Receive_Data(UART_LPUART1, UartRecvPtr, &pReadLen, 100);//100ms检测
+			if (SocketId < 0)
+			{
+				PROC_TCP_STATE_SWITCH(PROCESS_TCP_REGCHK);
+			}
+			else if (pReadLen>0)
+			{
+				PROC_TCP_STATE_SWITCH(PROCESS_TCP_RECV);
+				RecvTimerDelay = TimerCounter;
+			}
+			else if (AppConfigInfo.eolFlg == 1 && TcpWorkState==0 && SendTimerFlg==true)
+			{
+				SendTimerFlg = false;
+				PROC_TCP_STATE_SWITCH(PROCESS_TCP_SEND);
+			}
+			if((TimerCounter-RecvTimerDelay)>=30000 && TcpWorkState==1)//10s内没有命令下发,进行正常发送任务
+			{
+				TcpWorkState = 0;
+			}
+			break;
+		}
+		case PROCESS_TCP_ATSYS:
+		{
+			sint8 ATRet = -1;
+			AtcmdTransmit(AT_CMD_TEST, NULL, 0, &ATRet,100);
+			if (ATRet == 0)
+			{
+				PROC_TCP_STATE_SWITCH(PROCESS_TCP_IDLE);
+			}
+			else
+			{
+				PROC_TCP_STATE_SWITCH(PROCESS_TCP_ERROR);
+			}
+			break;
+		}
+		case PROCESS_TCP_REGCHK: //驻网检查,包括SIM,CPIN检查,ICCID获取
+		{
+			RegChkRet = TcpRegisterChkFunc();
+			if (RegChkRet > 0) //检查通过,SIM卡已就绪,已进行驻网
+			{
+				PROC_TCP_STATE_SWITCH(PROCESS_TCP_CONNECT);
+			}
+			else
+			{
+				PROC_TCP_STATE_SWITCH(PROCESS_TCP_ERROR);
+			}
+			break;
+		}
+		case PROCESS_TCP_CONNECT: //网络连接,包括域名转换
+		{
+			if (SocketId < 0)
+			{
+				sint8 ConnectRet = 0;
+				ConnectRet = TcpConnectFunc(&SocketId);
+				if (ConnectRet > 0)
+				{
+					PROC_TCP_STATE_SWITCH(PROCESS_TCP_IDLE);
+				}
+				else
+				{
+					PROC_TCP_STATE_SWITCH(PROCESS_TCP_ERROR);
+				}
+			}
+			break;
+		}
+		case PROCESS_TCP_SEND: //网络数据发送
+		{
+			sint8 SendRet = -1;
+			SendRet = TcpDataSendFunc(SocketId);
+			if (SendRet == 0)
+			{
+				PROC_TCP_STATE_SWITCH(PROCESS_TCP_IDLE);
+				tcpErrorCounter = 0;
+			}
+			else
+			{
+				SocketId = -1;
+				PROC_TCP_STATE_SWITCH(PROCESS_TCP_ERROR);
+			}
+			break;
+		}
+		case PROCESS_TCP_RECV: //网络数据接收,100ms空闲状态下即可接收
+		{
+			Dio_FlipChannel(DioConf_DioChannel_PTE0_GPIO_OUT_MCU_LED1);
+
+			if (pReadLen > 0 && SocketId >= 0)
+			{
+				TcpDataInfoRecvHandle(UartRecvPtr, pReadLen);
+			}
+			PROC_TCP_STATE_SWITCH(PROCESS_TCP_IDLE);
+			break;
+		}
+		case PROCESS_TCP_HEART: //心跳包发送
+		{
+			break;
+		}
+		case PROCESS_TCP_SLEEP: //网络休眠状态
+		{
+			break;
+		}
+		case PROCESS_TCP_ERROR: //错误状态
+		{
+			vTaskDelay(pdMS_TO_TICKS(1000));
+			tcpErrorCounter++;
+			if(tcpErrorCounter>60&&TcpSysReboot == 1)//无法驻网或者联网
+			{
+				Dio_WriteChannel(DioConf_DioChannel_PTA7_GPIO_OUT_MCU_4G_PWRKEY, STD_ON);
+				vTaskDelay(pdMS_TO_TICKS(2500));
+				Dio_WriteChannel(DioConf_DioChannel_PTA7_GPIO_OUT_MCU_4G_PWRKEY, STD_OFF);
+				vTaskDelay(pdMS_TO_TICKS(2500));
+				tcpErrorCounter = 0;
+			}
+			PROC_TCP_STATE_SWITCH(PROCESS_TCP_IDLE);
+			break;
+		}
+		}
+	}
+}
+static void vTimer1000msCallback(TimerHandle_t pxTimer)
+{
+	uint32 ulTimerID;
+	ulTimerID = (uint32)pvTimerGetTimerID(pxTimer);
+	if(ulTimerID==0)
+	{
+		SendTimerFlg = true;
+		TcpSendTimeCounter++;
+	}
+}
+sint8 TcpDataSendFunc(sint8 ConnectId)
+{
+	sint8 outValue = -1;
+	uint32 pSendDataAddr = 0;
+	uint16 DataSendLen = 0;
+	TcpDataEncode(&pSendDataAddr, &DataSendLen); //数据组包,malloc申请在里面,pSendData指向申请的地址
+	if (DataSendLen == 0)
+	{
+		return 0; //暂时无数据可以发
+	}
+	outValue = tcpipConnectionSend(ConnectId, (uint8 *)pSendDataAddr, DataSendLen); //发送函数
+	if (pSendDataAddr != 0)
+	{
+		vPortFree((uint8 *)(pSendDataAddr));
+	}
+	pSendDataAddr = 0;
+	return outValue;
+}
+sint8 tcpipConnectionSend(uint8 TcpConnectId, uint8 *SendDataPtr, uint16 SendDataLen)
+{
+	sint8 outValue = -1;
+	uint8  sendErrConuter= 0;
+	uint16 ReadLen = 0;
+	char AtCmdSend[30] = {0};
+	uint8 AtCmdSendTotalLen = 0;
+	uint8 UartRecvPtr[128];//暂存buffer改大
+	uint8 ret = 0;
+	sprintf(AtCmdSend, "AT+CIPSEND=%d,%d\r\n", TcpConnectId, SendDataLen);
+	AtCmdSendTotalLen = mstrlen(AtCmdSend);
+	while(outValue!=0&&sendErrConuter<3)
+	{
+		ret = UART_Query_Data(UART_LPUART1, UART_LPUART1, (uint8 *)AtCmdSend, AtCmdSendTotalLen, UartRecvPtr, &ReadLen, 1000);
+		if (((ret==0)&&(ReadLen>0)&&((uint8 *)strstr((char *)UartRecvPtr, (char *)(">"))))||1)//此IF条件默认通过
+		{
+			UART_Send_Data(UART_LPUART1, (uint8 *)SendDataPtr, SendDataLen, 1000);
+			sint8 ret = AtcmdDelayRecvFunc(UART_LPUART1,(char *)("+CIPSEND"),2000);
+			if (ret==0)
+			{
+				outValue = 0;
+			}
+			else
+			{
+				outValue = -2;
+				sendErrConuter++;
+			}
+		}
+		else
+		{
+			outValue = -1;
+			sendErrConuter++;
+		}
+	}
+	return outValue;
+}
+sint8 TcpConnectFunc(sint8 *ConnectId)
+{
+	uint8 ConnectStep = 0;
+	sint8 ChkState = 0;
+	sint8 ATRet = -1;
+	uint8 UartRecvPtr[100];
+	while (1)
+	{
+		switch (ConnectStep)
+		{
+		case 0: // AT指令同步
+		{
+			char *ATCmdSend = (char *)("ATE0\r\n");
+			uint8 ATCmdSendLen = mstrlen(ATCmdSend);
+			uint8 ReadLen = 0;
+			UART_Query_Data(UART_LPUART1, UART_LPUART1, (uint8 *)ATCmdSend, ATCmdSendLen,UartRecvPtr, &ReadLen, pdMS_TO_TICKS(1000));
+			uint8 *retptr = NULL;
+			if (ReadLen > 0)
+			{
+				retptr = (uint8 *)strstr((char *)UartRecvPtr, (char *)("OK"));
+				if (retptr)
+				{
+					ConnectStep++;
+				}
+				else
+				{
+					ChkState = -ConnectStep;
+					return ChkState;
+				}
+			}
+			else
+			{
+				ChkState = -ConnectStep;
+				return ChkState;
+			}
+			break;
+		}
+		case 1: // Netopen
+		{
+			AtcmdTransmit(AT_NETOPEN, NULL, 0, &ATRet,100);
+			if (ATRet == 0)
+			{
+				ConnectStep++;
+			}
+			else
+			{
+				ChkState = -ConnectStep;
+				return ChkState;
+			}
+			break;
+		}
+		case 2: //连接检查
+		{
+			AtcmdTransmit(AT_CONNECTCHK, NULL, 0, &ATRet,1000); // ATret返回的值是连接id,如果未连接返回-1
+			if (ATRet >= 0)
+			{
+				*ConnectId = ATRet;
+				return 2;
+			}
+			else
+			{
+				ConnectStep++;
+			}
+			break;
+		}
+		case 3: //域名转换
+		{
+			char AtCmdSend[30] = {0};
+			uint8 AtCmdSendLen = 0;
+			AtCmdSendLen = mstrlen(WebSiteName);
+			memcpy(AtCmdSend, WebSiteName, AtCmdSendLen);
+			memcpy(AtCmdSend + AtCmdSendLen, (char *)CRLF, sizeof(CRLF));
+			AtCmdSendLen = AtCmdSendLen + 2;
+			AtcmdTransmit(AT_CGIP, (uint8 *)AtCmdSend, AtCmdSendLen, &ATRet,5000);
+			if (ATRet == 0)
+			{
+				ConnectStep++;
+			}
+			else
+			{
+				ChkState = -ConnectStep;
+				return ChkState;
+			}
+			break;
+		}
+		case 4: //创建连接
+		{
+			char AtCmdSend[50] = {0};
+			uint8 AtCmdSendTotalLen = 0;
+			*ConnectId = 0;
+			/*IP测试更改*/
+//			char *ATCmdSend = (char *)("\"120.26.68.165\"");
+//			memset(WebSiteIp,0x00,sizeof(WebSiteIp));
+//			memcpy(WebSiteIp ,ATCmdSend,strlen(ATCmdSend));
+//			WebSitePort = 14401;
+			/**/
+			sprintf(AtCmdSend, "AT+CIPOPEN=%d,\"TCP\",%s,%d\r\n", *ConnectId, WebSiteIp, WebSitePort); //此处需要优化
+			AtCmdSendTotalLen = mstrlen(AtCmdSend);
+			UART_Send_Data(UART_LPUART1, AtCmdSend, AtCmdSendTotalLen, pdMS_TO_TICKS(100));
+			ATRet = AtcmdDelayRecvFunc(UART_LPUART1,(char *)("+CIPOPEN: 0,0"),20000);
+			if (ATRet == 0)
+			{
+				ConnectStep++;
+			}
+			else
+			{
+				ChkState = -ConnectStep;
+				*ConnectId = -1;
+				return ChkState;
+			}
+			break;
+		}
+		default:
+			ChkState = ConnectStep;
+			return ChkState;
+		}
+	}
+}
+sint8 TcpRegisterChkFunc(void)
+{
+	uint8 RegChkStep = 0;
+	sint8 ChkState = 0; //默认为0
+	sint8 ATRet = -1;
+	while (1)
+	{
+		switch (RegChkStep)
+		{
+		case 0: // AT指令同步
+		{
+			AtcmdTransmit(AT_CMD_TEST, NULL, 0, &ATRet,100);
+			if (ATRet == 0)
+			{
+				RegChkStep++;
+			}
+			else
+			{
+				ChkState = -RegChkStep;
+				return ChkState;
+			}
+			break;
+		}
+		case 1: // CPIN检查
+		{
+			AtcmdTransmit(AT_SIMREADY, NULL, 0, &ATRet,100);
+			if (ATRet == 0)
+			{
+				RegChkStep++;
+			}
+			else
+			{
+				ChkState = -RegChkStep;
+				return ChkState;
+			}
+			break;
+		}
+		case 2:
+		{
+			AtcmdTransmit(AT_CGREG, NULL, 0, &ATRet,1000); //驻网检查,返回值1和5是驻网成功
+			if (ATRet == 1 || ATRet == 5)
+			{
+				RegChkStep++;
+			}
+			else
+			{
+				ChkState = -RegChkStep;
+				return ChkState;
+			}
+			break;
+		}
+		default:
+			ChkState = RegChkStep;
+			return ChkState;
+			break;
+		}
+	}
+}
+void InitFunc(void)
+{
+	// 4G模块初始化
+	uint8 _4G_InitStep = 0;
+	sint8 ATRet = -1;
+	uint16 ReadLen = 0;
+	char *ATCmdSend = NULL;
+	uint8 ATCmdSendLen = 0;
+	uint8 UartRecvPtr[50];
+	uint16 ATerrorCnt = 0;
+	uint8 *retptr = NULL;
+	while (1)
+	{
+		switch (_4G_InitStep)
+		{
+		case 0: // AT指令同步
+		{
+			AtcmdTransmit(AT_CMD_TEST, NULL, 0, &ATRet,100);
+			if (ATRet == 0)
+			{
+				ATerrorCnt = 0;
+				_4G_InitStep++;
+			}
+			else
+			{
+				vTaskDelay(pdMS_TO_TICKS(1000));
+				ATerrorCnt++;
+				if(ATerrorCnt>60*5)
+				{
+					SystemSoftwareReset();
+				}
+			}
+			break;
+		}
+		case 1: //关闭回显
+		{
+			ATCmdSend = (char *)("ATE0\r\n");
+			ATCmdSendLen = mstrlen(ATCmdSend);
+			UART_Query_Data(UART_LPUART1, UART_LPUART1, (uint8 *)ATCmdSend, ATCmdSendLen, UartRecvPtr, &ReadLen, pdMS_TO_TICKS(10000));
+			if (ReadLen > 0)
+			{
+				retptr = (uint8 *)strstr((char *)UartRecvPtr, (char *)("OK"));
+				if (retptr)
+				{
+					_4G_InitStep++;
+				}
+				else
+				{
+					_4G_InitStep=0;
+				}
+			}
+			else
+			{
+				_4G_InitStep=0;
+			}
+			break;
+		}
+		case 2: // IMEI获取
+		{
+			ATCmdSend = (char *)("AT+SIMEI?\r\n");
+			ATCmdSendLen = mstrlen(ATCmdSend);
+			UART_Query_Data(UART_LPUART1, UART_LPUART1, (uint8 *)ATCmdSend, ATCmdSendLen, UartRecvPtr, &ReadLen, pdMS_TO_TICKS(1000));
+			if (ReadLen > 0)
+			{
+				retptr = (uint8 *)strstr((char *)UartRecvPtr, (char *)("+SIMEI"));
+				if (retptr)
+				{
+					memcpy(ImeiNum, retptr + 8, 15);
+					_4G_InitStep++;
+				}
+				else
+				{
+					_4G_InitStep=0;
+				}
+			}
+			else
+			{
+				_4G_InitStep = 0;
+			}
+			break;
+		}
+		case 3: // 打开时间自动更新
+		{
+			ATCmdSend = (char *)("AT+CTZU=1\r\n");
+			ATCmdSendLen = mstrlen(ATCmdSend);
+			UART_Query_Data(UART_LPUART1, UART_LPUART1, (uint8 *)ATCmdSend, ATCmdSendLen, UartRecvPtr, &ReadLen, pdMS_TO_TICKS(1000));
+			if (ReadLen > 0)
+			{
+				retptr = (uint8 *)strstr((char *)UartRecvPtr, (char *)("OK"));
+				if (retptr)
+				{
+					_4G_InitStep++;
+				}
+			}
+			else
+			{
+				_4G_InitStep = 0;
+			}
+			break;
+		}
+		case 4: // ICCID获取
+		{
+			AtcmdTransmit(AT_GETICCID, NULL, 0, &ATRet,1000);
+			if (ATRet == 0)
+			{
+				_4G_InitStep++;
+			}
+			else
+			{
+				_4G_InitStep=0;
+			}
+			break;
+		}
+		case 5:
+		{
+			ATCmdSend = (char *)("AT+CIPSENDMODE=0\r\n");
+			ATCmdSendLen = mstrlen(ATCmdSend);
+			UART_Query_Data(UART_LPUART1, UART_LPUART1, (uint8 *)ATCmdSend, ATCmdSendLen, UartRecvPtr, &ReadLen, pdMS_TO_TICKS(100));
+			if (ReadLen > 0)
+			{
+				retptr = (uint8 *)strstr((char *)UartRecvPtr, (char *)("OK"));
+				if (retptr)
+				{
+					_4G_InitStep++;
+				}
+			}
+			else
+			{
+				_4G_InitStep = 0;
+			}
+		}
+		default:
+		{
+			return;
+			break;
+		}
+		}
+	}
+}
+static void AtcmdTransmit(sint8 CmdIdx, uint8 *SetValuePtr, uint16 SetValueLen, sint8 *retFunc,uint16 timeout)
+{
+	uint16 ReadLen = 0;
+	uint8 PtrATCmdSend[64];
+	uint8 ATCmdFixedLen = 0;
+	uint16 ATCmdTotalLen = 0;
+	uint8 UartRecvPtr[256];
+	ATCmdFixedLen = mstrlen(Atcmdfunc[CmdIdx].str);
+	ATCmdTotalLen = ATCmdFixedLen + SetValueLen;
+	memset(PtrATCmdSend, 0x00, ATCmdTotalLen + 1);
+	memcpy(PtrATCmdSend, Atcmdfunc[CmdIdx].str, ATCmdFixedLen);
+	if (SetValuePtr != NULL)
+	{
+		memcpy(&PtrATCmdSend[ATCmdFixedLen], SetValuePtr, SetValueLen);
+	}
+	UART_Query_Data(UART_LPUART1, UART_LPUART1, PtrATCmdSend, ATCmdTotalLen, UartRecvPtr, &ReadLen, timeout);
+	if(ReadLen>0)
+	{
+		*retFunc = Atcmdfunc[CmdIdx].cb((char *)PtrATCmdSend, UartRecvPtr, CmdIdx, ReadLen);
+	}
+	else
+	{
+		*retFunc = -1;
+	}
+	return;
+}
+sint8 at_callbackFunc(char *PSendStr, char *pReadStr, uint8 CmdIdx, uint16 pReadLen)
+{
+	sint8 OutValue = -1;
+	uint8 *retptr = NULL;
+	char *OkAns = "OK";
+	retptr = (uint8 *)strstr((char *)pReadStr, OkAns);
+	switch (CmdIdx)
+	{
+	case AT_CMD_TEST:
+	{
+		if (retptr)
+		{
+			OutValue = 0;
+		}
+		break;
+	}
+	case AT_SIMREADY:
+	{
+		if (retptr)
+		{
+			retptr = (uint8 *)strstr((char *)pReadStr, (char *)("READY"));
+			if (retptr)
+			{
+				OutValue = 0;
+			}
+		}
+		break;
+	}
+	case AT_GETICCID:
+	{
+		if (retptr)
+		{
+			retptr = (uint8 *)strstr((char *)pReadStr, (char *)("ICCID:"));
+			if (retptr)
+			{
+				memcpy(IccidNum, retptr + 7, 20);
+				OutValue = 0;
+			}
+		}
+		break;
+	}
+	case AT_CGREG:
+	{
+		if (retptr)
+		{
+			retptr = (uint8 *)strstr((char *)pReadStr, (char *)("CGREG:"));
+			if (retptr)
+			{
+				uint8 RegN = 0;
+				uint8 RegState = 0;
+				RegN = CharToHex(*(retptr + 7));
+				RegState = CharToHex(*(retptr + 9));
+				OutValue = (RegState + RegN);
+				return OutValue;
+			}
+		}
+
+		break;
+	}
+	case AT_NETOPEN:
+	{
+		if (retptr)
+		{
+			OutValue = 0;
+		}
+		retptr = (uint8 *)strstr((char *)pReadStr, (char *)("opened")); //重复打开
+		if (retptr)
+		{
+			OutValue = 0;
+		}
+		break;
+	}
+	case AT_CONNECTCHK:
+	{
+		if (retptr)
+		{
+			retptr = (uint8 *)strstr((char *)pReadStr, (char *)("TCP"));
+			if (retptr)
+			{
+				OutValue = CharToHex(*(retptr - 3));
+				return OutValue;
+			}
+		}
+		break;
+	}
+	case AT_CGIP:
+	{
+		if (retptr)
+		{
+			memset(WebSiteIp,0x00,sizeof(WebSiteIp));
+			for (uint8 i = 0; i < 30; i++)
+			{
+				if (*(retptr - i) == ',')
+				{
+					memcpy(WebSiteIp, retptr - i + 1, i-5);
+					OutValue = 0;
+					break;
+				}
+			}
+		}
+		break;
+	}
+	case AT_CONNECT:
+	{
+		if (retptr)
+		{
+			retptr = (uint8 *)strstr((char *)pReadStr, (char *)("CIPOPEN:"));
+			if (retptr&&pReadLen>9)
+			{
+				SocketId = CharToHex(*(retptr + 9));
+			}
+			OutValue = 0;
+		}
+		break;
+	}
+	case AT_SEND:
+	{
+		retptr = (uint8 *)strstr((char *)pReadStr, (char *)(">"));
+		if (retptr)
+		{
+			OutValue = 0;
+		}
+		else
+		{
+			OutValue = -1;
+		}
+		break;
+	}
+	default:
+		break;
+	}
+	return OutValue;
+}
+void TcpDataEncode(uint32 *PtrSendAddr, uint16 *SendLen)
+{
+	static UTC8TimeType UTC8TimeTcp;
+	uint8 *SendBuffer = NULL;
+	uint8 DataIdx = 0;
+	if (TcpSendTimeCounter == 5)
+	{
+		DataIdx = VerMsg; //版本信息发送
+	}
+	else if (TcpSendTimeCounter % 10 == 1)
+	{
+		DataIdx = BattMsg; //电池信息发送
+	}
+	else if ((TcpSendTimeCounter) % 10 == 2)
+	{
+		DataIdx = 0x83; //储能开关信息发送
+	}
+	else if ((TcpSendTimeCounter) % 240 == 3)
+	{
+		DataIdx = GpsMsg; //定位信息发送
+	}
+	else if ((TcpSendTimeCounter) % 240 == 4)
+	{
+		DataIdx = 0x93; //储能电量信息发送
+	}
+	else if ((TcpSendTimeCounter) % 60 == 5)
+	{
+		DataIdx = 0x8A; //累计信息发送
+	}
+	else if ((TcpSendTimeCounter) % (60*60*2) == 6)
+	{
+		DataIdx = 0x01; //时间校准
+	}
+	else
+	{
+		*SendLen = 0;
+		DataIdx = 0; //不发送,返回
+		return;
+	}
+	memcpy(TcpbattSN, AppConfigInfo.deviceSn, 17);
+	GetUtc8Time(&UTC8TimeTcp); //时间获取
+	vTaskDelay(pdMS_TO_TICKS(100));
+	switch (DataIdx)
+	{
+	case 0x01://时间校准
+	{
+		char *ATCmdSend = (char *)("AT+CNTP\r\n");
+		uint8 ATCmdSendLen = mstrlen(ATCmdSend);
+		uint8 ReadLen = 0;
+		uint8 UartRecvPtr[20];
+		UART_Query_Data(UART_LPUART1, UART_LPUART1, (uint8 *)ATCmdSend, ATCmdSendLen,UartRecvPtr, &ReadLen, pdMS_TO_TICKS(500));
+		*SendLen = 0;//不发送,长度为0
+		return;
+	}
+	case 0x82:
+	{
+		GPSInfo GpsRecvData;
+		GPSMsgtoTcpType GpsToTcpInfo;
+		*SendLen = sizeof(GpsToTcpInfo);
+		SendBuffer = pvPortMalloc(*SendLen);
+		uint16 tac = 0;
+		uint32 cellId = 0;
+		uint8 DataLen = (uint16)sizeof(GpsToTcpInfo.gpsInfo);
+		GpsToTcpInfo.startSymbol[0] = TCP_START_SYM1;
+		GpsToTcpInfo.startSymbol[1] = TCP_START_SYM2;
+		GpsToTcpInfo.cmdSymbol = TCP_CMD_SYM;
+		GpsToTcpInfo.ansSymbol = TCP_ANS_SYM;
+		memcpy(GpsToTcpInfo.SN, TcpbattSN, BATT_SN_LEN);
+		GpsToTcpInfo.encryptMethod = TCP_ENCPT_DISABLE; // not encrypt
+		GpsToTcpInfo.dataLength[0] = (DataLen >> 8) & 0xFF;
+		GpsToTcpInfo.dataLength[1] = DataLen & 0xFF;
+		GpsToTcpInfo.gpsInfo.sendTimeUTC[0] = (UTC8TimeTcp.year) & 0xFF; // year
+		GpsToTcpInfo.gpsInfo.sendTimeUTC[1] = UTC8TimeTcp.month & 0xFF;	 // month
+		GpsToTcpInfo.gpsInfo.sendTimeUTC[2] = UTC8TimeTcp.day & 0xFF;	 // day
+		GpsToTcpInfo.gpsInfo.sendTimeUTC[3] = UTC8TimeTcp.hour & 0xFF;	 // hour
+		GpsToTcpInfo.gpsInfo.sendTimeUTC[4] = UTC8TimeTcp.minute & 0xFF; // mins
+		GpsToTcpInfo.gpsInfo.sendTimeUTC[5] = UTC8TimeTcp.second & 0xFF; // sec
+		GpsToTcpInfo.gpsInfo.msgMark = DataIdx;
+		GpsToTcpInfo.gpsInfo.msgCollectionTimeUTC[0] = (UTC8TimeTcp.year) & 0xFF; // year
+		GpsToTcpInfo.gpsInfo.msgCollectionTimeUTC[1] = UTC8TimeTcp.month & 0xFF;  // month
+		GpsToTcpInfo.gpsInfo.msgCollectionTimeUTC[2] = UTC8TimeTcp.day & 0xFF;	  // day
+		GpsToTcpInfo.gpsInfo.msgCollectionTimeUTC[3] = UTC8TimeTcp.hour & 0xFF;	  // hour
+		GpsToTcpInfo.gpsInfo.msgCollectionTimeUTC[4] = UTC8TimeTcp.minute & 0xFF; // mins
+		GpsToTcpInfo.gpsInfo.msgCollectionTimeUTC[5] = UTC8TimeTcp.second & 0xFF;
+		if (xQueueReceive(GpsDataQueueHandle, &GpsRecvData, 0) == pdPASS)
+		{
+			memcpy((uint8 *)&GpsToTcpInfo.gpsInfo.GpsInfoData, (uint8 *)&GpsRecvData, sizeof(GPSInfo));
+		}
+		else
+		{
+			memset((uint8 *)&GpsToTcpInfo.gpsInfo.GpsInfoData, 0x00, sizeof(GPSInfo));
+		}
+		GpsToTcpInfo.gpsInfo.Tac[0] = tac >> 8;
+		GpsToTcpInfo.gpsInfo.Tac[1] = tac & 0xFF;
+		GpsToTcpInfo.gpsInfo.CellID[0] = cellId >> 24;
+		GpsToTcpInfo.gpsInfo.CellID[0] = cellId >> 16;
+		GpsToTcpInfo.gpsInfo.CellID[0] = cellId >> 8;
+		GpsToTcpInfo.gpsInfo.CellID[0] = cellId;
+		uint16 xyzDatacache[3] = {0};
+		memcpy(xyzDatacache, xyzData, 3*sizeof(uint16));
+		for (uint8 i = 0; i < 3; i++)
+		{
+			if (xyzDatacache[i] > 0x8000) // 数据为负
+			{
+				xyzDatacache[i] = 20000U + (sint16)xyzDatacache[i];
+			}
+			else
+			{
+				xyzDatacache[i] = xyzDatacache[i] + 20000U;
+			}
+		}
+		GpsToTcpInfo.gpsInfo.xData[0] = xyzDatacache[0] >> 8;
+		GpsToTcpInfo.gpsInfo.xData[1] = xyzDatacache[0];
+		GpsToTcpInfo.gpsInfo.yData[0] = xyzDatacache[1] >> 8;
+		GpsToTcpInfo.gpsInfo.yData[1] = xyzDatacache[1];
+		GpsToTcpInfo.gpsInfo.zData[0] = xyzDatacache[2] >> 8;
+		GpsToTcpInfo.gpsInfo.zData[1] = xyzDatacache[2];
+		GpsToTcpInfo.CRC = bcc_chk((uint8 *)&GpsToTcpInfo, sizeof(GPSMsgtoTcpType) - 1);
+		memcpy(SendBuffer, &GpsToTcpInfo, sizeof(GpsToTcpInfo));
+		*PtrSendAddr = (uint32)SendBuffer;
+		break;
+	}
+	case 0x86:
+	{
+		VersionMsgtoTcpType VerMsgToTcpInfo;
+		*SendLen = sizeof(VersionMsgtoTcpType);
+		SendBuffer = pvPortMalloc(*SendLen);
+		uint16 DataLen = 0;
+		DataLen = (uint16)sizeof(VerMsgToTcpInfo.VerInfo);
+		VerMsgToTcpInfo.startSymbol[0] = TCP_START_SYM1;
+		VerMsgToTcpInfo.startSymbol[1] = TCP_START_SYM2;
+		VerMsgToTcpInfo.cmdSymbol = TCP_CMD_SYM;
+		VerMsgToTcpInfo.ansSymbol = TCP_ANS_SYM;
+		memcpy(VerMsgToTcpInfo.SN, TcpbattSN, BATT_SN_LEN);
+		VerMsgToTcpInfo.encryptMethod = TCP_ENCPT_DISABLE; // not encrypt
+		VerMsgToTcpInfo.dataLength[0] = (DataLen >> 8) & 0xFF;
+		VerMsgToTcpInfo.dataLength[1] = DataLen & 0xFF;
+		VerMsgToTcpInfo.VerInfo.sendTimeUTC[0] = (UTC8TimeTcp.year) & 0xFF; // year
+		VerMsgToTcpInfo.VerInfo.sendTimeUTC[1] = UTC8TimeTcp.month & 0xFF;	// month
+		VerMsgToTcpInfo.VerInfo.sendTimeUTC[2] = UTC8TimeTcp.day & 0xFF;	// day
+		VerMsgToTcpInfo.VerInfo.sendTimeUTC[3] = UTC8TimeTcp.hour & 0xFF;	// hour
+		VerMsgToTcpInfo.VerInfo.sendTimeUTC[4] = UTC8TimeTcp.minute & 0xFF; // mins
+		VerMsgToTcpInfo.VerInfo.sendTimeUTC[5] = UTC8TimeTcp.second & 0xFF; // sec
+		VerMsgToTcpInfo.VerInfo.msgMark = DataIdx;
+		VerMsgToTcpInfo.VerInfo.msgCollectionTimeUTC[0] = (UTC8TimeTcp.year) & 0xFF; // year
+		VerMsgToTcpInfo.VerInfo.msgCollectionTimeUTC[1] = UTC8TimeTcp.month & 0xFF;	 // month
+		VerMsgToTcpInfo.VerInfo.msgCollectionTimeUTC[2] = UTC8TimeTcp.day & 0xFF;	 // day
+		VerMsgToTcpInfo.VerInfo.msgCollectionTimeUTC[3] = UTC8TimeTcp.hour & 0xFF;	 // hour
+		VerMsgToTcpInfo.VerInfo.msgCollectionTimeUTC[4] = UTC8TimeTcp.minute & 0xFF; // mins
+		VerMsgToTcpInfo.VerInfo.msgCollectionTimeUTC[5] = UTC8TimeTcp.second & 0xFF;
+		memcpy(VerMsgToTcpInfo.VerInfo.ICCID, IccidNum, 20);
+		memcpy(VerMsgToTcpInfo.VerInfo.IMEI, ImeiNum, 15);
+		VerMsgToTcpInfo.VerInfo.BMSHwVersion[0] = bmsHwVersion>>8;
+		VerMsgToTcpInfo.VerInfo.BMSHwVersion[1] = bmsHwVersion;
+		VerMsgToTcpInfo.VerInfo.BMSSwVersion[0] = bmsSwVersion>>24;
+		VerMsgToTcpInfo.VerInfo.BMSSwVersion[1] = bmsSwVersion>>16;
+		VerMsgToTcpInfo.VerInfo.BMSSwVersion[2] = bmsSwVersion>>8;
+		VerMsgToTcpInfo.VerInfo.BMSSwVersion[3] = bmsSwVersion;
+		VerMsgToTcpInfo.VerInfo.HwVersion[0] = (HwVersion >> 8) & 0xFF;
+		VerMsgToTcpInfo.VerInfo.HwVersion[1] = (HwVersion)&0xFF;
+		VerMsgToTcpInfo.VerInfo.BLVersion[0] = (BlSwVersion >> 24) & 0xFF;
+		VerMsgToTcpInfo.VerInfo.BLVersion[1] = (BlSwVersion >> 16) & 0xFF;
+		VerMsgToTcpInfo.VerInfo.BLVersion[2] = (BlSwVersion >> 8) & 0xFF;
+		VerMsgToTcpInfo.VerInfo.BLVersion[3] = (BlSwVersion)&0xFF;
+		VerMsgToTcpInfo.VerInfo.DRVVersion[0] = (DrvSwVersion >> 24) & 0xFF;
+		VerMsgToTcpInfo.VerInfo.DRVVersion[1] = (DrvSwVersion >> 16) & 0xFF;
+		VerMsgToTcpInfo.VerInfo.DRVVersion[2] = (DrvSwVersion >> 8) & 0xFF;
+		VerMsgToTcpInfo.VerInfo.DRVVersion[3] = (DrvSwVersion)&0xFF;
+		VerMsgToTcpInfo.VerInfo.APPVersion[0] = (AppSwVersion >> 24) & 0xFF;
+		VerMsgToTcpInfo.VerInfo.APPVersion[1] = (AppSwVersion >> 16) & 0xFF;
+		VerMsgToTcpInfo.VerInfo.APPVersion[2] = (AppSwVersion >> 8) & 0xFF;
+		VerMsgToTcpInfo.VerInfo.APPVersion[3] = (AppSwVersion)&0xFF;
+		VerMsgToTcpInfo.VerInfo.BmsType = BmsManuFacture;
+		VerMsgToTcpInfo.VerInfo.BmsInfo = BmsInfo;
+		VerMsgToTcpInfo.VerInfo.DataModuleType = DataModuleType;
+		VerMsgToTcpInfo.CRC = bcc_chk((uint8 *)&VerMsgToTcpInfo, sizeof(VerMsgToTcpInfo) - 1);
+		memcpy(SendBuffer, &VerMsgToTcpInfo, sizeof(VersionMsgtoTcpType));
+		*PtrSendAddr = (uint32)SendBuffer;
+		break;
+	}
+	case 0x80:
+	{
+		uint16 ErrorTemp;
+		ErrorTemp = GetErrorNum(ErrorArray,sizeof(ErrorArray)/2);
+		uint8 ProtocolHeaderLen = 25;																					  //电池信息协议头部加校验码长度,此长度不更改
+		uint8 ProtocolFixedLen = 60;																					  //电池信息协议固定总长度 如协议新增,需要更改此长度
+		uint16 ProtocolFluctedLen = AppDataInfo.BattCellCount * 2 + AppDataInfo.BattTempCount + BmsOtherTemp + OtherTemp; //电池信息协议变动长度
+		uint16 DataLen;
+		*SendLen = ProtocolFixedLen + ProtocolFluctedLen;
+		SendBuffer = pvPortMalloc(*SendLen);
+		GetCSQValue(&CSQValue);
+		*(SendBuffer + 0) = TCP_START_SYM1;									 //起始码-1
+		*(SendBuffer + 1) = TCP_START_SYM2;									 //起始码-2
+		*(SendBuffer + 2) = TCP_CMD_SYM;									 //命令标识-3
+		*(SendBuffer + 3) = TCP_ANS_SYM;									 //应答标识-4
+		memcpy(SendBuffer + 4, TcpbattSN, BATT_SN_LEN);						 // SN码 5-21
+		*(SendBuffer + 21) = TCP_ENCPT_DISABLE;								 //加密方式-22
+		DataLen = ProtocolFixedLen + ProtocolFluctedLen - ProtocolHeaderLen; //电池信息单元协议固定长度
+		*(SendBuffer + 22) = (DataLen >> 8) & 0xFF;							 //数据长度H-23
+		*(SendBuffer + 23) = DataLen & 0xFF;								 //数据长度L-24
+		*(SendBuffer + 24) = (UTC8TimeTcp.year) & 0xFF;						 // year-25
+		*(SendBuffer + 25) = UTC8TimeTcp.month & 0xFF;						 // month-26
+		*(SendBuffer + 26) = UTC8TimeTcp.day & 0xFF;						 // day-27
+		*(SendBuffer + 27) = UTC8TimeTcp.hour & 0xFF;						 // hour-28
+		*(SendBuffer + 28) = UTC8TimeTcp.minute & 0xFF;						 // mins-29
+		*(SendBuffer + 29) = UTC8TimeTcp.second & 0xFF;						 // sec-30
+		*(SendBuffer + 30) = DataIdx;										 //电池信息发送-31
+		*(SendBuffer + 31) = (UTC8TimeTcp.year) & 0xFF;						 // year-32
+		*(SendBuffer + 32) = UTC8TimeTcp.month & 0xFF;						 // month-33
+		*(SendBuffer + 33) = UTC8TimeTcp.day & 0xFF;						 // day-34
+		*(SendBuffer + 34) = UTC8TimeTcp.hour & 0xFF;						 // hour-35
+		*(SendBuffer + 35) = UTC8TimeTcp.minute & 0xFF;						 // mins-36
+		*(SendBuffer + 36) = UTC8TimeTcp.second & 0xFF;						 // sec-37
+		*(SendBuffer + 37) = CSQValue;										 //信号强度-38
+		*(SendBuffer + 38) = 0;												 //故障等级-39
+		*(SendBuffer + 39) = ErrorTemp >> 8;								 //故障代码H-40
+		*(SendBuffer + 40) = ErrorTemp & 0xFF;								 //故障代码L-41
+		*(SendBuffer + 41) = battI >> 8;									 //电流-42
+		*(SendBuffer + 42) = battI & 0xFF;									 //电流-43
+		*(SendBuffer + 43) = battPackVol >> 8;								 //电压-44
+		*(SendBuffer + 44) = battPackVol & 0xFF;							 //电压-45
+		*(SendBuffer + 45) = battPackVol >> 8;								 //电压-46
+		*(SendBuffer + 46) = battPackVol & 0xFF;							 //电压-47
+		*(SendBuffer + 47) = battMOSSwitchState;							 // mos状态-48
+		*(SendBuffer + 48) = (uint8)(battSOC);					 // soc-49
+		*(SendBuffer + 49) = (uint8)(battSOH);					 // soh-50
+		*(SendBuffer + 50) = (battBalanceoInfo >> 24) & 0xFF;
+		*(SendBuffer + 51) = (battBalanceoInfo >> 16) & 0xFF;
+		*(SendBuffer + 52) = (battBalanceoInfo >> 8) & 0xFF;
+		*(SendBuffer + 53) = battBalanceoInfo & 0xFF;		  //均衡状态-51-54
+		*(SendBuffer + 54) = AppDataInfo.BattCellCount;		  //电压个数-55
+		for (uint8 i = 0; i < AppDataInfo.BattCellCount; i++) //单体电压
+		{
+			*(SendBuffer + 54 + i * 2 + 1) = (battCellU[i] >> 8) & 0xFF;
+			*(SendBuffer + 54 + i * 2 + 2) = battCellU[i] & 0xFF;
+		}
+		*(SendBuffer + 55 + AppDataInfo.BattCellCount * 2) = AppDataInfo.BattTempCount;							   //模组温度个数
+		memcpy((SendBuffer + 55 + AppDataInfo.BattCellCount * 2 + 1), &battCellTemp, AppDataInfo.BattTempCount);   //模组温度
+		*(SendBuffer + 56 + AppDataInfo.BattCellCount * 2 + AppDataInfo.BattTempCount) = battWorkState;			   //电池工作状态
+		*(SendBuffer + 57 + AppDataInfo.BattCellCount * 2 + AppDataInfo.BattTempCount) = battHeatEnableState;	   //电池加热使能状态
+		*(SendBuffer + 58 + AppDataInfo.BattCellCount * 2 + AppDataInfo.BattTempCount) = BmsOtherTemp + OtherTemp; //其他温度个数
+		// *(SendBuffer + 58 + AppDataInfo.BattCellCount * 2 + AppDataInfo.BattTempCount + 1) = MOSTemp;																						  // mos温度
+		// *(SendBuffer + 58 + AppDataInfo.BattCellCount * 2 + AppDataInfo.BattTempCount + 2) = packTemp;																						  //环境温度
+		// *(SendBuffer + 58 + AppDataInfo.BattCellCount * 2 + AppDataInfo.BattTempCount + 3) = fastChargeTemp;																				  //快充温度
+		// *(SendBuffer + 58 + AppDataInfo.BattCellCount * 2 + AppDataInfo.BattTempCount + 4) = normalChargeTemp;																				  //慢充温度
+		// *(SendBuffer + 58 + AppDataInfo.BattCellCount * 2 + AppDataInfo.BattTempCount + 5) = heatTemp1;																						  //加热温度1
+		// *(SendBuffer + 58 + AppDataInfo.BattCellCount * 2 + AppDataInfo.BattTempCount + 6) = heatTemp2;																						  //加热温度2
+		*(SendBuffer + 59 + AppDataInfo.BattCellCount * 2 + AppDataInfo.BattTempCount + BmsOtherTemp + OtherTemp) = bcc_chk(SendBuffer, ProtocolFixedLen + ProtocolFluctedLen - 1); //校验码
+		*PtrSendAddr = (uint32)SendBuffer;
+		break;
+	}
+	case 0x83://储能场景的开关信息
+	{
+		StorageInfoToTcp StorageInfo;
+		*SendLen = sizeof(StorageInfo);
+		SendBuffer = pvPortMalloc(*SendLen);
+		uint16 DataLen = 0;
+		DataLen = (uint16)sizeof(StorageInfo.StorageMsg);
+		StorageInfo.startSymbol[0] = TCP_START_SYM1;
+		StorageInfo.startSymbol[1] = TCP_START_SYM2;
+		StorageInfo.cmdSymbol = TCP_CMD_SYM;
+		StorageInfo.ansSymbol = TCP_ANS_SYM;
+		memcpy(StorageInfo.SN, TcpbattSN, BATT_SN_LEN);
+		StorageInfo.encryptMethod = TCP_ENCPT_DISABLE; // not encrypt
+		StorageInfo.dataLength[0] = (DataLen >> 8) & 0xFF;
+		StorageInfo.dataLength[1] = DataLen & 0xFF;
+		StorageInfo.StorageMsg.sendTimeUTC[0] = (UTC8TimeTcp.year) & 0xFF; // year
+		StorageInfo.StorageMsg.sendTimeUTC[1] = UTC8TimeTcp.month & 0xFF;	// month
+		StorageInfo.StorageMsg.sendTimeUTC[2] = UTC8TimeTcp.day & 0xFF;	// day
+		StorageInfo.StorageMsg.sendTimeUTC[3] = UTC8TimeTcp.hour & 0xFF;	// hour
+		StorageInfo.StorageMsg.sendTimeUTC[4] = UTC8TimeTcp.minute & 0xFF; // mins
+		StorageInfo.StorageMsg.sendTimeUTC[5] = UTC8TimeTcp.second & 0xFF; // sec
+		StorageInfo.StorageMsg.msgMark = DataIdx;
+		StorageInfo.StorageMsg.msgCollectionTimeUTC[0] = (UTC8TimeTcp.year) & 0xFF; // year
+		StorageInfo.StorageMsg.msgCollectionTimeUTC[1] = UTC8TimeTcp.month & 0xFF;	 // month
+		StorageInfo.StorageMsg.msgCollectionTimeUTC[2] = UTC8TimeTcp.day & 0xFF;	 // day
+		StorageInfo.StorageMsg.msgCollectionTimeUTC[3] = UTC8TimeTcp.hour & 0xFF;	 // hour
+		StorageInfo.StorageMsg.msgCollectionTimeUTC[4] = UTC8TimeTcp.minute & 0xFF; // mins
+		StorageInfo.StorageMsg.msgCollectionTimeUTC[5] = UTC8TimeTcp.second & 0xFF;
+		StorageInfo.StorageMsg.RelayState = battRelayState;
+		StorageInfo.StorageMsg.FanState = battFanState;
+		StorageInfo.StorageMsg.HeatState = battHeatState;
+		StorageInfo.StorageMsg.ConvertState = battConverState;
+		StorageInfo.CRC = bcc_chk((uint8 *)&StorageInfo, sizeof(StorageInfo) - 1);
+		memcpy(SendBuffer, &StorageInfo, sizeof(StorageInfo));
+		*PtrSendAddr = (uint32)SendBuffer;
+		break;
+	}
+	case 0x93://储能场景的电量信息
+	{
+		StorageInfoToTcp2 StorageInfo2;
+		*SendLen = sizeof(StorageInfo2);
+		SendBuffer = pvPortMalloc(*SendLen);
+		uint16 DataLen = 0;
+		DataLen = (uint16)sizeof(StorageInfo2.StorageMsg2);
+		StorageInfo2.startSymbol[0] = TCP_START_SYM1;
+		StorageInfo2.startSymbol[1] = TCP_START_SYM2;
+		StorageInfo2.cmdSymbol = TCP_CMD_SYM;
+		StorageInfo2.ansSymbol = TCP_ANS_SYM;
+		memcpy(StorageInfo2.SN, TcpbattSN, BATT_SN_LEN);
+		StorageInfo2.encryptMethod = TCP_ENCPT_DISABLE; // not encrypt
+		StorageInfo2.dataLength[0] = (DataLen >> 8) & 0xFF;
+		StorageInfo2.dataLength[1] = DataLen & 0xFF;
+		StorageInfo2.StorageMsg2.sendTimeUTC[0] = (UTC8TimeTcp.year) & 0xFF; // year
+		StorageInfo2.StorageMsg2.sendTimeUTC[1] = UTC8TimeTcp.month & 0xFF;	// month
+		StorageInfo2.StorageMsg2.sendTimeUTC[2] = UTC8TimeTcp.day & 0xFF;	// day
+		StorageInfo2.StorageMsg2.sendTimeUTC[3] = UTC8TimeTcp.hour & 0xFF;	// hour
+		StorageInfo2.StorageMsg2.sendTimeUTC[4] = UTC8TimeTcp.minute & 0xFF; // mins
+		StorageInfo2.StorageMsg2.sendTimeUTC[5] = UTC8TimeTcp.second & 0xFF; // sec
+		StorageInfo2.StorageMsg2.msgMark = DataIdx;
+		StorageInfo2.StorageMsg2.msgCollectionTimeUTC[0] = (UTC8TimeTcp.year) & 0xFF; // year
+		StorageInfo2.StorageMsg2.msgCollectionTimeUTC[1] = UTC8TimeTcp.month & 0xFF;	 // month
+		StorageInfo2.StorageMsg2.msgCollectionTimeUTC[2] = UTC8TimeTcp.day & 0xFF;	 // day
+		StorageInfo2.StorageMsg2.msgCollectionTimeUTC[3] = UTC8TimeTcp.hour & 0xFF;	 // hour
+		StorageInfo2.StorageMsg2.msgCollectionTimeUTC[4] = UTC8TimeTcp.minute & 0xFF; // mins
+		StorageInfo2.StorageMsg2.msgCollectionTimeUTC[5] = UTC8TimeTcp.second & 0xFF;
+		StorageInfo2.StorageMsg2.meter1AllPwr[0] = meterAllPwr[0]>>24;
+		StorageInfo2.StorageMsg2.meter1AllPwr[1] = meterAllPwr[0]>>16;
+		StorageInfo2.StorageMsg2.meter1AllPwr[2] = meterAllPwr[0]>>8;
+		StorageInfo2.StorageMsg2.meter1AllPwr[3] = meterAllPwr[0]>>0;
+		StorageInfo2.StorageMsg2.meter1PosPwr[0] = meterPosPwr[0]>>24;
+		StorageInfo2.StorageMsg2.meter1PosPwr[1] = meterPosPwr[0]>>16;
+		StorageInfo2.StorageMsg2.meter1PosPwr[2] = meterPosPwr[0]>>8;
+		StorageInfo2.StorageMsg2.meter1PosPwr[3] = meterPosPwr[0]>>0;
+		StorageInfo2.StorageMsg2.meter1NegPwr[0] = meterNegPwr[0]>>24;
+		StorageInfo2.StorageMsg2.meter1NegPwr[1] = meterNegPwr[0]>>16;
+		StorageInfo2.StorageMsg2.meter1NegPwr[2] = meterNegPwr[0]>>8;
+		StorageInfo2.StorageMsg2.meter1NegPwr[3] = meterNegPwr[0]>>0;
+
+		StorageInfo2.StorageMsg2.meter2AllPwr[0] = meterAllPwr[1]>>24;
+		StorageInfo2.StorageMsg2.meter2AllPwr[1] = meterAllPwr[1]>>16;
+		StorageInfo2.StorageMsg2.meter2AllPwr[2] = meterAllPwr[1]>>8;
+		StorageInfo2.StorageMsg2.meter2AllPwr[3] = meterAllPwr[1]>>0;
+		StorageInfo2.StorageMsg2.meter2PosPwr[0] = meterPosPwr[1]>>24;
+		StorageInfo2.StorageMsg2.meter2PosPwr[1] = meterPosPwr[1]>>16;
+		StorageInfo2.StorageMsg2.meter2PosPwr[2] = meterPosPwr[1]>>8;
+		StorageInfo2.StorageMsg2.meter2PosPwr[3] = meterPosPwr[1]>>0;
+		StorageInfo2.StorageMsg2.meter2NegPwr[0] = meterNegPwr[1]>>24;
+		StorageInfo2.StorageMsg2.meter2NegPwr[1] = meterNegPwr[1]>>16;
+		StorageInfo2.StorageMsg2.meter2NegPwr[2] = meterNegPwr[1]>>8;
+		StorageInfo2.StorageMsg2.meter2NegPwr[3] = meterNegPwr[1]>>0;
+
+		StorageInfo2.CRC = bcc_chk((uint8 *)&StorageInfo2, sizeof(StorageInfo2) - 1);
+		memcpy(SendBuffer, &StorageInfo2, sizeof(StorageInfo2));
+		*PtrSendAddr = (uint32)SendBuffer;
+		break;
+	}
+	case 0x8A:
+	{
+		AccInfoToTcp AccInfoToTcpMsg;
+		*SendLen = sizeof(AccInfoToTcpMsg);
+		SendBuffer = pvPortMalloc(*SendLen);
+		uint16 DataLen = 0;
+		DataLen = (uint16)sizeof(AccInfoToTcpMsg.AccMsg);
+		AccInfoToTcpMsg.startSymbol[0] = TCP_START_SYM1;
+		AccInfoToTcpMsg.startSymbol[1] = TCP_START_SYM2;
+		AccInfoToTcpMsg.cmdSymbol = TCP_CMD_SYM;
+		AccInfoToTcpMsg.ansSymbol = TCP_ANS_SYM;
+		memcpy(AccInfoToTcpMsg.SN, TcpbattSN, BATT_SN_LEN);
+		AccInfoToTcpMsg.encryptMethod = TCP_ENCPT_DISABLE; // not encrypt
+		AccInfoToTcpMsg.dataLength[0] = (DataLen >> 8) & 0xFF;
+		AccInfoToTcpMsg.dataLength[1] = DataLen & 0xFF;
+		AccInfoToTcpMsg.AccMsg.sendTimeUTC[0] = (UTC8TimeTcp.year) & 0xFF; // year
+		AccInfoToTcpMsg.AccMsg.sendTimeUTC[1] = UTC8TimeTcp.month & 0xFF;	// month
+		AccInfoToTcpMsg.AccMsg.sendTimeUTC[2] = UTC8TimeTcp.day & 0xFF;	// day
+		AccInfoToTcpMsg.AccMsg.sendTimeUTC[3] = UTC8TimeTcp.hour & 0xFF;	// hour
+		AccInfoToTcpMsg.AccMsg.sendTimeUTC[4] = UTC8TimeTcp.minute & 0xFF; // mins
+		AccInfoToTcpMsg.AccMsg.sendTimeUTC[5] = UTC8TimeTcp.second & 0xFF; // sec
+		AccInfoToTcpMsg.AccMsg.msgMark = DataIdx;
+		AccInfoToTcpMsg.AccMsg.msgCollectionTimeUTC[0] = (UTC8TimeTcp.year) & 0xFF; // year
+		AccInfoToTcpMsg.AccMsg.msgCollectionTimeUTC[1] = UTC8TimeTcp.month & 0xFF;	 // month
+		AccInfoToTcpMsg.AccMsg.msgCollectionTimeUTC[2] = UTC8TimeTcp.day & 0xFF;	 // day
+		AccInfoToTcpMsg.AccMsg.msgCollectionTimeUTC[3] = UTC8TimeTcp.hour & 0xFF;	 // hour
+		AccInfoToTcpMsg.AccMsg.msgCollectionTimeUTC[4] = UTC8TimeTcp.minute & 0xFF; // mins
+		AccInfoToTcpMsg.AccMsg.msgCollectionTimeUTC[5] = UTC8TimeTcp.second & 0xFF;
+		AccInfoToTcpMsg.AccMsg.accOnlineDays[0] = 0;
+		AccInfoToTcpMsg.AccMsg.accOnlineDays[1] = 0;
+		AccInfoToTcpMsg.AccMsg.accDrvMiles[0] = 0;
+		AccInfoToTcpMsg.AccMsg.accDrvMiles[1] = 0;
+		AccInfoToTcpMsg.AccMsg.sohNoCalibrTime[0] = 0;
+		AccInfoToTcpMsg.AccMsg.sohNoCalibrTime[1] = 0;
+		AccInfoToTcpMsg.AccMsg.accChrgEng[0] = 0;
+		AccInfoToTcpMsg.AccMsg.accChrgEng[1] = 0;
+		AccInfoToTcpMsg.AccMsg.accChrgEng[2] = 0;
+		AccInfoToTcpMsg.AccMsg.accChrgEng[3] = 0;
+		uint32 temp = 0;
+		temp = AppConfigInfo.AppDataInfo.battDischrgAccEnrg/1000;
+		AccInfoToTcpMsg.AccMsg.accDischrgEng[0] = temp>>24;
+		AccInfoToTcpMsg.AccMsg.accDischrgEng[1] = temp>>16;
+		AccInfoToTcpMsg.AccMsg.accDischrgEng[2] = temp>>8;
+		AccInfoToTcpMsg.AccMsg.accDischrgEng[3] = temp>>0;
+		AccInfoToTcpMsg.AccMsg.accChrgCap[0] = 0;
+		AccInfoToTcpMsg.AccMsg.accChrgCap[1] = 0;
+		AccInfoToTcpMsg.AccMsg.accChrgCap[2] = 0;
+		AccInfoToTcpMsg.AccMsg.accChrgCap[3] = 0;
+		temp = AppConfigInfo.AppDataInfo.battDischrgAccCap/1000;
+		AccInfoToTcpMsg.AccMsg.accDischrgCap[0] = temp>>24;
+		AccInfoToTcpMsg.AccMsg.accDischrgCap[1] = temp>>16;
+		AccInfoToTcpMsg.AccMsg.accDischrgCap[2] = temp>>8;
+		AccInfoToTcpMsg.AccMsg.accDischrgCap[3] = temp;
+		AccInfoToTcpMsg.AccMsg.accOverChrgTimes= 0;
+		AccInfoToTcpMsg.AccMsg.accOverDischrgTimes = 0;
+		AccInfoToTcpMsg.AccMsg.accCycleTimes[0] = AppConfigInfo.AppDataInfo.battCycleTimes>>8;
+		AccInfoToTcpMsg.AccMsg.accCycleTimes[1] = AppConfigInfo.AppDataInfo.battCycleTimes;
+		AccInfoToTcpMsg.CRC = bcc_chk((uint8 *)&AccInfoToTcpMsg, sizeof(AccInfoToTcpMsg) - 1);
+		memcpy(SendBuffer, &AccInfoToTcpMsg, sizeof(AccInfoToTcpMsg));
+		*PtrSendAddr = (uint32)SendBuffer;
+		break;
+	}
+	default:
+		break;
+	}
+}
+void GetUtc8Time(UTC8TimeType *UTC8TimeTcp)
+{
+	char *AtCmdAsk = (char *)("AT+CCLK?\r\n");
+	uint8 AtCmdLen = mstrlen(AtCmdAsk);
+	uint16 ReadLen = 0;
+	uint8 *retptr = NULL;
+	uint8 UartRecvPtr[128];
+	UART_Query_Data(UART_LPUART1, UART_LPUART1, (uint8 *)AtCmdAsk, AtCmdLen, UartRecvPtr, &ReadLen, pdMS_TO_TICKS(100));
+	if (ReadLen > 0)
+	{
+		if ((uint8 *)strstr((char *)UartRecvPtr, (char *)("OK")))
+		{
+			retptr = (uint8 *)strstr((char *)UartRecvPtr, (char *)("+CCLK:"));
+			if(retptr)
+			{
+				UTC8TimeTcp->year = CharToHex(*(retptr + 8)) * 10 + CharToHex(*(retptr + 9));
+				UTC8TimeTcp->month = CharToHex(*(retptr + 11)) * 10 + CharToHex(*(retptr + 12));
+				UTC8TimeTcp->day = CharToHex(*(retptr + 14)) * 10 + CharToHex(*(retptr + 15));
+				UTC8TimeTcp->hour = CharToHex(*(retptr + 17)) * 10 + CharToHex(*(retptr + 18));
+				UTC8TimeTcp->minute = CharToHex(*(retptr + 20)) * 10 + CharToHex(*(retptr + 21));
+				UTC8TimeTcp->second = CharToHex(*(retptr + 23)) * 10 + CharToHex(*(retptr + 24));
+			}
+		}
+	}
+}
+static void GetCSQValue(uint8 *out)
+{
+	char *AtCmdAsk = (char *)("AT+CSQ\r\n");
+	uint8 AtCmdLen = mstrlen(AtCmdAsk);
+	uint16 ReadLen = 0;
+	uint8 *retptr = NULL;
+	uint8 UartRecvPtr[30];
+	UART_Query_Data(UART_LPUART1, UART_LPUART1, (uint8 *)AtCmdAsk, AtCmdLen, UartRecvPtr, &ReadLen, pdMS_TO_TICKS(100));
+	*out = 99;
+	if (ReadLen > 0)
+	{
+		if ((uint8 *)strstr((char *)UartRecvPtr, (char *)("OK")))
+		{
+			*out = 0;
+			retptr = (uint8 *)strstr((char *)UartRecvPtr, (char *)("+CSQ:"));
+			char CsqStr[5];
+			for (uint8 i = 0; i < 5; i++)
+			{
+				if (*(retptr+i+6) == ',')
+				{
+					break;
+				}
+				memcpy((CsqStr+i),(retptr+i+6),1);
+			}
+			*out = atoi(CsqStr);
+		}
+	}
+	return;
+}
+static void TcpDataInfoRecvHandle(uint8 *DataRecv, uint16 DataRecvLen)
+{
+	uint8 Tcp_Cmd;
+	uint8 *Ptr = NULL, *retptr = NULL;
+	uint8 TcpCmdAnswer[50]={0};
+	uint16 TcpDataLen = 0;
+	uint16 NumCalTemp = 1;
+	retptr = (uint8 *)strstr((char *)DataRecv, (char *)("\r\n##"));
+	if (retptr == NULL||DataRecvLen<5)
+		return;
+	for (uint8 i = 0; i < 5; i++)
+	{
+		if (*(retptr - i - 1) == 'D')
+		{
+			break;
+		}
+		TcpDataLen = TcpDataLen + CharToHex(*(retptr - i - 1)) * NumCalTemp;
+		NumCalTemp = NumCalTemp * 10;
+	}
+	if (TcpDataLen > 0)
+	{
+		Ptr = retptr + 2;
+		if ((*(Ptr + 0) == TCP_START_SYM1) && (*(Ptr + 1) == TCP_START_SYM2)) //服务器起始信息
+		{
+			Tcp_Cmd = *(Ptr + 2); //命令标志
+			if (*(Ptr + 3) == 0xFE)
+			{
+				TcpWorkState = 0x01;//需要暂停发送,进行命令应答的标志
+			}
+			else
+			{
+				return;
+			}
+			switch (Tcp_Cmd)
+			{
+			case TCP_QUERY_SYM:
+				break;
+			case TCP_SETCMD_SYM:
+				break;
+			case TCP_CONCMD_SYM:
+			{
+				TcpCmdAnswer[0] = TCP_START_SYM1;
+				TcpCmdAnswer[1] = TCP_START_SYM1;
+				TcpCmdAnswer[2] = TCP_CONCMD_SYM;
+				if (*(Ptr + 30) == 0x83) //远程升级指令
+				{
+                    TcpCmdAnswer[3] = 0x01;
+                    memcpy(&TcpCmdAnswer[4], (Ptr + 4), BATT_SN_LEN);
+                    TcpCmdAnswer[21] = TCP_ENCPT_DISABLE;
+                    TcpCmdAnswer[22] = 0x00;
+                    TcpCmdAnswer[23] = 0x06;
+                    memcpy(&TcpCmdAnswer[24], (Ptr + 24), 6);
+                    TcpCmdAnswer[30] = bcc_chk(TcpCmdAnswer, 30);
+					tcpipConnectionSend(SocketId, TcpCmdAnswer, 31);
+					vTaskDelay(pdMS_TO_TICKS(5000));
+					Fota_Ftp(Ptr + 32);
+				}
+                else if (*(Ptr + 30) == 0x80) //远程锁定命令
+                {
+                    TcpCmdAnswer[3] = 0x01;
+                    memcpy(&TcpCmdAnswer[4], (Ptr + 4), BATT_SN_LEN);
+                    TcpCmdAnswer[21] = TCP_ENCPT_DISABLE;
+                    TcpCmdAnswer[22] = 0x00;
+                    TcpCmdAnswer[23] = 0x06;
+                    memcpy(&TcpCmdAnswer[24], (Ptr + 24), 6);
+                    TcpCmdAnswer[30] = bcc_chk(TcpCmdAnswer, 30);
+                    if (*(Ptr + 31) == 0x01) // 0x01代表锁定
+                    {
+                    	battSeparateEnable = 1;
+                    	battSeparateCtlState = 1;
+                        tcpipConnectionSend(SocketId, TcpCmdAnswer, 31 );
+                    }
+                    else if (*(Ptr + 31) == 0x02) // 0x02代表解锁
+                    {
+                    	battSeparateEnable = 1;
+                    	battSeparateCtlState = 0;
+                        tcpipConnectionSend(SocketId, TcpCmdAnswer, 31);
+                    }
+                }
+				else
+				{
+					TcpCmdAnswer[3] = 0x0f;
+					memcpy(&TcpCmdAnswer[4], (Ptr + 4), BATT_SN_LEN);
+					TcpCmdAnswer[21] = TCP_ENCPT_DISABLE;
+					TcpCmdAnswer[22] = 0x00;
+					TcpCmdAnswer[23] = 0x06;
+					memcpy(&TcpCmdAnswer[24], (Ptr + 24), 6);
+					TcpCmdAnswer[30] = bcc_chk(TcpCmdAnswer, 30);
+					tcpipConnectionSend(SocketId, TcpCmdAnswer, 31);
+				}
+				break;
+            }
+			case TCP_UDSCMD_SYM:
+			{
+				TcpCmdAnswer[0] = TCP_START_SYM1;
+				TcpCmdAnswer[1] = TCP_START_SYM1;
+				TcpCmdAnswer[2] = TCP_UDSCMD_SYM;
+				tcpUdsFunc(Ptr,TcpCmdAnswer);
+//				tcpipConnectionSend(SocketId, TcpCmdAnswer, 30);
+				break;
+			}
+            default:
+            {
+                break;
+            }
+            }
+        }
+    }
+}
+void tcpUdsFunc(uint8 *Ptr,uint8 *AnsPtr)
+{
+	uint8 contrlType = 0;
+	uint16 udsDataLen = 0;
+	uint16 DIDBuffer = 0;
+	uint8 udsType_SID = 0;
+	uint8 DataBuffer[10];
+	contrlType = *(Ptr + 30);
+	udsDataLen = *(Ptr + 31);
+	udsType_SID = *(Ptr + 32);
+	DIDBuffer = *(Ptr + 33)<<8|*(Ptr + 34);
+	memcpy(DataBuffer,Ptr + 35,udsDataLen);
+	switch(contrlType)
+	{
+	case 0x00:
+	{
+		break;
+	}
+	case 0x01:
+	{
+		switch(udsType_SID)
+		{
+		case 0x2E:
+		{
+			switch(DIDBuffer)
+			{
+			case 0x01:
+			{
+            	battSeparateEnable = 1;
+				if(DataBuffer[0]==0x01)
+				{
+					battSeparateCtlState = 1;
+				}
+				else if(DataBuffer[0]==0x00)
+				{
+					battSeparateCtlState = 0;
+				}
+				*(AnsPtr+3) = 0x0f;
+				memcpy((AnsPtr+4), (Ptr + 4), BATT_SN_LEN);
+				*(AnsPtr+21) = TCP_ENCPT_DISABLE;
+				*(AnsPtr+22) = 0x00;
+				*(AnsPtr+23) = 0x06;
+				memcpy((AnsPtr+24), (Ptr + 24), 6);
+				*(AnsPtr+30) = contrlType;
+				*(AnsPtr+31) = udsDataLen;
+				*(AnsPtr+32) = udsType_SID;
+				*(AnsPtr+33) = DIDBuffer>>8;
+				*(AnsPtr+34) = DIDBuffer;
+				*(AnsPtr+36) = DataBuffer[0];
+				*(AnsPtr+37) = bcc_chk(AnsPtr, 37);
+				return;
+				break;
+			}
+			default:
+				break;
+			}
+			break;
+		}
+		case 0x22:
+		{
+			break;
+		}
+		default:
+			break;
+		}
+		break;
+	}
+	default:
+		break;
+	}
+	*(AnsPtr+3) = 0x0f;
+	memcpy((AnsPtr+4), (Ptr + 4), BATT_SN_LEN);
+	*(AnsPtr+21) = TCP_ENCPT_DISABLE;
+	*(AnsPtr+22) = 0x00;
+	*(AnsPtr+23) = 0x06;
+	memcpy((AnsPtr+24), (Ptr + 24), 6);
+	*(AnsPtr+30) = contrlType;
+	*(AnsPtr+31) = udsDataLen;
+	*(AnsPtr+32) = 0x7F;
+	*(AnsPtr+33) = DIDBuffer>>8;
+	*(AnsPtr+34) = DIDBuffer;
+	*(AnsPtr+36) = 0x31;
+	*(AnsPtr+37) = bcc_chk(AnsPtr, 37);
+}
+
+
+/***************************************************************************************/
+void Fota_Ftp(uint8 *dataPtrIn)
+{
+	static uint8 ftp_process = 0;
+	char *ATCmdSend = NULL;
+	sint8 recvRet = -1;
+	char ATSendDataBuffer[100] = {0};
+	uint8 UartRecvBuffer[50];
+	uint16 ReadLen = 0;
+	uint8 *retptr = NULL;
+//	char temp[70]=",qx,qx900,120.27.243.131,21,0,0.0.1.5,0.0.1.5,/Debug/V0.0.1.5.bin,";
+	/*URL信息解析*/
+	char *databuffer[20];
+	char *accountPtr;
+	char *passwordPtr;
+	char *ftpServerIpPtr;
+	char *ftpServerPort;
+	char *filePathPtr;
+	char *filenamePtr;
+	char keyFilename[20]={0};
+	char *p = NULL;
+	p = strtok((char *)dataPtrIn, ",");
+	uint8 index = 0;
+	uint8 ftp_EndFlg = 0;
+	while (p&&index<20)
+	{
+		databuffer[index] = p;
+		p = strtok(NULL, ",");//报硬件错误
+		index++;
+	}
+	accountPtr = databuffer[0];
+	passwordPtr = databuffer[1];
+	ftpServerIpPtr = databuffer[2];
+	ftpServerPort = databuffer[3];
+	filePathPtr = databuffer[7];
+	for(sint8 i=strlen(filePathPtr);i--;i<0)
+	{
+		if(*(filePathPtr+i)=='/')
+		{
+			*(filePathPtr+i) = 0;
+			filenamePtr = filePathPtr+i+1;
+			break;
+		}
+
+	}
+	memcpy(keyFilename,filenamePtr,mstrlen(filenamePtr)-3);
+	memcpy(&keyFilename[mstrlen(filenamePtr)-3],"zl",strlen("zl"));
+	while(!ftp_EndFlg)
+	{
+		vTaskDelay(pdMS_TO_TICKS(100));
+		switch(ftp_process)
+		{
+		case 0://start
+		{
+			ATCmdSend = (char *)("AT+CFTPSSTART\r\n");
+			UART_Send_Data(UART_LPUART1, ATCmdSend, mstrlen(ATCmdSend), pdMS_TO_TICKS(100));
+			recvRet = AtcmdDelayRecvFunc(UART_LPUART1,(char *)("+CFTPSSTART: 0"),2000);
+			if(recvRet==0)
+			{
+				ftp_process++;
+			}
+			else
+			{
+				ftp_EndFlg=1;
+			}
+			break;
+		}
+		case 1://login
+		{
+			memset(ATSendDataBuffer,0x00,sizeof(ATSendDataBuffer));
+			sprintf(ATSendDataBuffer, "AT+CFTPSLOGIN=\"%s\",%s,\"%s\",\"%s\",0\r\n", ftpServerIpPtr, ftpServerPort,accountPtr,passwordPtr);
+			UART_Send_Data(UART_LPUART1, ATSendDataBuffer, mstrlen(ATSendDataBuffer), pdMS_TO_TICKS(100));
+			recvRet = AtcmdDelayRecvFunc(UART_LPUART1,(char *)("+CFTPSLOGIN: 0"),30000);
+			if(recvRet==0)
+			{
+				ftp_process++;
+			}
+			else
+			{
+				ftp_EndFlg=1;
+			}
+			break;
+		}
+		case 2://transmit bin file from server to module
+		{
+			uint8 *UartData = NULL;
+			memset(ATSendDataBuffer,0x00,sizeof(ATSendDataBuffer));
+			sprintf(ATSendDataBuffer, "AT+CFTPSGETFILE=\"%s/%s\"\r\n", filePathPtr,filenamePtr);
+			UART_Send_Data(UART_LPUART1, ATSendDataBuffer, mstrlen(ATSendDataBuffer), pdMS_TO_TICKS(100));
+			recvRet = AtcmdDelayRecvFunc(UART_LPUART1,(char *)("+CFTPSGETFILE: 0"),10000);
+			if(recvRet==0)
+			{
+				ftp_process++;
+			}
+			else
+			{
+				ftp_EndFlg=1;
+			}
+			break;
+		}
+		case 3://transmit zl file from server to module
+		{
+			memset(ATSendDataBuffer,0x00,sizeof(ATSendDataBuffer));
+			sprintf(ATSendDataBuffer, "AT+CFTPSGETFILE=\"%s/%s\"\r\n", filePathPtr,keyFilename);
+			UART_Send_Data(UART_LPUART1, ATSendDataBuffer, mstrlen(ATSendDataBuffer), pdMS_TO_TICKS(100));
+			recvRet = AtcmdDelayRecvFunc(UART_LPUART1,(char *)("+CFTPSGETFILE: 0"),10000);
+			if(recvRet==0)
+			{
+				ftp_process++;
+			}
+			else
+			{
+				ftp_EndFlg=1;
+			}
+			break;
+		}
+		case 4://logout
+		{
+			ATCmdSend = (char *)("AT+CFTPSLOGOUT\r\n");
+			UART_Send_Data(UART_LPUART1, ATCmdSend, mstrlen(ATCmdSend), pdMS_TO_TICKS(100));
+			recvRet = AtcmdDelayRecvFunc(UART_LPUART1,(char *)("+CFTPSLOGOUT: 0"),2000);
+			if(recvRet==0)
+			{
+				ftp_process++;
+			}
+			else
+			{
+				ftp_process++;
+			}
+			break;
+		}
+		case 5://stop
+		{
+			ATCmdSend = (char *)("AT+CFTPSSTOP\r\n");
+			UART_Send_Data(UART_LPUART1, ATCmdSend, mstrlen(ATCmdSend), pdMS_TO_TICKS(100));
+			recvRet = AtcmdDelayRecvFunc(UART_LPUART1,(char *)("CFTPSSTOP: 0"),2000);
+			if(recvRet==0)
+			{
+				ftp_process++;
+			}
+			else
+			{
+				ftp_process++;
+			}
+			break;
+		}
+		case 6://get data from module
+		{
+			char findDataBuffer[25] = {0};
+			uint32 currentAddr = 0;
+			uint16 readLenAsk = 256;
+	        uint16 FotaRecvDataLen_8 = 0;
+			uint32 fileLen = 65535;
+	        uint32 FlashAddStart = 0;
+	        uint32 appReceviedCRC;
+	        uint16 getDataLenErrCount = 0;
+	        uint8 UartData[512] = {0};
+	        uint8 FlashData[512] = {0};
+	        uint8 *fileDataPtr = NULL;
+	        memset(ATSendDataBuffer,0x00,sizeof(ATSendDataBuffer));
+			sprintf(ATSendDataBuffer, "AT+CFTRANTX=\"c:/%s\"\r\n",keyFilename);
+			UART_Query_Data(UART_LPUART1, UART_LPUART1, ATSendDataBuffer, mstrlen(ATSendDataBuffer), UartRecvBuffer, &ReadLen, pdMS_TO_TICKS(5000));
+			if (ReadLen == (4+45))
+			{
+				retptr = (uint8 *)strstr((char *)UartRecvBuffer, (char *)("+CFTRANTX: DATA"));
+				if (retptr)
+				{
+					fileLen = (*(retptr+21)<<24)|(*(retptr+22)<<16)|(*(retptr+23)<<8)|(*(retptr+24)<<0);
+					appReceviedCRC = (*(retptr+19)<<8)|(*(retptr+20)<<0);
+			        Hal_FlsGetAppVectorTableStartAddr(&FlashAddStart);
+			        Hal_OTAFlashAppInfoInit();
+	                Hal_FlsErase(0,FlashAddStart + fileLen + FLS_INTERNAL_WRITE_SIZE, 100);
+	                Hal_SetAppInfo(fileLen, appReceviedCRC, CONTROLLER_SELF);
+					while(readLenAsk!=0)
+					{
+						memset(UartData,0x00,512);
+						memset(FlashData,0x00,512);
+						memset(ATSendDataBuffer,0x00,sizeof(ATSendDataBuffer));
+						sprintf(ATSendDataBuffer, "AT+CFTRANTX=\"c:/%s\",%d,%d\r\n", filenamePtr,currentAddr, readLenAsk);
+						UART_Query_Data(UART_LPUART1, UART_LPUART1, ATSendDataBuffer, mstrlen(ATSendDataBuffer), UartData, &ReadLen, pdMS_TO_TICKS(5000));
+						sprintf(findDataBuffer, "+CFTRANTX: DATA,%d", readLenAsk);
+						if (ReadLen == (readLenAsk+strlen(findDataBuffer)+26))
+						{
+							retptr = (uint8 *)strstr((char *)UartData, findDataBuffer);
+							if (retptr)
+							{
+								uint16 uartcrc = 0x00;
+								uint16 flashcrc = 0xff;
+								fileDataPtr = retptr+ 2 + mstrlen(findDataBuffer);
+								FotaRecvDataLen_8 = ((readLenAsk+7)/8)*8;
+								Hal_FlsWrite(FlashAddStart + currentAddr, fileDataPtr, FotaRecvDataLen_8, 100);
+								Hal_FlsRead(FlashAddStart + currentAddr, FlashData, FotaRecvDataLen_8, 100);
+								uartcrc = CRC16_Modbus(fileDataPtr,FotaRecvDataLen_8);
+								flashcrc = CRC16_Modbus(FlashData,FotaRecvDataLen_8);
+								if(flashcrc==uartcrc)
+								{
+									currentAddr = currentAddr + readLenAsk;
+									getDataLenErrCount = 0;
+								}
+								else
+								{
+									uint32 secflash = (FlashAddStart + currentAddr) & 0xFFFFF000;
+									if(secflash>0)
+									{
+										currentAddr = secflash - FlashAddStart;
+									}
+									else
+									{
+										currentAddr = 0;
+									}
+									MemIf_JobResultType ret = Hal_FlsErase(secflash,4096, 100);
+									getDataLenErrCount++;
+								}
+								readLenAsk = min(fileLen-currentAddr,readLenAsk);
+							}
+							else
+							{
+								getDataLenErrCount++;
+							}
+						}
+						else
+						{
+							getDataLenErrCount++;
+						}
+						if(getDataLenErrCount>=100)
+						{
+							break;
+						}
+					}
+	                if(getDataLenErrCount<50&&Hal_FlsCheckIsTransferSucceed()==TRUE)
+	                {
+	                	ftp_process++;
+	                }
+	                else
+	                {
+	                	ftp_EndFlg = 1;
+	                }
+				}
+			}
+			else
+			{
+				ftp_EndFlg = 1;
+			}
+			break;
+		}
+		case 7://delete the bin and zl files
+		{
+	        memset(ATSendDataBuffer,0x00,sizeof(ATSendDataBuffer));
+			sprintf(ATSendDataBuffer, "AT+FSDEL=*.*\r\n");
+			UART_Query_Data(UART_LPUART1, UART_LPUART1, ATSendDataBuffer, mstrlen(ATSendDataBuffer), UartRecvBuffer, &ReadLen, pdMS_TO_TICKS(5000));
+			ftp_process++;
+			Fota_update_flag = TRUE;
+			break;
+		}
+		default:
+			ftp_EndFlg = 1;
+			break;
+		}
+	}
+	if(ftp_process<6)
+	{
+		Fota_error_flag = 1;
+	}
+}

+ 207 - 0
code/app/AppTaskUart1.h

@@ -0,0 +1,207 @@
+/*** 
+ * @Author: chenjie
+ * @Date: 2022-06-06
+ * @LastEditTime: 2022-10-27
+ * @LastEditors: chenjie
+ * @Description: 
+ * @FilePath: \S32K146_4G\code\app\AppTaskUart1.h
+ * @Copyright (c) 2022 by chenjie, All Rights Reserved.
+ */
+
+
+#ifndef APPTASKUART1_H_
+#define APPTASKUART1_H_
+#include "hal_adapter.h"
+#include "AppFunclib.h"
+#include "AppGlobalVar.h"
+#include "AppTaskGps.h"
+#define CRLF "\r\n"
+#define BATT_SN_LEN 17
+#define TCP_START_SYM1 0x23
+#define TCP_START_SYM2 0x23
+#define TCP_CMD_SYM 0x02   //实时信息上报是0x02
+#define TCP_HEART_SYM 0x07 //心跳包标志
+#define TCP_ANS_SYM 0xFE
+#define TCP_ENCPT_ENABLE 0x00
+#define TCP_ENCPT_DISABLE 0x01
+#define BattMsg (0x80)
+#define GpsMsg (0x82)
+#define VerMsg (0x86)
+#define TruckBattMsg (0x91)
+#define TruckVehiMsg (0x90)
+#define TruckAcclMsg (0x92)
+#define TCP_QUERY_SYM 0x80
+#define TCP_SETCMD_SYM 0x81
+#define TCP_CONCMD_SYM 0x82
+#define TCP_UDSCMD_SYM 0x83
+typedef struct _GPSInfoType
+{
+	uint8 sendTimeUTC[6];
+	uint8 msgMark;
+	uint8 msgCollectionTimeUTC[6];
+	GPSInfo GpsInfoData;
+	uint8 Tac[2];
+	uint8 CellID[4];
+	uint8 xData[2];
+	uint8 yData[2];
+	uint8 zData[2];
+} GPSInfoType;
+typedef struct GPSMsgtoTcpType
+{
+	uint8 startSymbol[2];
+	uint8 cmdSymbol;
+	uint8 ansSymbol;
+	uint8 SN[BATT_SN_LEN];
+	uint8 encryptMethod;
+	uint8 dataLength[2];
+	GPSInfoType gpsInfo;
+	uint8 CRC;
+} GPSMsgtoTcpType;
+typedef struct _VerInfoType
+{
+	uint8 sendTimeUTC[6];
+	uint8 msgMark;
+	uint8 msgCollectionTimeUTC[6];
+	uint8 ICCID[20];
+	uint8 IMEI[15];
+	uint8 BMSHwVersion[2];
+	uint8 BMSSwVersion[4];
+	uint8 HwVersion[2];
+	uint8 BLVersion[4];
+	uint8 DRVVersion[4];
+	uint8 APPVersion[4];
+	uint8 BmsType;
+	uint8 BmsInfo;
+	uint8 DataModuleType;
+} VerInfoType;
+typedef struct VersionMsgtoTcpType
+{
+	uint8 startSymbol[2];
+	uint8 cmdSymbol;
+	uint8 ansSymbol;
+	uint8 SN[BATT_SN_LEN];
+	uint8 encryptMethod;
+	uint8 dataLength[2];
+	VerInfoType VerInfo;
+	uint8 CRC;
+} VersionMsgtoTcpType;
+typedef struct StorageInfoType
+{
+	uint8 sendTimeUTC[6];
+	uint8 msgMark;
+	uint8 msgCollectionTimeUTC[6];
+	uint8 RelayState;
+	uint8 FanState;
+	uint8 HeatState;
+	uint8 ConvertState;
+} StorageInfo;
+typedef struct StorageInfoToTcpType
+{
+	uint8 startSymbol[2];
+	uint8 cmdSymbol;
+	uint8 ansSymbol;
+	uint8 SN[BATT_SN_LEN];
+	uint8 encryptMethod;
+	uint8 dataLength[2];
+	StorageInfo StorageMsg;
+	uint8 CRC;
+} StorageInfoToTcp;
+typedef struct StorageInfoType2
+{
+	uint8 sendTimeUTC[6];
+	uint8 msgMark;
+	uint8 msgCollectionTimeUTC[6];
+	uint8 meter1AllPwr[4];
+	uint8 meter1PosPwr[4];
+	uint8 meter1NegPwr[4];
+	uint8 meter2AllPwr[4];
+	uint8 meter2PosPwr[4];
+	uint8 meter2NegPwr[4];
+} StorageInfo2;
+typedef struct StorageInfoToTcpType2
+{
+	uint8 startSymbol[2];
+	uint8 cmdSymbol;
+	uint8 ansSymbol;
+	uint8 SN[BATT_SN_LEN];
+	uint8 encryptMethod;
+	uint8 dataLength[2];
+	StorageInfo2 StorageMsg2;
+	uint8 CRC;
+} StorageInfoToTcp2;
+typedef struct AccInfoType
+{
+	uint8 sendTimeUTC[6];
+	uint8 msgMark;
+	uint8 msgCollectionTimeUTC[6];
+	uint8 accOnlineDays[2];
+	uint8 accDrvMiles[2];
+	uint8 sohNoCalibrTime[2];
+	uint8 accChrgEng[4];
+	uint8 accDischrgEng[4];
+	uint8 accChrgCap[4];
+	uint8 accDischrgCap[4];
+	uint8 accOverChrgTimes;
+	uint8 accOverDischrgTimes;
+	uint8 accCycleTimes[2];
+}AccInfo;
+typedef struct AccInfoToTcpType
+{
+	uint8 startSymbol[2];
+	uint8 cmdSymbol;
+	uint8 ansSymbol;
+	uint8 SN[BATT_SN_LEN];
+	uint8 encryptMethod;
+	uint8 dataLength[2];
+	AccInfo AccMsg;
+	uint8 CRC;
+}AccInfoToTcp;
+typedef struct UTC8Time_Type
+{
+	uint8 year;
+	uint8 month;
+	uint8 day;
+	uint8 hour;
+	uint8 minute;
+	uint8 second;
+} UTC8TimeType;
+typedef enum
+{
+	AT_CMD_TEST = 0,
+	AT_ATE0,
+	AT_SIMREADY,
+	AT_GETICCID,
+	AT_CGREG,
+	AT_CSQ,
+	AT_NETOPEN,
+	AT_CGIP,
+	AT_CONNECT,
+	AT_CONNECTCHK,
+	AT_SEND,
+	AT_DISCON,
+	AT_NETCLOSE,
+	AT_CGNSSPWR
+} ATCmd;
+typedef sint8 (*pFunc)(char *PSendStr, char *pReadStr, uint8 CmdIdx, uint16 pReadLen);
+sint8 at_callbackFunc(char *PSendStr, char *pReadStr, uint8 CmdIdx, uint16 pReadLen);
+typedef struct
+{
+	ATCmd cmd; /*指令序号*/
+	char *str; /*指令内容*/
+	pFunc cb;  /*对应的执行*/
+} ATCmdFunc;
+typedef enum
+{
+	PROCESS_TCP_IDLE = 0,
+	PROCESS_TCP_ATSYS,
+	PROCESS_TCP_REGCHK,
+	PROCESS_TCP_CONNECT,
+	PROCESS_TCP_SEND,
+	PROCESS_TCP_RECV,
+	PROCESS_TCP_HEART,
+	PROCESS_TCP_SLEEP,
+	PROCESS_TCP_ERROR
+} process_Tcp;
+void Uart_4G_Task(void *pvParameters);
+sint8 tcpipConnectionSend(uint8 TcpConnectId, uint8 *SendDataPtr, uint16 SendDataLen);
+#endif /* APPTASKUART1_H_ */

+ 1 - 1
src/UDSTask.c → code/app/UDSTask.c

@@ -1,7 +1,7 @@
 /*
  * UDSTask.c
  *
- *  Created on: 2022Äê3ÔÂ14ÈÕ
+ *  Created on: 2022Äê3ÔÂ14ÈÕ
  *      Author: Zhengchao
  */
 #include "UDSTask.h"

+ 45 - 0
code/app/UDSTask.h

@@ -0,0 +1,45 @@
+/*
+ * UDSTask.h
+ *
+ *  Created on: 2022Äê3ÔÂ14ÈÕ
+ *      Author: Zhengchao
+ */
+
+
+
+#ifndef UDSTASK_H_
+#define UDSTASK_H_
+
+
+#include "PlatformTypes.h"
+#include "hal_adapter.h"
+#include "USER_CONFIG.h"
+
+#define INFO_START_ADDR                 0x2000EFF0u
+#define REQUEST_ENTER_BOOTLOADER_ADDR   0x2000EFF1u
+#define DOWNLOAD_APP_SUCCESSFUL_ADDR    0x2000EFF0u
+
+#define EN_CRC_SOFTWARE /* Enable CRC module with software */
+
+
+/* TODO Bootloader: #01 CAN RX and TX message ID Configuration */
+#if defined (CAN1_MSG_TYPE)
+	#if (CAN1_MSG_TYPE == CAN_MSG_STANDARD)
+		#define RX_FUN_ADDR_ID       (0x7BFu)    /* FuncReq  - CAN TP RX function ID */
+		#define RX_PHY_ADDR_ID       (0x7A0u)    /* PhysReq  - CAN TP RX physical ID */
+		#define TX_RESP_ADDR_ID      (0x7A8u)    /* PhysResp - CAN TP TX physical ID */
+	#elif (CAN1_MSG_TYPE == CAN_MSG_EXTENDED)
+		#define RX_FUN_ADDR_ID       (0x18DA55FFu)    /* FuncReq  - CAN TP RX function ID */
+		#define RX_PHY_ADDR_ID       (0x18DA5535u)    /* PhysReq  - CAN TP RX physical ID */
+		#define TX_RESP_ADDR_ID      (0x18DA3555u)    /* PhysResp - CAN TP TX physical ID */
+	#endif
+#else
+	#error "please define the CAN MSG Type of can1"
+#endif
+
+
+void RequestEnterBootloader(void);
+boolean IsJumptoBootloader(uint32 CanID, uint8 Data[]);
+void DoRoutinePositiveAnswer(void);
+boolean Boot_CheckDownlaodAPPStatus(void);
+#endif /* UDSTASK_H_ */

+ 1 - 1
src/USER_CONFIG.h → code/app/USER_CONFIG.h

@@ -1,7 +1,7 @@
 /*
  * USER_CONFIG.h
  *
- *  Created on: 2022Äê4ÔÂ27ÈÕ
+ *  Created on: 2022Äê4ÔÂ27ÈÕ
  *      Author: Zhengchao
  */
 

+ 39 - 46
src/AppFuncLib.c → code/app/lib/AppFuncLib.c

@@ -1,25 +1,18 @@
 /*
- * @Author       : ChenJie
- * @Date         : 2022-01-21 09:28:20
- * @Version      : V3.0
- * @LastEditors  : ChenJie
- * @LastEditTime : 2022-02-14 15:23:30
- * @Description  : file content
- * @FilePath     : \S32K146_4G\src\AppFuncLib.c
+ * @Author: chenjie
+ * @Date: 2022-06-06
+ * @LastEditTime: 2022-10-27
+ * @LastEditors: chenjie
+ * @Description: 
+ * @FilePath: \S32K146_4G\code\app\lib\AppFuncLib.c
+ * Copyright (c) 2022 by chenjie, All Rights Reserved.
  */
-/*
- * AppFuncLib.c
- *应用层函数库
- *  Created on: 2022121
- *      Author: QiXiang_CHENJIE
- */
-
 #include "AppFuncLib.h"
 #include "AppGlobalVar.h"
 #include "Hal_Fls.h"
 #include "AppTaskUart1.h"
 /**
- * @brief : 获取故障码函数,从故障数组中获取故障码,并将之前的故障码向前移动
+ * @brief : 鑾峰彇鏁呴殰鐮佸嚱鏁帮紝浠庢晠闅滄暟缁勪腑鑾峰彇鏁呴殰鐮侊紝骞跺皢涔嬪墠鐨勬晠闅滅爜鍚戝墠绉诲姩
  * @param {UINT16} *ErrorArray
  * @param {UINT8} Errorlen
  * @return {*}
@@ -114,7 +107,7 @@ unsigned char HexToChar(unsigned char bHex)
 {
     if ((bHex >= 0) && (bHex <= 9))
         bHex += 0x30;
-    else if ((bHex >= 10) && (bHex <= 15)) //大写字母
+    else if ((bHex >= 10) && (bHex <= 15)) //澶у啓瀛楁瘝
         bHex += 0x37;
     else
         bHex = 0xff;
@@ -124,9 +117,9 @@ unsigned char CharToHex(unsigned char bChar)
 {
     if ((bChar >= 0x30) && (bChar <= 0x39))
         bChar -= 0x30;
-    else if ((bChar >= 0x41) && (bChar <= 0x46)) //大写字母
+    else if ((bChar >= 0x41) && (bChar <= 0x46)) //澶у啓瀛楁瘝
         bChar -= 0x37;
-    else if ((bChar >= 0x61) && (bChar <= 0x66)) //小写字母
+    else if ((bChar >= 0x61) && (bChar <= 0x66)) //灏忓啓瀛楁瘝
         bChar -= 0x57;
     else
         bChar = 0xff;
@@ -137,7 +130,7 @@ uint8 AtStrCompare(const char *a, const char *b)
     uint8 out = 1;
     while (1)
     {
-        if (*a == '\0' || *b == '\0') //判断其中是否有字符串结束
+        if (*a == '\0' || *b == '\0') //鍒ゆ柇鍏朵腑鏄�惁鏈夊瓧绗︿覆缁撴潫
         {
             if (strlen(a) == strlen(b))
             {
@@ -221,10 +214,10 @@ char *Myitoa(int value, char *result, int base)
 }
 
 /************************************************************************
- * @brief 整数转字符串
- * @param[in] num 整数
- * @param[out] buf 字符串
- * @return 返回字符串长度
+ * @brief 鏁存暟杞�瓧绗︿覆
+ * @param[in] num 鏁存暟
+ * @param[out] buf 瀛楃�涓�
+ * @return 杩斿洖瀛楃�涓查暱搴�
  ************************************************************************/
 inline int _itoa(int num, char buf[32])
 {
@@ -232,11 +225,11 @@ inline int _itoa(int num, char buf[32])
 }
 
 /************************************************************************
- * @brief 整数转字符串
- * @param[in] num 整数
- * @param[out] buf 字符串
- * @param[in] radix 进位制整数
- * @return 返回字符串长度
+ * @brief 鏁存暟杞�瓧绗︿覆
+ * @param[in] num 鏁存暟
+ * @param[out] buf 瀛楃�涓�
+ * @param[in] radix 杩涗綅鍒舵暣鏁�
+ * @return 杩斿洖瀛楃�涓查暱搴�
  ************************************************************************/
 int _i2a(int num, char buf[32], int radix)
 {
@@ -270,11 +263,11 @@ int _i2a(int num, char buf[32], int radix)
 }
 
 /************************************************************************
- * @brief 浮点数转字符串
- * @param[in] val 浮点数
- * @param[out] buf 字符串
- * @param[in] eps 精度(小数位)
- * @return 返回字符串长度
+ * @brief 娴�偣鏁拌浆瀛楃�涓�
+ * @param[in] val 娴�偣鏁�
+ * @param[out] buf 瀛楃�涓�
+ * @param[in] eps 绮惧害(灏忔暟浣�)
+ * @return 杩斿洖瀛楃�涓查暱搴�
  ************************************************************************/
 int _ftoa(double val, char buf[32], int eps)
 {
@@ -291,11 +284,11 @@ int _ftoa(double val, char buf[32], int eps)
 }
 
 /************************************************************************
- * @brief 浮点数转字符串:范围(-1, 1)
- * @param[in] val 浮点数
- * @param[out] buf 字符串
- * @param[in] eps 精度(小数位)
- * @return 返回字符串长度
+ * @brief 娴�偣鏁拌浆瀛楃�涓诧細鑼冨洿(-1, 1)
+ * @param[in] val 娴�偣鏁�
+ * @param[out] buf 瀛楃�涓�
+ * @param[in] eps 绮惧害(灏忔暟浣�)
+ * @return 杩斿洖瀛楃�涓查暱搴�
  ************************************************************************/
 int __ftoa(double val, char buf[32], int eps)
 {
@@ -315,8 +308,8 @@ int __ftoa(double val, char buf[32], int eps)
 }
 
 /************************************************************************
- * @brief 替换sprintf
- * @ref 可变长参数列表误区与陷阱——va_arg不可接受的类型
+ * @brief 鏇挎崲sprintf
+ * @ref 鍙�彉闀垮弬鏁板垪琛ㄨ�鍖轰笌闄烽槺鈥斺€攙a_arg涓嶅彲鎺ュ彈鐨勭被鍨�
  * http://www.cppblog.com/ownwaterloo/archive/2009/04/21/80655.aspx
  ************************************************************************/
 int _sprintf(char *dst, const char *format, ...)
@@ -338,7 +331,7 @@ int _sprintf(char *dst, const char *format, ...)
             ++f;
             switch (*f)
             {
-            case 's': // 字符串
+            case 's': // 瀛楃�涓�
             {
                 const char *p = va_arg(ap, char *);
                 n = strlen(p);
@@ -347,7 +340,7 @@ int _sprintf(char *dst, const char *format, ...)
             break;
 
             case 'd':
-            case 'u': // 整数
+            case 'u': // 鏁存暟
             {
                 char buf[32];
                 n = _itoa(va_arg(ap, int), buf);
@@ -355,7 +348,7 @@ int _sprintf(char *dst, const char *format, ...)
             }
             break;
 
-            case 'f': // 浮点数
+            case 'f': // 娴�偣鏁�
             {
                 char buf[32];
                 n = _ftoa(va_arg(ap, double), buf, 6);
@@ -363,7 +356,7 @@ int _sprintf(char *dst, const char *format, ...)
             }
             break;
 
-            case 'x': // 16进制数
+            case 'x': // 16杩涘埗鏁�
             {
                 char buf[32];
                 n = _i2a(va_arg(ap, int), buf, 16);
@@ -371,13 +364,13 @@ int _sprintf(char *dst, const char *format, ...)
             }
             break;
 
-            case 'c': // 字符
+            case 'c': // 瀛楃�
             {
                 *s = va_arg(ap, int);
             }
             break;
 
-            case '%': // 百分号
+            case '%': // 鐧惧垎鍙�
             {
                 *s = '%';
             }

+ 13 - 19
src/AppFuncLib.h → code/app/lib/AppFuncLib.h

@@ -1,17 +1,11 @@
-/*
- * @Author       : ChenJie
- * @Date         : 2022-01-23 13:45:09
- * @Version      : V3.0
- * @LastEditors  : ChenJie
- * @LastEditTime : 2022-02-14 15:24:03
- * @Description  : file content
- * @FilePath     : \S32K146_4G\src\AppFuncLib.h
- */
-/*
- * AppFunc.h
- *应用层函数库
- *  Created on: 2022年1月21日
- *      Author: QiXiang_CHENJIE
+/*** 
+ * @Author: chenjie
+ * @Date: 2022-06-06
+ * @LastEditTime: 2022-10-27
+ * @LastEditors: chenjie
+ * @Description: 
+ * @FilePath: \S32K146_4G\code\app\lib\AppFuncLib.h
+ * @Copyright (c) 2022 by chenjie, All Rights Reserved.
  */
 
 #ifndef APPFUNCLIB_H_
@@ -33,20 +27,20 @@ uint8 AtStrCompare(const char *a, const char *b);
 unsigned short CRC16_Modbus(unsigned char *pdata, int len);
 uint8 bcc_chk(uint8 *data, uint16 length);
 char *Myitoa(int value, char *result, int base);
-// 整数转字符串
+// 鏁存暟杞�瓧绗︿覆
 int _itoa(int num, char buf[32]);
 
 int _i2a(int num, char buf[32], int radix);
 
-// 浮点转字符串
+// 娴�偣杞�瓧绗︿覆
 int _ftoa(double val, char buf[32], int eps);
 
-// 浮点转字符串,范围(-1,1)
+// 娴�偣杞�瓧绗︿覆锛岃寖鍥达紙-1锛�1锛�
 int __ftoa(double val, char buf[32], int eps);
 
-// 替代sprintf
+// 鏇夸唬sprintf
 int _sprintf(char *dst, const char *format, ...);
-//串口校验
+//涓插彛鏍¢獙
 uint16 crc_chk(uint8 *data, uint8 length);
 void Fota_Func(uint8 *DataPtr, sint32 connectId);
 #endif /* APPFUNCLIB_H_ */

+ 113 - 0
code/debug/SEGGER/Global.h

@@ -0,0 +1,113 @@
+/*********************************************************************
+*                    SEGGER Microcontroller GmbH                     *
+*                        The Embedded Experts                        *
+**********************************************************************
+*                                                                    *
+*            (c) 1995 - 2021 SEGGER Microcontroller GmbH             *
+*                                                                    *
+*       www.segger.com     Support: support@segger.com               *
+*                                                                    *
+**********************************************************************
+*                                                                    *
+*       SEGGER SystemView * Real-time application analysis           *
+*                                                                    *
+**********************************************************************
+*                                                                    *
+* All rights reserved.                                               *
+*                                                                    *
+* SEGGER strongly recommends to not make any changes                 *
+* to or modify the source code of this software in order to stay     *
+* compatible with the SystemView and RTT protocol, and J-Link.       *
+*                                                                    *
+* Redistribution and use in source and binary forms, with or         *
+* without modification, are permitted provided that the following    *
+* condition is met:                                                  *
+*                                                                    *
+* o Redistributions of source code must retain the above copyright   *
+*   notice, this condition and the following disclaimer.             *
+*                                                                    *
+* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND             *
+* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,        *
+* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF           *
+* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE           *
+* DISCLAIMED. IN NO EVENT SHALL SEGGER Microcontroller BE LIABLE FOR *
+* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR           *
+* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT  *
+* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;    *
+* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF      *
+* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT          *
+* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE  *
+* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH   *
+* DAMAGE.                                                            *
+*                                                                    *
+**********************************************************************
+*                                                                    *
+*       SystemView version: 3.32                                    *
+*                                                                    *
+**********************************************************************
+----------------------------------------------------------------------
+File    : Global.h
+Purpose : Global types
+          In case your application already has a Global.h, you should
+          merge the files. In order to use Segger code, the types
+          U8, U16, U32, I8, I16, I32 need to be defined in Global.h;
+          additional definitions do not hurt.
+Revision: $Rev: 12501 $
+---------------------------END-OF-HEADER------------------------------
+*/
+
+#ifndef GLOBAL_H            // Guard against multiple inclusion
+#define GLOBAL_H
+
+#define U8    unsigned char
+#define I8    signed char
+#define U16   unsigned short
+#define I16   signed short
+#ifdef __x86_64__
+#define U32   unsigned
+#define I32   int
+#else
+#define U32   unsigned long
+#define I32   signed long
+#endif
+
+//
+// CC_NO_LONG_SUPPORT can be defined to compile test
+// without long support for compilers that do not
+// support C99 and its long type.
+//
+#ifdef CC_NO_LONG_SUPPORT
+  #define PTR_ADDR  U32
+#else  // Supports long type.
+#if defined(_WIN32) && !defined(__clang__) && !defined(__MINGW32__)
+  //
+  // Microsoft VC6 compiler related
+  //
+  #define U64   unsigned __int64
+  #define U128  unsigned __int128
+  #define I64   __int64
+  #define I128  __int128
+  #if _MSC_VER <= 1200
+    #define U64_C(x) x##UI64
+  #else
+    #define U64_C(x) x##ULL
+  #endif
+#else
+  //
+  // C99 compliant compiler
+  //
+  #define U64   unsigned long long
+  #define I64   signed long long
+  #define U64_C(x) x##ULL
+#endif
+
+#if (defined(_WIN64) || defined(__LP64__))  // 64-bit symbols used by Visual Studio and GCC, maybe others as well.
+  #define PTR_ADDR  U64
+#else
+  #define PTR_ADDR  U32
+#endif
+#endif  // Supports long type.
+
+#endif                      // Avoid multiple inclusion
+
+/*************************** End of file ****************************/

+ 248 - 0
code/debug/SEGGER/SEGGER.h

@@ -0,0 +1,248 @@
+/*********************************************************************
+*                    SEGGER Microcontroller GmbH                     *
+*                        The Embedded Experts                        *
+**********************************************************************
+*                                                                    *
+*            (c) 1995 - 2021 SEGGER Microcontroller GmbH             *
+*                                                                    *
+*       www.segger.com     Support: support@segger.com               *
+*                                                                    *
+**********************************************************************
+*                                                                    *
+*       SEGGER SystemView * Real-time application analysis           *
+*                                                                    *
+**********************************************************************
+*                                                                    *
+* All rights reserved.                                               *
+*                                                                    *
+* SEGGER strongly recommends to not make any changes                 *
+* to or modify the source code of this software in order to stay     *
+* compatible with the SystemView and RTT protocol, and J-Link.       *
+*                                                                    *
+* Redistribution and use in source and binary forms, with or         *
+* without modification, are permitted provided that the following    *
+* condition is met:                                                  *
+*                                                                    *
+* o Redistributions of source code must retain the above copyright   *
+*   notice, this condition and the following disclaimer.             *
+*                                                                    *
+* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND             *
+* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,        *
+* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF           *
+* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE           *
+* DISCLAIMED. IN NO EVENT SHALL SEGGER Microcontroller BE LIABLE FOR *
+* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR           *
+* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT  *
+* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;    *
+* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF      *
+* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT          *
+* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE  *
+* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH   *
+* DAMAGE.                                                            *
+*                                                                    *
+**********************************************************************
+*                                                                    *
+*       SystemView version: 3.32                                    *
+*                                                                    *
+**********************************************************************
+----------------------------------------------------------------------
+File    : SEGGER.h
+Purpose : Global types etc & general purpose utility functions
+Revision: $Rev: 18102 $
+---------------------------END-OF-HEADER------------------------------
+*/
+
+#ifndef SEGGER_H            // Guard against multiple inclusion
+#define SEGGER_H
+
+#include <stdarg.h>         // For va_list.
+#include "Global.h"         // Type definitions: U8, U16, U32, I8, I16, I32
+
+#if defined(__cplusplus)
+extern "C" {     /* Make sure we have C-declarations in C++ programs */
+#endif
+
+/*********************************************************************
+*
+*       Keywords/specifiers
+*
+**********************************************************************
+*/
+
+#ifndef INLINE
+  #if (defined(__ICCARM__) || defined(__RX) || defined(__ICCRX__))
+    //
+    // Other known compilers.
+    //
+    #define INLINE  inline
+  #else
+    #if (defined(_WIN32) && !defined(__clang__))
+      //
+      // Microsoft VC6 and newer.
+      // Force inlining without cost checking.
+      //
+      #define INLINE  __forceinline
+    #elif defined(__GNUC__) || defined(__clang__)
+      //
+      // Force inlining with GCC + clang
+      //
+      #define INLINE inline __attribute__((always_inline))
+    #elif (defined(__CC_ARM))
+      //
+      // Force inlining with ARMCC (Keil)
+      //
+      #define INLINE  __inline
+    #else
+      //
+      // Unknown compilers.
+      //
+      #define INLINE
+    #endif
+  #endif
+#endif
+
+/*********************************************************************
+*
+*       Function-like macros
+*
+**********************************************************************
+*/
+
+#define SEGGER_COUNTOF(a)          (sizeof((a))/sizeof((a)[0]))
+#define SEGGER_MIN(a,b)            (((a) < (b)) ? (a) : (b))
+#define SEGGER_MAX(a,b)            (((a) > (b)) ? (a) : (b))
+
+#ifndef   SEGGER_USE_PARA                   // Some compiler complain about unused parameters.
+  #define SEGGER_USE_PARA(Para) (void)Para  // This works for most compilers.
+#endif
+
+#define SEGGER_ADDR2PTR(Type, Addr)  (/*lint -e(923) -e(9078)*/((Type*)((PTR_ADDR)(Addr))))    // Allow cast from address to pointer.
+#define SEGGER_PTR2ADDR(p)           (/*lint -e(923) -e(9078)*/((PTR_ADDR)(p)))                // Allow cast from pointer to address.
+#define SEGGER_PTR2PTR(Type, p)      (/*lint -e(740) -e(826) -e(9079) -e(9087)*/((Type*)(p)))  // Allow cast from one pointer type to another (ignore different size).
+#define SEGGER_PTR_DISTANCE(p0, p1)  (SEGGER_PTR2ADDR(p0) - SEGGER_PTR2ADDR(p1))
+
+/*********************************************************************
+*
+*       Defines
+*
+**********************************************************************
+*/
+
+#define SEGGER_PRINTF_FLAG_ADJLEFT    (1 << 0)
+#define SEGGER_PRINTF_FLAG_SIGNFORCE  (1 << 1)
+#define SEGGER_PRINTF_FLAG_SIGNSPACE  (1 << 2)
+#define SEGGER_PRINTF_FLAG_PRECEED    (1 << 3)
+#define SEGGER_PRINTF_FLAG_ZEROPAD    (1 << 4)
+#define SEGGER_PRINTF_FLAG_NEGATIVE   (1 << 5)
+
+/*********************************************************************
+*
+*       Types
+*
+**********************************************************************
+*/
+
+typedef struct {
+  char* pBuffer;
+  int   BufferSize;
+  int   Cnt;
+} SEGGER_BUFFER_DESC;
+
+typedef struct {
+  unsigned int CacheLineSize;                             // 0: No Cache. Most Systems such as ARM9 use a 32 bytes cache line size.
+  void (*pfDMB)       (void);                             // Optional DMB function for Data Memory Barrier to make sure all memory operations are completed.
+  void (*pfClean)     (void *p, unsigned long NumBytes);  // Optional clean function for cached memory.
+  void (*pfInvalidate)(void *p, unsigned long NumBytes);  // Optional invalidate function for cached memory.
+} SEGGER_CACHE_CONFIG;
+
+typedef struct SEGGER_SNPRINTF_CONTEXT_struct SEGGER_SNPRINTF_CONTEXT;
+
+struct SEGGER_SNPRINTF_CONTEXT_struct {
+  void*               pContext;                       // Application specific context.
+  SEGGER_BUFFER_DESC* pBufferDesc;                    // Buffer descriptor to use for output.
+  void (*pfFlush)(SEGGER_SNPRINTF_CONTEXT* pContext); // Callback executed once the buffer is full. Callback decides if the buffer gets cleared to store more or not.
+};
+
+typedef struct {
+  void (*pfStoreChar)       (SEGGER_BUFFER_DESC* pBufferDesc, SEGGER_SNPRINTF_CONTEXT* pContext, char c);
+  int  (*pfPrintUnsigned)   (SEGGER_BUFFER_DESC* pBufferDesc, SEGGER_SNPRINTF_CONTEXT* pContext, U32 v, unsigned Base, char Flags, int Width, int Precision);
+  int  (*pfPrintInt)        (SEGGER_BUFFER_DESC* pBufferDesc, SEGGER_SNPRINTF_CONTEXT* pContext, I32 v, unsigned Base, char Flags, int Width, int Precision);
+} SEGGER_PRINTF_API;
+
+typedef void (*SEGGER_pFormatter)(SEGGER_BUFFER_DESC* pBufferDesc, SEGGER_SNPRINTF_CONTEXT* pContext, const SEGGER_PRINTF_API* pApi, va_list* pParamList, char Lead, int Width, int Precision);
+
+typedef struct SEGGER_PRINTF_FORMATTER {
+  struct SEGGER_PRINTF_FORMATTER* pNext;              // Pointer to next formatter.
+  SEGGER_pFormatter               pfFormatter;        // Formatter function.
+  char                            Specifier;          // Format specifier.
+} SEGGER_PRINTF_FORMATTER;
+
+typedef struct {
+  U32 (*pfGetHPTimestamp)(void);          // Mandatory, pfGetHPTimestamp
+  int (*pfGetUID)        (U8 abUID[16]);  // Optional,  pfGetUID
+} SEGGER_BSP_API;
+
+/*********************************************************************
+*
+*       Utility functions
+*
+**********************************************************************
+*/
+
+//
+// Memory operations.
+//
+void SEGGER_ARM_memcpy(void* pDest, const void* pSrc, int NumBytes);
+void SEGGER_memcpy    (void* pDest, const void* pSrc, unsigned NumBytes);
+void SEGGER_memxor    (void* pDest, const void* pSrc, unsigned NumBytes);
+
+//
+// String functions.
+//
+int      SEGGER_atoi       (const char* s);
+int      SEGGER_isalnum    (int c);
+int      SEGGER_isalpha    (int c);
+unsigned SEGGER_strlen     (const char* s);
+int      SEGGER_tolower    (int c);
+int      SEGGER_strcasecmp (const char* sText1, const char* sText2);
+int      SEGGER_strncasecmp(const char *sText1, const char *sText2, unsigned Count);
+
+//
+// Buffer/printf related.
+//
+void SEGGER_StoreChar    (SEGGER_BUFFER_DESC* pBufferDesc, char c);
+void SEGGER_PrintUnsigned(SEGGER_BUFFER_DESC* pBufferDesc, U32 v, unsigned Base, int Precision);
+void SEGGER_PrintInt     (SEGGER_BUFFER_DESC* pBufferDesc, I32 v, unsigned Base, int Precision);
+int  SEGGER_snprintf     (char* pBuffer, int BufferSize, const char* sFormat, ...);
+int  SEGGER_vsnprintf    (char* pBuffer, int BufferSize, const char* sFormat, va_list ParamList);
+int  SEGGER_vsnprintfEx  (SEGGER_SNPRINTF_CONTEXT* pContext, const char* sFormat, va_list ParamList);
+
+int  SEGGER_PRINTF_AddFormatter       (SEGGER_PRINTF_FORMATTER* pFormatter, SEGGER_pFormatter pfFormatter, char c);
+void SEGGER_PRINTF_AddDoubleFormatter (void);
+void SEGGER_PRINTF_AddIPFormatter     (void);
+void SEGGER_PRINTF_AddBLUEFormatter   (void);
+void SEGGER_PRINTF_AddCONNECTFormatter(void);
+void SEGGER_PRINTF_AddSSLFormatter    (void);
+void SEGGER_PRINTF_AddSSHFormatter    (void);
+void SEGGER_PRINTF_AddHTMLFormatter   (void);
+
+//
+// BSP abstraction API.
+//
+int  SEGGER_BSP_GetUID  (U8 abUID[16]);
+int  SEGGER_BSP_GetUID32(U32* pUID);
+void SEGGER_BSP_SetAPI  (const SEGGER_BSP_API* pAPI);
+void SEGGER_BSP_SeedUID (void);
+
+//
+// Other API.
+//
+void SEGGER_VERSION_GetString(char acText[8], unsigned Version);
+
+#if defined(__cplusplus)
+}                /* Make sure we have C-declarations in C++ programs */
+#endif
+
+#endif                      // Avoid multiple inclusion
+
+/*************************** End of file ****************************/

+ 2095 - 0
code/debug/SEGGER/SEGGER_RTT.c

@@ -0,0 +1,2095 @@
+/*********************************************************************
+*                    SEGGER Microcontroller GmbH                     *
+*                        The Embedded Experts                        *
+**********************************************************************
+*                                                                    *
+*            (c) 1995 - 2021 SEGGER Microcontroller GmbH             *
+*                                                                    *
+*       www.segger.com     Support: support@segger.com               *
+*                                                                    *
+**********************************************************************
+*                                                                    *
+*       SEGGER SystemView * Real-time application analysis           *
+*                                                                    *
+**********************************************************************
+*                                                                    *
+* All rights reserved.                                               *
+*                                                                    *
+* SEGGER strongly recommends to not make any changes                 *
+* to or modify the source code of this software in order to stay     *
+* compatible with the SystemView and RTT protocol, and J-Link.       *
+*                                                                    *
+* Redistribution and use in source and binary forms, with or         *
+* without modification, are permitted provided that the following    *
+* condition is met:                                                  *
+*                                                                    *
+* o Redistributions of source code must retain the above copyright   *
+*   notice, this condition and the following disclaimer.             *
+*                                                                    *
+* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND             *
+* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,        *
+* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF           *
+* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE           *
+* DISCLAIMED. IN NO EVENT SHALL SEGGER Microcontroller BE LIABLE FOR *
+* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR           *
+* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT  *
+* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;    *
+* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF      *
+* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT          *
+* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE  *
+* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH   *
+* DAMAGE.                                                            *
+*                                                                    *
+**********************************************************************
+*                                                                    *
+*       SystemView version: 3.32                                    *
+*                                                                    *
+**********************************************************************
+---------------------------END-OF-HEADER------------------------------
+File    : SEGGER_RTT.c
+Purpose : Implementation of SEGGER real-time transfer (RTT) which
+          allows real-time communication on targets which support
+          debugger memory accesses while the CPU is running.
+Revision: $Rev: 25842 $
+
+Additional information:
+          Type "int" is assumed to be 32-bits in size
+          H->T    Host to target communication
+          T->H    Target to host communication
+
+          RTT channel 0 is always present and reserved for Terminal usage.
+          Name is fixed to "Terminal"
+
+          Effective buffer size: SizeOfBuffer - 1
+
+          WrOff == RdOff:       Buffer is empty
+          WrOff == (RdOff - 1): Buffer is full
+          WrOff >  RdOff:       Free space includes wrap-around
+          WrOff <  RdOff:       Used space includes wrap-around
+          (WrOff == (SizeOfBuffer - 1)) && (RdOff == 0):  
+                                Buffer full and wrap-around after next byte
+
+
+----------------------------------------------------------------------
+*/
+
+#include "SEGGER_RTT.h"
+
+#include <string.h>                 // for memcpy
+
+/*********************************************************************
+*
+*       Configuration, default values
+*
+**********************************************************************
+*/
+
+#if SEGGER_RTT_CPU_CACHE_LINE_SIZE
+  #ifdef SEGGER_RTT_CB_ALIGN
+    #error "Custom SEGGER_RTT_CB_ALIGN() is not supported for SEGGER_RTT_CPU_CACHE_LINE_SIZE != 0"
+  #endif
+  #ifdef SEGGER_RTT_BUFFER_ALIGN
+    #error "Custom SEGGER_RTT_BUFFER_ALIGN() is not supported for SEGGER_RTT_CPU_CACHE_LINE_SIZE != 0"
+  #endif
+  #ifdef SEGGER_RTT_PUT_CB_SECTION
+    #error "Custom SEGGER_RTT_PUT_CB_SECTION() is not supported for SEGGER_RTT_CPU_CACHE_LINE_SIZE != 0"
+  #endif
+  #ifdef SEGGER_RTT_PUT_BUFFER_SECTION
+    #error "Custom SEGGER_RTT_PUT_BUFFER_SECTION() is not supported for SEGGER_RTT_CPU_CACHE_LINE_SIZE != 0"
+  #endif
+  #ifdef SEGGER_RTT_BUFFER_ALIGNMENT
+    #error "Custom SEGGER_RTT_BUFFER_ALIGNMENT is not supported for SEGGER_RTT_CPU_CACHE_LINE_SIZE != 0"
+  #endif
+  #ifdef SEGGER_RTT_ALIGNMENT
+    #error "Custom SEGGER_RTT_ALIGNMENT is not supported for SEGGER_RTT_CPU_CACHE_LINE_SIZE != 0"
+  #endif
+#endif
+
+#ifndef   BUFFER_SIZE_UP
+  #define BUFFER_SIZE_UP                                  1024  // Size of the buffer for terminal output of target, up to host
+#endif
+
+#ifndef   BUFFER_SIZE_DOWN
+  #define BUFFER_SIZE_DOWN                                16    // Size of the buffer for terminal input to target from host (Usually keyboard input)
+#endif
+
+#ifndef   SEGGER_RTT_MAX_NUM_UP_BUFFERS
+  #define SEGGER_RTT_MAX_NUM_UP_BUFFERS                    2    // Number of up-buffers (T->H) available on this target
+#endif
+
+#ifndef   SEGGER_RTT_MAX_NUM_DOWN_BUFFERS
+  #define SEGGER_RTT_MAX_NUM_DOWN_BUFFERS                  2    // Number of down-buffers (H->T) available on this target
+#endif
+
+#ifndef SEGGER_RTT_BUFFER_SECTION
+  #if defined(SEGGER_RTT_SECTION)
+    #define SEGGER_RTT_BUFFER_SECTION SEGGER_RTT_SECTION
+  #endif
+#endif
+
+#ifndef   SEGGER_RTT_ALIGNMENT
+  #define SEGGER_RTT_ALIGNMENT                            SEGGER_RTT_CPU_CACHE_LINE_SIZE
+#endif
+
+#ifndef   SEGGER_RTT_BUFFER_ALIGNMENT
+  #define SEGGER_RTT_BUFFER_ALIGNMENT                     SEGGER_RTT_CPU_CACHE_LINE_SIZE
+#endif
+
+#ifndef   SEGGER_RTT_MODE_DEFAULT
+  #define SEGGER_RTT_MODE_DEFAULT                         SEGGER_RTT_MODE_NO_BLOCK_SKIP
+#endif
+
+#ifndef   SEGGER_RTT_LOCK
+  #define SEGGER_RTT_LOCK()
+#endif
+
+#ifndef   SEGGER_RTT_UNLOCK
+  #define SEGGER_RTT_UNLOCK()
+#endif
+
+#ifndef   STRLEN
+  #define STRLEN(a)                                       strlen((a))
+#endif
+
+#ifndef   STRCPY
+  #define STRCPY(pDest, pSrc)                             strcpy((pDest), (pSrc))
+#endif
+
+#ifndef   SEGGER_RTT_MEMCPY_USE_BYTELOOP
+  #define SEGGER_RTT_MEMCPY_USE_BYTELOOP                  0
+#endif
+
+#ifndef   SEGGER_RTT_MEMCPY
+  #ifdef  MEMCPY
+    #define SEGGER_RTT_MEMCPY(pDest, pSrc, NumBytes)      MEMCPY((pDest), (pSrc), (NumBytes))
+  #else
+    #define SEGGER_RTT_MEMCPY(pDest, pSrc, NumBytes)      memcpy((pDest), (pSrc), (NumBytes))
+  #endif
+#endif
+
+#ifndef   MIN
+  #define MIN(a, b)         (((a) < (b)) ? (a) : (b))
+#endif
+
+#ifndef   MAX
+  #define MAX(a, b)         (((a) > (b)) ? (a) : (b))
+#endif
+//
+// For some environments, NULL may not be defined until certain headers are included
+//
+#ifndef NULL
+  #define NULL 0
+#endif
+
+/*********************************************************************
+*
+*       Defines, fixed
+*
+**********************************************************************
+*/
+#if (defined __ICCARM__) || (defined __ICCRX__)
+  #define RTT_PRAGMA(P) _Pragma(#P)
+#endif
+
+#if SEGGER_RTT_ALIGNMENT || SEGGER_RTT_BUFFER_ALIGNMENT
+  #if ((defined __GNUC__) || (defined __clang__))
+    #define SEGGER_RTT_ALIGN(Var, Alignment) Var __attribute__ ((aligned (Alignment)))
+  #elif (defined __ICCARM__) || (defined __ICCRX__)
+    #define PRAGMA(A) _Pragma(#A)
+#define SEGGER_RTT_ALIGN(Var, Alignment) RTT_PRAGMA(data_alignment=Alignment) \
+                                  Var
+  #elif (defined __CC_ARM)
+    #define SEGGER_RTT_ALIGN(Var, Alignment) Var __attribute__ ((aligned (Alignment)))
+  #else
+    #error "Alignment not supported for this compiler."
+  #endif
+#else
+  #define SEGGER_RTT_ALIGN(Var, Alignment) Var
+#endif
+
+#if defined(SEGGER_RTT_SECTION) || defined (SEGGER_RTT_BUFFER_SECTION)
+  #if ((defined __GNUC__) || (defined __clang__))
+    #define SEGGER_RTT_PUT_SECTION(Var, Section) __attribute__ ((section (Section))) Var
+  #elif (defined __ICCARM__) || (defined __ICCRX__)
+#define SEGGER_RTT_PUT_SECTION(Var, Section) RTT_PRAGMA(location=Section) \
+                                        Var
+  #elif (defined __CC_ARM)
+    #define SEGGER_RTT_PUT_SECTION(Var, Section) __attribute__ ((section (Section), zero_init))  Var
+  #else
+    #error "Section placement not supported for this compiler."
+  #endif
+#else
+  #define SEGGER_RTT_PUT_SECTION(Var, Section) Var
+#endif
+
+#if SEGGER_RTT_ALIGNMENT
+  #define SEGGER_RTT_CB_ALIGN(Var)  SEGGER_RTT_ALIGN(Var, SEGGER_RTT_ALIGNMENT)
+#else
+  #define SEGGER_RTT_CB_ALIGN(Var)  Var
+#endif
+
+#if SEGGER_RTT_BUFFER_ALIGNMENT
+  #define SEGGER_RTT_BUFFER_ALIGN(Var)  SEGGER_RTT_ALIGN(Var, SEGGER_RTT_BUFFER_ALIGNMENT)
+#else
+  #define SEGGER_RTT_BUFFER_ALIGN(Var)  Var
+#endif
+
+
+#if defined(SEGGER_RTT_SECTION)
+  #define SEGGER_RTT_PUT_CB_SECTION(Var) SEGGER_RTT_PUT_SECTION(Var, SEGGER_RTT_SECTION)
+#else
+  #define SEGGER_RTT_PUT_CB_SECTION(Var) Var
+#endif
+
+#if defined(SEGGER_RTT_BUFFER_SECTION)
+  #define SEGGER_RTT_PUT_BUFFER_SECTION(Var) SEGGER_RTT_PUT_SECTION(Var, SEGGER_RTT_BUFFER_SECTION)
+#else
+  #define SEGGER_RTT_PUT_BUFFER_SECTION(Var) Var
+#endif
+
+/*********************************************************************
+*
+*       Static const data
+*
+**********************************************************************
+*/
+
+static unsigned char _aTerminalId[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
+
+/*********************************************************************
+*
+*       Static data
+*
+**********************************************************************
+*/
+
+//
+// RTT Control Block and allocate buffers for channel 0
+//
+#if SEGGER_RTT_CPU_CACHE_LINE_SIZE
+  #if ((defined __GNUC__) || (defined __clang__))
+    SEGGER_RTT_CB _SEGGER_RTT                                                             __attribute__ ((aligned (SEGGER_RTT_CPU_CACHE_LINE_SIZE)));
+    static char   _acUpBuffer  [SEGGER_RTT__ROUND_UP_2_CACHE_LINE_SIZE(BUFFER_SIZE_UP)]   __attribute__ ((aligned (SEGGER_RTT_CPU_CACHE_LINE_SIZE)));
+    static char   _acDownBuffer[SEGGER_RTT__ROUND_UP_2_CACHE_LINE_SIZE(BUFFER_SIZE_DOWN)] __attribute__ ((aligned (SEGGER_RTT_CPU_CACHE_LINE_SIZE)));
+  #else
+    #error "Don't know how to place _SEGGER_RTT, _acUpBuffer, _acDownBuffer cache-line aligned"
+  #endif
+#else
+  SEGGER_RTT_PUT_CB_SECTION(SEGGER_RTT_CB_ALIGN(SEGGER_RTT_CB _SEGGER_RTT));
+  SEGGER_RTT_PUT_BUFFER_SECTION(SEGGER_RTT_BUFFER_ALIGN(static char _acUpBuffer  [BUFFER_SIZE_UP]));
+  SEGGER_RTT_PUT_BUFFER_SECTION(SEGGER_RTT_BUFFER_ALIGN(static char _acDownBuffer[BUFFER_SIZE_DOWN]));
+#endif
+
+static unsigned char _ActiveTerminal;
+
+/*********************************************************************
+*
+*       Static functions
+*
+**********************************************************************
+*/
+
+/*********************************************************************
+*
+*       _DoInit()
+*
+*  Function description
+*    Initializes the control block an buffers.
+*    May only be called via INIT() to avoid overriding settings.
+*
+*/
+#define INIT()  {                                                                                    \
+                  volatile SEGGER_RTT_CB* pRTTCBInit;                                                \
+                  pRTTCBInit = (volatile SEGGER_RTT_CB*)((char*)&_SEGGER_RTT + SEGGER_RTT_UNCACHED_OFF); \
+                  do {                                                                               \
+                    if (pRTTCBInit->acID[0] == '\0') {                                               \
+                      _DoInit();                                                                     \
+                    }                                                                                \
+                  } while (0);                                                                       \
+                }
+
+static void _DoInit(void) {
+  volatile SEGGER_RTT_CB* p;   // Volatile to make sure that compiler cannot change the order of accesses to the control block
+  static const char _aInitStr[] = "\0\0\0\0\0\0TTR REGGES";  // Init complete ID string to make sure that things also work if RTT is linked to a no-init memory area
+  unsigned i;
+  //
+  // Initialize control block
+  //
+  p                     = (volatile SEGGER_RTT_CB*)((char*)&_SEGGER_RTT + SEGGER_RTT_UNCACHED_OFF);  // Access control block uncached so that nothing in the cache ever becomes dirty and all changes are visible in HW directly
+  memset((SEGGER_RTT_CB*)p, 0, sizeof(_SEGGER_RTT));         // Make sure that the RTT CB is always zero initialized.
+  p->MaxNumUpBuffers    = SEGGER_RTT_MAX_NUM_UP_BUFFERS;
+  p->MaxNumDownBuffers  = SEGGER_RTT_MAX_NUM_DOWN_BUFFERS;
+  //
+  // Initialize up buffer 0
+  //
+  p->aUp[0].sName         = "Terminal";
+  p->aUp[0].pBuffer       = _acUpBuffer;
+  p->aUp[0].SizeOfBuffer  = BUFFER_SIZE_UP;
+  p->aUp[0].RdOff         = 0u;
+  p->aUp[0].WrOff         = 0u;
+  p->aUp[0].Flags         = SEGGER_RTT_MODE_DEFAULT;
+  //
+  // Initialize down buffer 0
+  //
+  p->aDown[0].sName         = "Terminal";
+  p->aDown[0].pBuffer       = _acDownBuffer;
+  p->aDown[0].SizeOfBuffer  = BUFFER_SIZE_DOWN;
+  p->aDown[0].RdOff         = 0u;
+  p->aDown[0].WrOff         = 0u;
+  p->aDown[0].Flags         = SEGGER_RTT_MODE_DEFAULT;
+  //
+  // Finish initialization of the control block.
+  // Copy Id string backwards to make sure that "SEGGER RTT" is not found in initializer memory (usually flash),
+  // as this would cause J-Link to "find" the control block at a wrong address.
+  //
+  RTT__DMB();                       // Force order of memory accesses for cores that may perform out-of-order memory accesses
+  for (i = 0; i < sizeof(_aInitStr) - 1; ++i) {
+    p->acID[i] = _aInitStr[sizeof(_aInitStr) - 2 - i];  // Skip terminating \0 at the end of the array
+  }
+  RTT__DMB();                       // Force order of memory accesses for cores that may perform out-of-order memory accesses
+}
+
+/*********************************************************************
+*
+*       _WriteBlocking()
+*
+*  Function description
+*    Stores a specified number of characters in SEGGER RTT ring buffer
+*    and updates the associated write pointer which is periodically
+*    read by the host.
+*    The caller is responsible for managing the write chunk sizes as
+*    _WriteBlocking() will block until all data has been posted successfully.
+*
+*  Parameters
+*    pRing        Ring buffer to post to.
+*    pBuffer      Pointer to character array. Does not need to point to a \0 terminated string.
+*    NumBytes     Number of bytes to be stored in the SEGGER RTT control block.
+*
+*  Return value
+*    >= 0 - Number of bytes written into buffer.
+*/
+static unsigned _WriteBlocking(SEGGER_RTT_BUFFER_UP* pRing, const char* pBuffer, unsigned NumBytes) {
+  unsigned NumBytesToWrite;
+  unsigned NumBytesWritten;
+  unsigned RdOff;
+  unsigned WrOff;
+  volatile char* pDst;
+  //
+  // Write data to buffer and handle wrap-around if necessary
+  //
+  NumBytesWritten = 0u;
+  WrOff = pRing->WrOff;
+  do {
+    RdOff = pRing->RdOff;                         // May be changed by host (debug probe) in the meantime
+    if (RdOff > WrOff) {
+      NumBytesToWrite = RdOff - WrOff - 1u;
+    } else {
+      NumBytesToWrite = pRing->SizeOfBuffer - (WrOff - RdOff + 1u);
+    }
+    NumBytesToWrite = MIN(NumBytesToWrite, (pRing->SizeOfBuffer - WrOff));      // Number of bytes that can be written until buffer wrap-around
+    NumBytesToWrite = MIN(NumBytesToWrite, NumBytes);
+    pDst = (pRing->pBuffer + WrOff) + SEGGER_RTT_UNCACHED_OFF;
+#if SEGGER_RTT_MEMCPY_USE_BYTELOOP
+    NumBytesWritten += NumBytesToWrite;
+    NumBytes        -= NumBytesToWrite;
+    WrOff           += NumBytesToWrite;
+    while (NumBytesToWrite--) {
+      *pDst++ = *pBuffer++;
+    };
+#else
+    SEGGER_RTT_MEMCPY((void*)pDst, pBuffer, NumBytesToWrite);
+    NumBytesWritten += NumBytesToWrite;
+    pBuffer         += NumBytesToWrite;
+    NumBytes        -= NumBytesToWrite;
+    WrOff           += NumBytesToWrite;
+#endif
+    if (WrOff == pRing->SizeOfBuffer) {
+      WrOff = 0u;
+    }
+    RTT__DMB();                     // Force data write to be complete before writing the <WrOff>, in case CPU is allowed to change the order of memory accesses
+    pRing->WrOff = WrOff;
+  } while (NumBytes);
+  return NumBytesWritten;
+}
+
+/*********************************************************************
+*
+*       _WriteNoCheck()
+*
+*  Function description
+*    Stores a specified number of characters in SEGGER RTT ring buffer
+*    and updates the associated write pointer which is periodically
+*    read by the host.
+*    It is callers responsibility to make sure data actually fits in buffer.
+*
+*  Parameters
+*    pRing        Ring buffer to post to.
+*    pBuffer      Pointer to character array. Does not need to point to a \0 terminated string.
+*    NumBytes     Number of bytes to be stored in the SEGGER RTT control block.
+*
+*  Notes
+*    (1) If there might not be enough space in the "Up"-buffer, call _WriteBlocking
+*/
+static void _WriteNoCheck(SEGGER_RTT_BUFFER_UP* pRing, const char* pData, unsigned NumBytes) {
+  unsigned NumBytesAtOnce;
+  unsigned WrOff;
+  unsigned Rem;
+  volatile char* pDst;
+
+  WrOff = pRing->WrOff;
+  Rem = pRing->SizeOfBuffer - WrOff;
+  if (Rem > NumBytes) {
+    //
+    // All data fits before wrap around
+    //
+    pDst = (pRing->pBuffer + WrOff) + SEGGER_RTT_UNCACHED_OFF;
+#if SEGGER_RTT_MEMCPY_USE_BYTELOOP
+    WrOff += NumBytes;
+    while (NumBytes--) {
+      *pDst++ = *pData++;
+    };
+    RTT__DMB();                     // Force data write to be complete before writing the <WrOff>, in case CPU is allowed to change the order of memory accesses
+    pRing->WrOff = WrOff;
+#else
+    SEGGER_RTT_MEMCPY((void*)pDst, pData, NumBytes);
+    RTT__DMB();                     // Force data write to be complete before writing the <WrOff>, in case CPU is allowed to change the order of memory accesses
+    pRing->WrOff = WrOff + NumBytes;
+#endif
+  } else {
+    //
+    // We reach the end of the buffer, so need to wrap around
+    //
+#if SEGGER_RTT_MEMCPY_USE_BYTELOOP
+    pDst = (pRing->pBuffer + WrOff) + SEGGER_RTT_UNCACHED_OFF;
+    NumBytesAtOnce = Rem;
+    while (NumBytesAtOnce--) {
+      *pDst++ = *pData++;
+    };
+    pDst = pRing->pBuffer + SEGGER_RTT_UNCACHED_OFF;
+    NumBytesAtOnce = NumBytes - Rem;
+    while (NumBytesAtOnce--) {
+      *pDst++ = *pData++;
+    };
+    RTT__DMB();                     // Force data write to be complete before writing the <WrOff>, in case CPU is allowed to change the order of memory accesses
+    pRing->WrOff = NumBytes - Rem;
+#else
+    NumBytesAtOnce = Rem;
+    pDst = (pRing->pBuffer + WrOff) + SEGGER_RTT_UNCACHED_OFF;
+    SEGGER_RTT_MEMCPY((void*)pDst, pData, NumBytesAtOnce);
+    NumBytesAtOnce = NumBytes - Rem;
+    pDst = pRing->pBuffer + SEGGER_RTT_UNCACHED_OFF;
+    SEGGER_RTT_MEMCPY((void*)pDst, pData + Rem, NumBytesAtOnce);
+    RTT__DMB();                     // Force data write to be complete before writing the <WrOff>, in case CPU is allowed to change the order of memory accesses
+    pRing->WrOff = NumBytesAtOnce;
+#endif
+  }
+}
+
+/*********************************************************************
+*
+*       _PostTerminalSwitch()
+*
+*  Function description
+*    Switch terminal to the given terminal ID.  It is the caller's
+*    responsibility to ensure the terminal ID is correct and there is
+*    enough space in the buffer for this to complete successfully.
+*
+*  Parameters
+*    pRing        Ring buffer to post to.
+*    TerminalId   Terminal ID to switch to.
+*/
+static void _PostTerminalSwitch(SEGGER_RTT_BUFFER_UP* pRing, unsigned char TerminalId) {
+  unsigned char ac[2];
+
+  ac[0] = 0xFFu;
+  ac[1] = _aTerminalId[TerminalId];  // Caller made already sure that TerminalId does not exceed our terminal limit
+  _WriteBlocking(pRing, (const char*)ac, 2u);
+}
+
+/*********************************************************************
+*
+*       _GetAvailWriteSpace()
+*
+*  Function description
+*    Returns the number of bytes that can be written to the ring
+*    buffer without blocking.
+*
+*  Parameters
+*    pRing        Ring buffer to check.
+*
+*  Return value
+*    Number of bytes that are free in the buffer.
+*/
+static unsigned _GetAvailWriteSpace(SEGGER_RTT_BUFFER_UP* pRing) {
+  unsigned RdOff;
+  unsigned WrOff;
+  unsigned r;
+  //
+  // Avoid warnings regarding volatile access order.  It's not a problem
+  // in this case, but dampen compiler enthusiasm.
+  //
+  RdOff = pRing->RdOff;
+  WrOff = pRing->WrOff;
+  if (RdOff <= WrOff) {
+    r = pRing->SizeOfBuffer - 1u - WrOff + RdOff;
+  } else {
+    r = RdOff - WrOff - 1u;
+  }
+  return r;
+}
+
+/*********************************************************************
+*
+*       Public code
+*
+**********************************************************************
+*/
+
+/*********************************************************************
+*
+*       SEGGER_RTT_ReadUpBufferNoLock()
+*
+*  Function description
+*    Reads characters from SEGGER real-time-terminal control block
+*    which have been previously stored by the application.
+*    Do not lock against interrupts and multiple access.
+*    Used to do the same operation that J-Link does, to transfer 
+*    RTT data via other channels, such as TCP/IP or UART.
+*
+*  Parameters
+*    BufferIndex  Index of Up-buffer to be used.
+*    pBuffer      Pointer to buffer provided by target application, to copy characters from RTT-up-buffer to.
+*    BufferSize   Size of the target application buffer.
+*
+*  Return value
+*    Number of bytes that have been read.
+*
+*  Additional information
+*    This function must not be called when J-Link might also do RTT.
+*/
+unsigned SEGGER_RTT_ReadUpBufferNoLock(unsigned BufferIndex, void* pData, unsigned BufferSize) {
+  unsigned                NumBytesRem;
+  unsigned                NumBytesRead;
+  unsigned                RdOff;
+  unsigned                WrOff;
+  unsigned char*          pBuffer;
+  SEGGER_RTT_BUFFER_UP*   pRing;
+  volatile char*          pSrc;
+
+  INIT();
+  pRing = (SEGGER_RTT_BUFFER_UP*)((char*)&_SEGGER_RTT.aUp[BufferIndex] + SEGGER_RTT_UNCACHED_OFF);  // Access uncached to make sure we see changes made by the J-Link side and all of our changes go into HW directly
+  pBuffer = (unsigned char*)pData;
+  RdOff = pRing->RdOff;
+  WrOff = pRing->WrOff;
+  NumBytesRead = 0u;
+  //
+  // Read from current read position to wrap-around of buffer, first
+  //
+  if (RdOff > WrOff) {
+    NumBytesRem = pRing->SizeOfBuffer - RdOff;
+    NumBytesRem = MIN(NumBytesRem, BufferSize);
+    pSrc = (pRing->pBuffer + RdOff) + SEGGER_RTT_UNCACHED_OFF;
+#if SEGGER_RTT_MEMCPY_USE_BYTELOOP
+    NumBytesRead += NumBytesRem;
+    BufferSize   -= NumBytesRem;
+    RdOff        += NumBytesRem;
+    while (NumBytesRem--) {
+      *pBuffer++ = *pSrc++;
+    };
+#else
+    SEGGER_RTT_MEMCPY(pBuffer, (void*)pSrc, NumBytesRem);
+    NumBytesRead += NumBytesRem;
+    pBuffer      += NumBytesRem;
+    BufferSize   -= NumBytesRem;
+    RdOff        += NumBytesRem;
+#endif
+    //
+    // Handle wrap-around of buffer
+    //
+    if (RdOff == pRing->SizeOfBuffer) {
+      RdOff = 0u;
+    }
+  }
+  //
+  // Read remaining items of buffer
+  //
+  NumBytesRem = WrOff - RdOff;
+  NumBytesRem = MIN(NumBytesRem, BufferSize);
+  if (NumBytesRem > 0u) {
+    pSrc = (pRing->pBuffer + RdOff) + SEGGER_RTT_UNCACHED_OFF;
+#if SEGGER_RTT_MEMCPY_USE_BYTELOOP
+    NumBytesRead += NumBytesRem;
+    BufferSize   -= NumBytesRem;
+    RdOff        += NumBytesRem;
+    while (NumBytesRem--) {
+      *pBuffer++ = *pSrc++;
+    };
+#else
+    SEGGER_RTT_MEMCPY(pBuffer, (void*)pSrc, NumBytesRem);
+    NumBytesRead += NumBytesRem;
+    pBuffer      += NumBytesRem;
+    BufferSize   -= NumBytesRem;
+    RdOff        += NumBytesRem;
+#endif
+  }
+  //
+  // Update read offset of buffer
+  //
+  if (NumBytesRead) {
+    pRing->RdOff = RdOff;
+  }
+  //
+  return NumBytesRead;
+}
+
+/*********************************************************************
+*
+*       SEGGER_RTT_ReadNoLock()
+*
+*  Function description
+*    Reads characters from SEGGER real-time-terminal control block
+*    which have been previously stored by the host.
+*    Do not lock against interrupts and multiple access.
+*
+*  Parameters
+*    BufferIndex  Index of Down-buffer to be used (e.g. 0 for "Terminal").
+*    pBuffer      Pointer to buffer provided by target application, to copy characters from RTT-down-buffer to.
+*    BufferSize   Size of the target application buffer.
+*
+*  Return value
+*    Number of bytes that have been read.
+*/
+unsigned SEGGER_RTT_ReadNoLock(unsigned BufferIndex, void* pData, unsigned BufferSize) {
+  unsigned                NumBytesRem;
+  unsigned                NumBytesRead;
+  unsigned                RdOff;
+  unsigned                WrOff;
+  unsigned char*          pBuffer;
+  SEGGER_RTT_BUFFER_DOWN* pRing;
+  volatile char*          pSrc;
+  //
+  INIT();
+  pRing = (SEGGER_RTT_BUFFER_DOWN*)((char*)&_SEGGER_RTT.aDown[BufferIndex] + SEGGER_RTT_UNCACHED_OFF);  // Access uncached to make sure we see changes made by the J-Link side and all of our changes go into HW directly
+  pBuffer = (unsigned char*)pData;
+  RdOff = pRing->RdOff;
+  WrOff = pRing->WrOff;
+  NumBytesRead = 0u;
+  //
+  // Read from current read position to wrap-around of buffer, first
+  //
+  if (RdOff > WrOff) {
+    NumBytesRem = pRing->SizeOfBuffer - RdOff;
+    NumBytesRem = MIN(NumBytesRem, BufferSize);
+    pSrc = (pRing->pBuffer + RdOff) + SEGGER_RTT_UNCACHED_OFF;
+#if SEGGER_RTT_MEMCPY_USE_BYTELOOP
+    NumBytesRead += NumBytesRem;
+    BufferSize   -= NumBytesRem;
+    RdOff        += NumBytesRem;
+    while (NumBytesRem--) {
+      *pBuffer++ = *pSrc++;
+    };
+#else
+    SEGGER_RTT_MEMCPY(pBuffer, (void*)pSrc, NumBytesRem);
+    NumBytesRead += NumBytesRem;
+    pBuffer      += NumBytesRem;
+    BufferSize   -= NumBytesRem;
+    RdOff        += NumBytesRem;
+#endif
+    //
+    // Handle wrap-around of buffer
+    //
+    if (RdOff == pRing->SizeOfBuffer) {
+      RdOff = 0u;
+    }
+  }
+  //
+  // Read remaining items of buffer
+  //
+  NumBytesRem = WrOff - RdOff;
+  NumBytesRem = MIN(NumBytesRem, BufferSize);
+  if (NumBytesRem > 0u) {
+    pSrc = (pRing->pBuffer + RdOff) + SEGGER_RTT_UNCACHED_OFF;
+#if SEGGER_RTT_MEMCPY_USE_BYTELOOP
+    NumBytesRead += NumBytesRem;
+    BufferSize   -= NumBytesRem;
+    RdOff        += NumBytesRem;
+    while (NumBytesRem--) {
+      *pBuffer++ = *pSrc++;
+    };
+#else
+    SEGGER_RTT_MEMCPY(pBuffer, (void*)pSrc, NumBytesRem);
+    NumBytesRead += NumBytesRem;
+    pBuffer      += NumBytesRem;
+    BufferSize   -= NumBytesRem;
+    RdOff        += NumBytesRem;
+#endif
+  }
+  if (NumBytesRead) {
+    pRing->RdOff = RdOff;
+  }
+  //
+  return NumBytesRead;
+}
+
+/*********************************************************************
+*
+*       SEGGER_RTT_ReadUpBuffer
+*
+*  Function description
+*    Reads characters from SEGGER real-time-terminal control block
+*    which have been previously stored by the application.
+*    Used to do the same operation that J-Link does, to transfer 
+*    RTT data via other channels, such as TCP/IP or UART.
+*
+*  Parameters
+*    BufferIndex  Index of Up-buffer to be used.
+*    pBuffer      Pointer to buffer provided by target application, to copy characters from RTT-up-buffer to.
+*    BufferSize   Size of the target application buffer.
+*
+*  Return value
+*    Number of bytes that have been read.
+*
+*  Additional information
+*    This function must not be called when J-Link might also do RTT.
+*    This function locks against all other RTT operations. I.e. during
+*    the read operation, writing is also locked.
+*    If only one consumer reads from the up buffer, 
+*    call sEGGER_RTT_ReadUpBufferNoLock() instead.
+*/
+unsigned SEGGER_RTT_ReadUpBuffer(unsigned BufferIndex, void* pBuffer, unsigned BufferSize) {
+  unsigned NumBytesRead;
+
+  SEGGER_RTT_LOCK();
+  //
+  // Call the non-locking read function
+  //
+  NumBytesRead = SEGGER_RTT_ReadUpBufferNoLock(BufferIndex, pBuffer, BufferSize);
+  //
+  // Finish up.
+  //
+  SEGGER_RTT_UNLOCK();
+  //
+  return NumBytesRead;
+}
+
+/*********************************************************************
+*
+*       SEGGER_RTT_Read
+*
+*  Function description
+*    Reads characters from SEGGER real-time-terminal control block
+*    which have been previously stored by the host.
+*
+*  Parameters
+*    BufferIndex  Index of Down-buffer to be used (e.g. 0 for "Terminal").
+*    pBuffer      Pointer to buffer provided by target application, to copy characters from RTT-down-buffer to.
+*    BufferSize   Size of the target application buffer.
+*
+*  Return value
+*    Number of bytes that have been read.
+*/
+unsigned SEGGER_RTT_Read(unsigned BufferIndex, void* pBuffer, unsigned BufferSize) {
+  unsigned NumBytesRead;
+
+  SEGGER_RTT_LOCK();
+  //
+  // Call the non-locking read function
+  //
+  NumBytesRead = SEGGER_RTT_ReadNoLock(BufferIndex, pBuffer, BufferSize);
+  //
+  // Finish up.
+  //
+  SEGGER_RTT_UNLOCK();
+  //
+  return NumBytesRead;
+}
+
+/*********************************************************************
+*
+*       SEGGER_RTT_WriteWithOverwriteNoLock
+*
+*  Function description
+*    Stores a specified number of characters in SEGGER RTT
+*    control block.
+*    SEGGER_RTT_WriteWithOverwriteNoLock does not lock the application 
+*    and overwrites data if the data does not fit into the buffer.
+*
+*  Parameters
+*    BufferIndex  Index of "Up"-buffer to be used (e.g. 0 for "Terminal").
+*    pBuffer      Pointer to character array. Does not need to point to a \0 terminated string.
+*    NumBytes     Number of bytes to be stored in the SEGGER RTT control block.
+*
+*  Notes
+*    (1) If there is not enough space in the "Up"-buffer, data is overwritten.
+*    (2) For performance reasons this function does not call Init()
+*        and may only be called after RTT has been initialized.
+*        Either by calling SEGGER_RTT_Init() or calling another RTT API function first.
+*    (3) Do not use SEGGER_RTT_WriteWithOverwriteNoLock if a J-Link 
+*        connection reads RTT data.
+*/
+void SEGGER_RTT_WriteWithOverwriteNoLock(unsigned BufferIndex, const void* pBuffer, unsigned NumBytes) {
+  const char*           pData;
+  SEGGER_RTT_BUFFER_UP* pRing;
+  unsigned              Avail;
+  volatile char*        pDst;
+  //
+  // Get "to-host" ring buffer and copy some elements into local variables.
+  //
+  pData = (const char *)pBuffer;
+  pRing = (SEGGER_RTT_BUFFER_UP*)((char*)&_SEGGER_RTT.aUp[BufferIndex] + SEGGER_RTT_UNCACHED_OFF);  // Access uncached to make sure we see changes made by the J-Link side and all of our changes go into HW directly
+  //
+  // Check if we will overwrite data and need to adjust the RdOff.
+  //
+  if (pRing->WrOff == pRing->RdOff) {
+    Avail = pRing->SizeOfBuffer - 1u;
+  } else if ( pRing->WrOff < pRing->RdOff) {
+    Avail = pRing->RdOff - pRing->WrOff - 1u;
+  } else {
+    Avail = pRing->RdOff - pRing->WrOff - 1u + pRing->SizeOfBuffer;
+  }
+  if (NumBytes > Avail) {
+    pRing->RdOff += (NumBytes - Avail);
+    while (pRing->RdOff >= pRing->SizeOfBuffer) {
+      pRing->RdOff -= pRing->SizeOfBuffer;
+    }
+  }
+  //
+  // Write all data, no need to check the RdOff, but possibly handle multiple wrap-arounds
+  //
+  Avail = pRing->SizeOfBuffer - pRing->WrOff;
+  do {
+    if (Avail > NumBytes) {
+      //
+      // Last round
+      //
+      pDst = (pRing->pBuffer + pRing->WrOff) + SEGGER_RTT_UNCACHED_OFF;
+#if SEGGER_RTT_MEMCPY_USE_BYTELOOP
+      Avail = NumBytes;
+      while (NumBytes--) {
+        *pDst++ = *pData++;
+      };
+      RTT__DMB();                     // Force data write to be complete before writing the <WrOff>, in case CPU is allowed to change the order of memory accesses
+      pRing->WrOff += Avail;
+#else
+      SEGGER_RTT_MEMCPY((void*)pDst, pData, NumBytes);
+      RTT__DMB();                     // Force data write to be complete before writing the <WrOff>, in case CPU is allowed to change the order of memory accesses
+      pRing->WrOff += NumBytes;
+#endif
+      break;
+    } else {
+      //
+      //  Wrap-around necessary, write until wrap-around and reset WrOff
+      //
+      pDst = (pRing->pBuffer + pRing->WrOff) + SEGGER_RTT_UNCACHED_OFF;
+#if SEGGER_RTT_MEMCPY_USE_BYTELOOP
+      NumBytes -= Avail;
+      while (Avail--) {
+        *pDst++ = *pData++;
+      };
+      RTT__DMB();                     // Force data write to be complete before writing the <WrOff>, in case CPU is allowed to change the order of memory accesses
+      pRing->WrOff = 0;
+#else
+      SEGGER_RTT_MEMCPY((void*)pDst, pData, Avail);
+      pData += Avail;
+      RTT__DMB();                     // Force data write to be complete before writing the <WrOff>, in case CPU is allowed to change the order of memory accesses
+      pRing->WrOff = 0;
+      NumBytes -= Avail;
+#endif
+      Avail = (pRing->SizeOfBuffer - 1);
+    }
+  } while (NumBytes);
+}
+
+/*********************************************************************
+*
+*       SEGGER_RTT_WriteSkipNoLock
+*
+*  Function description
+*    Stores a specified number of characters in SEGGER RTT
+*    control block which is then read by the host.
+*    SEGGER_RTT_WriteSkipNoLock does not lock the application and
+*    skips all data, if the data does not fit into the buffer.
+*
+*  Parameters
+*    BufferIndex  Index of "Up"-buffer to be used (e.g. 0 for "Terminal").
+*    pBuffer      Pointer to character array. Does not need to point to a \0 terminated string.
+*    NumBytes     Number of bytes to be stored in the SEGGER RTT control block.
+*                 MUST be > 0!!!
+*                 This is done for performance reasons, so no initial check has do be done.
+*
+*  Return value
+*    1: Data has been copied
+*    0: No space, data has not been copied
+*
+*  Notes
+*    (1) If there is not enough space in the "Up"-buffer, all data is dropped.
+*    (2) For performance reasons this function does not call Init()
+*        and may only be called after RTT has been initialized.
+*        Either by calling SEGGER_RTT_Init() or calling another RTT API function first.
+*/
+#if (RTT_USE_ASM == 0)
+unsigned SEGGER_RTT_WriteSkipNoLock(unsigned BufferIndex, const void* pBuffer, unsigned NumBytes) {
+  const char*           pData;
+  SEGGER_RTT_BUFFER_UP* pRing;
+  unsigned              Avail;
+  unsigned              RdOff;
+  unsigned              WrOff;
+  unsigned              Rem;
+  volatile char*        pDst;
+  //
+  // Cases:
+  //   1) RdOff <= WrOff => Space until wrap-around is sufficient
+  //   2) RdOff <= WrOff => Space after wrap-around needed (copy in 2 chunks)
+  //   3) RdOff <  WrOff => No space in buf
+  //   4) RdOff >  WrOff => Space is sufficient
+  //   5) RdOff >  WrOff => No space in buf
+  //
+  // 1) is the most common case for large buffers and assuming that J-Link reads the data fast enough
+  //
+  pData = (const char *)pBuffer;
+  pRing = (SEGGER_RTT_BUFFER_UP*)((char*)&_SEGGER_RTT.aUp[BufferIndex] + SEGGER_RTT_UNCACHED_OFF);  // Access uncached to make sure we see changes made by the J-Link side and all of our changes go into HW directly
+  RdOff = pRing->RdOff;
+  WrOff = pRing->WrOff;
+  if (RdOff <= WrOff) {                                 // Case 1), 2) or 3)
+    Avail = pRing->SizeOfBuffer - WrOff - 1u;           // Space until wrap-around (assume 1 byte not usable for case that RdOff == 0)
+    if (Avail >= NumBytes) {                            // Case 1)?
+CopyStraight:
+      pDst = (pRing->pBuffer + WrOff) + SEGGER_RTT_UNCACHED_OFF;
+      memcpy((void*)pDst, pData, NumBytes);
+      RTT__DMB();                     // Force data write to be complete before writing the <WrOff>, in case CPU is allowed to change the order of memory accesses
+      pRing->WrOff = WrOff + NumBytes;
+      return 1;
+    }
+    Avail += RdOff;                                     // Space incl. wrap-around
+    if (Avail >= NumBytes) {                            // Case 2? => If not, we have case 3) (does not fit)
+      Rem = pRing->SizeOfBuffer - WrOff;                // Space until end of buffer
+      pDst = (pRing->pBuffer + WrOff) + SEGGER_RTT_UNCACHED_OFF;
+      memcpy((void*)pDst, pData, Rem);                  // Copy 1st chunk
+      NumBytes -= Rem;
+      //
+      // Special case: First check that assumed RdOff == 0 calculated that last element before wrap-around could not be used
+      // But 2nd check (considering space until wrap-around and until RdOff) revealed that RdOff is not 0, so we can use the last element
+      // In this case, we may use a copy straight until buffer end anyway without needing to copy 2 chunks
+      // Therefore, check if 2nd memcpy is necessary at all
+      //
+      if (NumBytes) {
+        pDst = pRing->pBuffer + SEGGER_RTT_UNCACHED_OFF;
+        memcpy((void*)pDst, pData + Rem, NumBytes);
+      }
+      RTT__DMB();                     // Force data write to be complete before writing the <WrOff>, in case CPU is allowed to change the order of memory accesses
+      pRing->WrOff = NumBytes;
+      return 1;
+    }
+  } else {                                             // Potential case 4)
+    Avail = RdOff - WrOff - 1u;
+    if (Avail >= NumBytes) {                           // Case 4)? => If not, we have case 5) (does not fit)
+      goto CopyStraight;
+    }
+  }
+  return 0;     // No space in buffer
+}
+#endif
+
+/*********************************************************************
+*
+*       SEGGER_RTT_WriteDownBufferNoLock
+*
+*  Function description
+*    Stores a specified number of characters in SEGGER RTT
+*    control block inside a <Down> buffer.
+*    SEGGER_RTT_WriteDownBufferNoLock does not lock the application.
+*    Used to do the same operation that J-Link does, to transfer 
+*    RTT data from other channels, such as TCP/IP or UART.
+*
+*  Parameters
+*    BufferIndex  Index of "Down"-buffer to be used.
+*    pBuffer      Pointer to character array. Does not need to point to a \0 terminated string.
+*    NumBytes     Number of bytes to be stored in the SEGGER RTT control block.
+*
+*  Return value
+*    Number of bytes which have been stored in the "Down"-buffer.
+*
+*  Notes
+*    (1) Data is stored according to buffer flags.
+*    (2) For performance reasons this function does not call Init()
+*        and may only be called after RTT has been initialized.
+*        Either by calling SEGGER_RTT_Init() or calling another RTT API function first.
+*
+*  Additional information
+*    This function must not be called when J-Link might also do RTT.
+*/
+unsigned SEGGER_RTT_WriteDownBufferNoLock(unsigned BufferIndex, const void* pBuffer, unsigned NumBytes) {
+  unsigned                Status;
+  unsigned                Avail;
+  const char*             pData;
+  SEGGER_RTT_BUFFER_UP*   pRing;
+  //
+  // Get "to-target" ring buffer.
+  // It is save to cast that to a "to-host" buffer. Up and Down buffer differ in volatility of offsets that might be modified by J-Link.
+  //
+  pData = (const char *)pBuffer;
+  pRing = (SEGGER_RTT_BUFFER_UP*)((char*)&_SEGGER_RTT.aDown[BufferIndex] + SEGGER_RTT_UNCACHED_OFF);  // Access uncached to make sure we see changes made by the J-Link side and all of our changes go into HW directly
+  //
+  // How we output depends upon the mode...
+  //
+  switch (pRing->Flags) {
+  case SEGGER_RTT_MODE_NO_BLOCK_SKIP:
+    //
+    // If we are in skip mode and there is no space for the whole
+    // of this output, don't bother.
+    //
+    Avail = _GetAvailWriteSpace(pRing);
+    if (Avail < NumBytes) {
+      Status = 0u;
+    } else {
+      Status = NumBytes;
+      _WriteNoCheck(pRing, pData, NumBytes);
+    }
+    break;
+  case SEGGER_RTT_MODE_NO_BLOCK_TRIM:
+    //
+    // If we are in trim mode, trim to what we can output without blocking.
+    //
+    Avail = _GetAvailWriteSpace(pRing);
+    Status = Avail < NumBytes ? Avail : NumBytes;
+    _WriteNoCheck(pRing, pData, Status);
+    break;
+  case SEGGER_RTT_MODE_BLOCK_IF_FIFO_FULL:
+    //
+    // If we are in blocking mode, output everything.
+    //
+    Status = _WriteBlocking(pRing, pData, NumBytes);
+    break;
+  default:
+    Status = 0u;
+    break;
+  }
+  //
+  // Finish up.
+  //
+  return Status;
+}
+
+/*********************************************************************
+*
+*       SEGGER_RTT_WriteNoLock
+*
+*  Function description
+*    Stores a specified number of characters in SEGGER RTT
+*    control block which is then read by the host.
+*    SEGGER_RTT_WriteNoLock does not lock the application.
+*
+*  Parameters
+*    BufferIndex  Index of "Up"-buffer to be used (e.g. 0 for "Terminal").
+*    pBuffer      Pointer to character array. Does not need to point to a \0 terminated string.
+*    NumBytes     Number of bytes to be stored in the SEGGER RTT control block.
+*
+*  Return value
+*    Number of bytes which have been stored in the "Up"-buffer.
+*
+*  Notes
+*    (1) Data is stored according to buffer flags.
+*    (2) For performance reasons this function does not call Init()
+*        and may only be called after RTT has been initialized.
+*        Either by calling SEGGER_RTT_Init() or calling another RTT API function first.
+*/
+unsigned SEGGER_RTT_WriteNoLock(unsigned BufferIndex, const void* pBuffer, unsigned NumBytes) {
+  unsigned              Status;
+  unsigned              Avail;
+  const char*           pData;
+  SEGGER_RTT_BUFFER_UP* pRing;
+  //
+  // Get "to-host" ring buffer.
+  //
+  pData = (const char *)pBuffer;
+  pRing = (SEGGER_RTT_BUFFER_UP*)((char*)&_SEGGER_RTT.aUp[BufferIndex] + SEGGER_RTT_UNCACHED_OFF);  // Access uncached to make sure we see changes made by the J-Link side and all of our changes go into HW directly
+  //
+  // How we output depends upon the mode...
+  //
+  switch (pRing->Flags) {
+  case SEGGER_RTT_MODE_NO_BLOCK_SKIP:
+    //
+    // If we are in skip mode and there is no space for the whole
+    // of this output, don't bother.
+    //
+    Avail = _GetAvailWriteSpace(pRing);
+    if (Avail < NumBytes) {
+      Status = 0u;
+    } else {
+      Status = NumBytes;
+      _WriteNoCheck(pRing, pData, NumBytes);
+    }
+    break;
+  case SEGGER_RTT_MODE_NO_BLOCK_TRIM:
+    //
+    // If we are in trim mode, trim to what we can output without blocking.
+    //
+    Avail = _GetAvailWriteSpace(pRing);
+    Status = Avail < NumBytes ? Avail : NumBytes;
+    _WriteNoCheck(pRing, pData, Status);
+    break;
+  case SEGGER_RTT_MODE_BLOCK_IF_FIFO_FULL:
+    //
+    // If we are in blocking mode, output everything.
+    //
+    Status = _WriteBlocking(pRing, pData, NumBytes);
+    break;
+  default:
+    Status = 0u;
+    break;
+  }
+  //
+  // Finish up.
+  //
+  return Status;
+}
+
+/*********************************************************************
+*
+*       SEGGER_RTT_WriteDownBuffer
+*
+*  Function description
+*    Stores a specified number of characters in SEGGER RTT control block in a <Down> buffer.
+*
+*  Parameters
+*    BufferIndex  Index of "Up"-buffer to be used (e.g. 0 for "Terminal").
+*    pBuffer      Pointer to character array. Does not need to point to a \0 terminated string.
+*    NumBytes     Number of bytes to be stored in the SEGGER RTT control block.
+*
+*  Return value
+*    Number of bytes which have been stored in the "Down"-buffer.
+*
+*  Notes
+*    (1) Data is stored according to buffer flags.
+*
+*  Additional information
+*    This function must not be called when J-Link might also do RTT.
+*    This function locks against all other RTT operations. I.e. during
+*    the write operation, writing from the application is also locked.
+*    If only one consumer writes to the down buffer, 
+*    call SEGGER_RTT_WriteDownBufferNoLock() instead.
+*/
+unsigned SEGGER_RTT_WriteDownBuffer(unsigned BufferIndex, const void* pBuffer, unsigned NumBytes) {
+  unsigned Status;
+
+  INIT();
+  SEGGER_RTT_LOCK();
+  Status = SEGGER_RTT_WriteDownBufferNoLock(BufferIndex, pBuffer, NumBytes);  // Call the non-locking write function
+  SEGGER_RTT_UNLOCK();
+  return Status;
+}
+
+/*********************************************************************
+*
+*       SEGGER_RTT_Write
+*
+*  Function description
+*    Stores a specified number of characters in SEGGER RTT
+*    control block which is then read by the host.
+*
+*  Parameters
+*    BufferIndex  Index of "Up"-buffer to be used (e.g. 0 for "Terminal").
+*    pBuffer      Pointer to character array. Does not need to point to a \0 terminated string.
+*    NumBytes     Number of bytes to be stored in the SEGGER RTT control block.
+*
+*  Return value
+*    Number of bytes which have been stored in the "Up"-buffer.
+*
+*  Notes
+*    (1) Data is stored according to buffer flags.
+*/
+unsigned SEGGER_RTT_Write(unsigned BufferIndex, const void* pBuffer, unsigned NumBytes) {
+  unsigned Status;
+
+  INIT();
+  SEGGER_RTT_LOCK();
+  Status = SEGGER_RTT_WriteNoLock(BufferIndex, pBuffer, NumBytes);  // Call the non-locking write function
+  SEGGER_RTT_UNLOCK();
+  return Status;
+}
+
+/*********************************************************************
+*
+*       SEGGER_RTT_WriteString
+*
+*  Function description
+*    Stores string in SEGGER RTT control block.
+*    This data is read by the host.
+*
+*  Parameters
+*    BufferIndex  Index of "Up"-buffer to be used (e.g. 0 for "Terminal").
+*    s            Pointer to string.
+*
+*  Return value
+*    Number of bytes which have been stored in the "Up"-buffer.
+*
+*  Notes
+*    (1) Data is stored according to buffer flags.
+*    (2) String passed to this function has to be \0 terminated
+*    (3) \0 termination character is *not* stored in RTT buffer
+*/
+unsigned SEGGER_RTT_WriteString(unsigned BufferIndex, const char* s) {
+  unsigned Len;
+
+  Len = STRLEN(s);
+  return SEGGER_RTT_Write(BufferIndex, s, Len);
+}
+
+/*********************************************************************
+*
+*       SEGGER_RTT_PutCharSkipNoLock
+*
+*  Function description
+*    Stores a single character/byte in SEGGER RTT buffer.
+*    SEGGER_RTT_PutCharSkipNoLock does not lock the application and
+*    skips the byte, if it does not fit into the buffer.
+*
+*  Parameters
+*    BufferIndex  Index of "Up"-buffer to be used (e.g. 0 for "Terminal").
+*    c            Byte to be stored.
+*
+*  Return value
+*    Number of bytes which have been stored in the "Up"-buffer.
+*
+*  Notes
+*    (1) If there is not enough space in the "Up"-buffer, the character is dropped.
+*    (2) For performance reasons this function does not call Init()
+*        and may only be called after RTT has been initialized.
+*        Either by calling SEGGER_RTT_Init() or calling another RTT API function first.
+*/
+
+unsigned SEGGER_RTT_PutCharSkipNoLock(unsigned BufferIndex, char c) {
+  SEGGER_RTT_BUFFER_UP* pRing;
+  unsigned              WrOff;
+  unsigned              Status;
+  volatile char*        pDst;
+  //
+  // Get "to-host" ring buffer.
+  //
+  pRing = (SEGGER_RTT_BUFFER_UP*)((char*)&_SEGGER_RTT.aUp[BufferIndex] + SEGGER_RTT_UNCACHED_OFF);  // Access uncached to make sure we see changes made by the J-Link side and all of our changes go into HW directly
+  //
+  // Get write position and handle wrap-around if necessary
+  //
+  WrOff = pRing->WrOff + 1;
+  if (WrOff == pRing->SizeOfBuffer) {
+    WrOff = 0;
+  }
+  //
+  // Output byte if free space is available
+  //
+  if (WrOff != pRing->RdOff) {
+    pDst = (pRing->pBuffer + pRing->WrOff) + SEGGER_RTT_UNCACHED_OFF;
+    *pDst = c;
+    RTT__DMB();                     // Force data write to be complete before writing the <WrOff>, in case CPU is allowed to change the order of memory accesses
+    pRing->WrOff = WrOff;
+    Status = 1;
+  } else {
+    Status = 0;
+  }
+  //
+  return Status;
+}
+
+/*********************************************************************
+*
+*       SEGGER_RTT_PutCharSkip
+*
+*  Function description
+*    Stores a single character/byte in SEGGER RTT buffer.
+*
+*  Parameters
+*    BufferIndex  Index of "Up"-buffer to be used (e.g. 0 for "Terminal").
+*    c            Byte to be stored.
+*
+*  Return value
+*    Number of bytes which have been stored in the "Up"-buffer.
+*
+*  Notes
+*    (1) If there is not enough space in the "Up"-buffer, the character is dropped.
+*/
+
+unsigned SEGGER_RTT_PutCharSkip(unsigned BufferIndex, char c) {
+  SEGGER_RTT_BUFFER_UP* pRing;
+  unsigned              WrOff;
+  unsigned              Status;
+  volatile char*        pDst;
+  //
+  // Prepare
+  //
+  INIT();
+  SEGGER_RTT_LOCK();
+  //
+  // Get "to-host" ring buffer.
+  //
+  pRing = (SEGGER_RTT_BUFFER_UP*)((char*)&_SEGGER_RTT.aUp[BufferIndex] + SEGGER_RTT_UNCACHED_OFF);  // Access uncached to make sure we see changes made by the J-Link side and all of our changes go into HW directly
+  //
+  // Get write position and handle wrap-around if necessary
+  //
+  WrOff = pRing->WrOff + 1;
+  if (WrOff == pRing->SizeOfBuffer) {
+    WrOff = 0;
+  }
+  //
+  // Output byte if free space is available
+  //
+  if (WrOff != pRing->RdOff) {
+    pDst  = (pRing->pBuffer + pRing->WrOff) + SEGGER_RTT_UNCACHED_OFF;
+    *pDst = c;
+    RTT__DMB();                     // Force data write to be complete before writing the <WrOff>, in case CPU is allowed to change the order of memory accesses
+    pRing->WrOff = WrOff;
+    Status = 1;
+  } else {
+    Status = 0;
+  }
+  //
+  // Finish up.
+  //
+  SEGGER_RTT_UNLOCK();
+  //
+  return Status;
+}
+
+ /*********************************************************************
+*
+*       SEGGER_RTT_PutChar
+*
+*  Function description
+*    Stores a single character/byte in SEGGER RTT buffer.
+*
+*  Parameters
+*    BufferIndex  Index of "Up"-buffer to be used (e.g. 0 for "Terminal").
+*    c            Byte to be stored.
+*
+*  Return value
+*    Number of bytes which have been stored in the "Up"-buffer.
+*
+*  Notes
+*    (1) Data is stored according to buffer flags.
+*/
+
+unsigned SEGGER_RTT_PutChar(unsigned BufferIndex, char c) {
+  SEGGER_RTT_BUFFER_UP* pRing;
+  unsigned              WrOff;
+  unsigned              Status;
+  volatile char*        pDst;
+  //
+  // Prepare
+  //
+  INIT();
+  SEGGER_RTT_LOCK();
+  //
+  // Get "to-host" ring buffer.
+  //
+  pRing = (SEGGER_RTT_BUFFER_UP*)((char*)&_SEGGER_RTT.aUp[BufferIndex] + SEGGER_RTT_UNCACHED_OFF);  // Access uncached to make sure we see changes made by the J-Link side and all of our changes go into HW directly
+  //
+  // Get write position and handle wrap-around if necessary
+  //
+  WrOff = pRing->WrOff + 1;
+  if (WrOff == pRing->SizeOfBuffer) {
+    WrOff = 0;
+  }
+  //
+  // Wait for free space if mode is set to blocking
+  //
+  if (pRing->Flags == SEGGER_RTT_MODE_BLOCK_IF_FIFO_FULL) {
+    while (WrOff == pRing->RdOff) {
+      ;
+    }
+  }
+  //
+  // Output byte if free space is available
+  //
+  if (WrOff != pRing->RdOff) {
+    pDst  = (pRing->pBuffer + pRing->WrOff) + SEGGER_RTT_UNCACHED_OFF;
+    *pDst = c;
+    RTT__DMB();                     // Force data write to be complete before writing the <WrOff>, in case CPU is allowed to change the order of memory accesses
+    pRing->WrOff = WrOff;
+    Status = 1;
+  } else {
+    Status = 0;
+  }
+  //
+  // Finish up.
+  //
+  SEGGER_RTT_UNLOCK();
+  return Status;
+}
+
+/*********************************************************************
+*
+*       SEGGER_RTT_GetKey
+*
+*  Function description
+*    Reads one character from the SEGGER RTT buffer.
+*    Host has previously stored data there.
+*
+*  Return value
+*    <  0 -   No character available (buffer empty).
+*    >= 0 -   Character which has been read. (Possible values: 0 - 255)
+*
+*  Notes
+*    (1) This function is only specified for accesses to RTT buffer 0.
+*/
+int SEGGER_RTT_GetKey(void) {
+  char c;
+  int r;
+
+  r = (int)SEGGER_RTT_Read(0u, &c, 1u);
+  if (r == 1) {
+    r = (int)(unsigned char)c;
+  } else {
+    r = -1;
+  }
+  return r;
+}
+
+/*********************************************************************
+*
+*       SEGGER_RTT_WaitKey
+*
+*  Function description
+*    Waits until at least one character is avaible in the SEGGER RTT buffer.
+*    Once a character is available, it is read and this function returns.
+*
+*  Return value
+*    >=0 -   Character which has been read.
+*
+*  Notes
+*    (1) This function is only specified for accesses to RTT buffer 0
+*    (2) This function is blocking if no character is present in RTT buffer
+*/
+int SEGGER_RTT_WaitKey(void) {
+  int r;
+
+  do {
+    r = SEGGER_RTT_GetKey();
+  } while (r < 0);
+  return r;
+}
+
+/*********************************************************************
+*
+*       SEGGER_RTT_HasKey
+*
+*  Function description
+*    Checks if at least one character for reading is available in the SEGGER RTT buffer.
+*
+*  Return value
+*    == 0 -     No characters are available to read.
+*    == 1 -     At least one character is available.
+*
+*  Notes
+*    (1) This function is only specified for accesses to RTT buffer 0
+*/
+int SEGGER_RTT_HasKey(void) {
+  SEGGER_RTT_BUFFER_DOWN* pRing;
+  unsigned RdOff;
+  int r;
+
+  INIT();
+  pRing = (SEGGER_RTT_BUFFER_DOWN*)((char*)&_SEGGER_RTT.aDown[0] + SEGGER_RTT_UNCACHED_OFF);  // Access uncached to make sure we see changes made by the J-Link side and all of our changes go into HW directly
+  RdOff = pRing->RdOff;
+  if (RdOff != pRing->WrOff) {
+    r = 1;
+  } else {
+    r = 0;
+  }
+  return r;
+}
+
+/*********************************************************************
+*
+*       SEGGER_RTT_HasData
+*
+*  Function description
+*    Check if there is data from the host in the given buffer.
+*
+*  Return value:
+*  ==0:  No data
+*  !=0:  Data in buffer
+*
+*/
+unsigned SEGGER_RTT_HasData(unsigned BufferIndex) {
+  SEGGER_RTT_BUFFER_DOWN* pRing;
+  unsigned                v;
+
+  pRing = (SEGGER_RTT_BUFFER_DOWN*)((char*)&_SEGGER_RTT.aDown[BufferIndex] + SEGGER_RTT_UNCACHED_OFF);  // Access uncached to make sure we see changes made by the J-Link side and all of our changes go into HW directly
+  v = pRing->WrOff;
+  return v - pRing->RdOff;
+}
+
+/*********************************************************************
+*
+*       SEGGER_RTT_HasDataUp
+*
+*  Function description
+*    Check if there is data remaining to be sent in the given buffer.
+*
+*  Return value:
+*  ==0:  No data
+*  !=0:  Data in buffer
+*
+*/
+unsigned SEGGER_RTT_HasDataUp(unsigned BufferIndex) {
+  SEGGER_RTT_BUFFER_UP* pRing;
+  unsigned                v;
+
+  pRing = (SEGGER_RTT_BUFFER_UP*)((char*)&_SEGGER_RTT.aUp[BufferIndex] + SEGGER_RTT_UNCACHED_OFF);  // Access uncached to make sure we see changes made by the J-Link side and all of our changes go into HW directly
+  v = pRing->RdOff;
+  return pRing->WrOff - v;
+}
+
+/*********************************************************************
+*
+*       SEGGER_RTT_AllocDownBuffer
+*
+*  Function description
+*    Run-time configuration of the next down-buffer (H->T).
+*    The next buffer, which is not used yet is configured.
+*    This includes: Buffer address, size, name, flags, ...
+*
+*  Parameters
+*    sName        Pointer to a constant name string.
+*    pBuffer      Pointer to a buffer to be used.
+*    BufferSize   Size of the buffer.
+*    Flags        Operating modes. Define behavior if buffer is full (not enough space for entire message).
+*                 Flags[31:24] are used for validity check and must be zero. Flags[23:2] are reserved for future use. Flags[1:0] = RTT operating mode.
+*
+*  Return value
+*    >= 0 - O.K. Buffer Index
+*     < 0 - Error
+*/
+int SEGGER_RTT_AllocDownBuffer(const char* sName, void* pBuffer, unsigned BufferSize, unsigned Flags) {
+  int BufferIndex;
+  volatile SEGGER_RTT_CB* pRTTCB;
+
+  INIT();
+  SEGGER_RTT_LOCK();
+  pRTTCB = (volatile SEGGER_RTT_CB*)((unsigned char*)&_SEGGER_RTT + SEGGER_RTT_UNCACHED_OFF);  // Access RTTCB uncached to make sure we see changes made by the J-Link side and all of our changes go into HW directly
+  BufferIndex = 0;
+  do {
+    if (pRTTCB->aDown[BufferIndex].pBuffer == NULL) {
+      break;
+    }
+    BufferIndex++;
+  } while (BufferIndex < pRTTCB->MaxNumDownBuffers);
+  if (BufferIndex < pRTTCB->MaxNumDownBuffers) {
+    pRTTCB->aDown[BufferIndex].sName        = sName;
+    pRTTCB->aDown[BufferIndex].pBuffer      = (char*)pBuffer;
+    pRTTCB->aDown[BufferIndex].SizeOfBuffer = BufferSize;
+    pRTTCB->aDown[BufferIndex].RdOff        = 0u;
+    pRTTCB->aDown[BufferIndex].WrOff        = 0u;
+    pRTTCB->aDown[BufferIndex].Flags        = Flags;
+    RTT__DMB();                     // Force data write to be complete before writing the <WrOff>, in case CPU is allowed to change the order of memory accesses
+  } else {
+    BufferIndex = -1;
+  }
+  SEGGER_RTT_UNLOCK();
+  return BufferIndex;
+}
+
+/*********************************************************************
+*
+*       SEGGER_RTT_AllocUpBuffer
+*
+*  Function description
+*    Run-time configuration of the next up-buffer (T->H).
+*    The next buffer, which is not used yet is configured.
+*    This includes: Buffer address, size, name, flags, ...
+*
+*  Parameters
+*    sName        Pointer to a constant name string.
+*    pBuffer      Pointer to a buffer to be used.
+*    BufferSize   Size of the buffer.
+*    Flags        Operating modes. Define behavior if buffer is full (not enough space for entire message).
+*                 Flags[31:24] are used for validity check and must be zero. Flags[23:2] are reserved for future use. Flags[1:0] = RTT operating mode.
+*
+*  Return value
+*    >= 0 - O.K. Buffer Index
+*     < 0 - Error
+*/
+int SEGGER_RTT_AllocUpBuffer(const char* sName, void* pBuffer, unsigned BufferSize, unsigned Flags) {
+  int BufferIndex;
+  volatile SEGGER_RTT_CB* pRTTCB;
+
+  INIT();
+  SEGGER_RTT_LOCK();
+  pRTTCB = (volatile SEGGER_RTT_CB*)((unsigned char*)&_SEGGER_RTT + SEGGER_RTT_UNCACHED_OFF);  // Access RTTCB uncached to make sure we see changes made by the J-Link side and all of our changes go into HW directly
+  BufferIndex = 0;
+  do {
+    if (pRTTCB->aUp[BufferIndex].pBuffer == NULL) {
+      break;
+    }
+    BufferIndex++;
+  } while (BufferIndex < pRTTCB->MaxNumUpBuffers);
+  if (BufferIndex < pRTTCB->MaxNumUpBuffers) {
+    pRTTCB->aUp[BufferIndex].sName        = sName;
+    pRTTCB->aUp[BufferIndex].pBuffer      = (char*)pBuffer;
+    pRTTCB->aUp[BufferIndex].SizeOfBuffer = BufferSize;
+    pRTTCB->aUp[BufferIndex].RdOff        = 0u;
+    pRTTCB->aUp[BufferIndex].WrOff        = 0u;
+    pRTTCB->aUp[BufferIndex].Flags        = Flags;
+    RTT__DMB();                     // Force data write to be complete before writing the <WrOff>, in case CPU is allowed to change the order of memory accesses
+  } else {
+    BufferIndex = -1;
+  }
+  SEGGER_RTT_UNLOCK();
+  return BufferIndex;
+}
+
+/*********************************************************************
+*
+*       SEGGER_RTT_ConfigUpBuffer
+*
+*  Function description
+*    Run-time configuration of a specific up-buffer (T->H).
+*    Buffer to be configured is specified by index.
+*    This includes: Buffer address, size, name, flags, ...
+*
+*  Parameters
+*    BufferIndex  Index of the buffer to configure.
+*    sName        Pointer to a constant name string.
+*    pBuffer      Pointer to a buffer to be used.
+*    BufferSize   Size of the buffer.
+*    Flags        Operating modes. Define behavior if buffer is full (not enough space for entire message).
+*                 Flags[31:24] are used for validity check and must be zero. Flags[23:2] are reserved for future use. Flags[1:0] = RTT operating mode.
+*
+*  Return value
+*    >= 0 - O.K.
+*     < 0 - Error
+*
+*  Additional information
+*    Buffer 0 is configured on compile-time.
+*    May only be called once per buffer.
+*    Buffer name and flags can be reconfigured using the appropriate functions.
+*/
+int SEGGER_RTT_ConfigUpBuffer(unsigned BufferIndex, const char* sName, void* pBuffer, unsigned BufferSize, unsigned Flags) {
+  int r;
+  volatile SEGGER_RTT_CB* pRTTCB;
+  volatile SEGGER_RTT_BUFFER_UP* pUp;
+
+  INIT();
+  pRTTCB = (volatile SEGGER_RTT_CB*)((unsigned char*)&_SEGGER_RTT + SEGGER_RTT_UNCACHED_OFF);  // Access RTTCB uncached to make sure we see changes made by the J-Link side and all of our changes go into HW directly
+  if (BufferIndex < SEGGER_RTT_MAX_NUM_UP_BUFFERS) {
+    SEGGER_RTT_LOCK();
+    pUp = &pRTTCB->aUp[BufferIndex];
+    if (BufferIndex) {
+      pUp->sName        = sName;
+      pUp->pBuffer      = (char*)pBuffer;
+      pUp->SizeOfBuffer = BufferSize;
+      pUp->RdOff        = 0u;
+      pUp->WrOff        = 0u;
+    }
+    pUp->Flags          = Flags;
+    SEGGER_RTT_UNLOCK();
+    r =  0;
+  } else {
+    r = -1;
+  }
+  return r;
+}
+
+/*********************************************************************
+*
+*       SEGGER_RTT_ConfigDownBuffer
+*
+*  Function description
+*    Run-time configuration of a specific down-buffer (H->T).
+*    Buffer to be configured is specified by index.
+*    This includes: Buffer address, size, name, flags, ...
+*
+*  Parameters
+*    BufferIndex  Index of the buffer to configure.
+*    sName        Pointer to a constant name string.
+*    pBuffer      Pointer to a buffer to be used.
+*    BufferSize   Size of the buffer.
+*    Flags        Operating modes. Define behavior if buffer is full (not enough space for entire message).
+*                 Flags[31:24] are used for validity check and must be zero. Flags[23:2] are reserved for future use. Flags[1:0] = RTT operating mode.
+*
+*  Return value
+*    >= 0  O.K.
+*     < 0  Error
+*
+*  Additional information
+*    Buffer 0 is configured on compile-time.
+*    May only be called once per buffer.
+*    Buffer name and flags can be reconfigured using the appropriate functions.
+*/
+int SEGGER_RTT_ConfigDownBuffer(unsigned BufferIndex, const char* sName, void* pBuffer, unsigned BufferSize, unsigned Flags) {
+  int r;
+  volatile SEGGER_RTT_CB* pRTTCB;
+  volatile SEGGER_RTT_BUFFER_DOWN* pDown;
+
+  INIT();
+  pRTTCB = (volatile SEGGER_RTT_CB*)((unsigned char*)&_SEGGER_RTT + SEGGER_RTT_UNCACHED_OFF);  // Access RTTCB uncached to make sure we see changes made by the J-Link side and all of our changes go into HW directly
+  if (BufferIndex < SEGGER_RTT_MAX_NUM_DOWN_BUFFERS) {
+    SEGGER_RTT_LOCK();
+    pDown = &pRTTCB->aDown[BufferIndex];
+    if (BufferIndex) {
+      pDown->sName        = sName;
+      pDown->pBuffer      = (char*)pBuffer;
+      pDown->SizeOfBuffer = BufferSize;
+      pDown->RdOff        = 0u;
+      pDown->WrOff        = 0u;
+    }
+    pDown->Flags          = Flags;
+    RTT__DMB();                     // Force data write to be complete before writing the <WrOff>, in case CPU is allowed to change the order of memory accesses
+    SEGGER_RTT_UNLOCK();
+    r =  0;
+  } else {
+    r = -1;
+  }
+  return r;
+}
+
+/*********************************************************************
+*
+*       SEGGER_RTT_SetNameUpBuffer
+*
+*  Function description
+*    Run-time configuration of a specific up-buffer name (T->H).
+*    Buffer to be configured is specified by index.
+*
+*  Parameters
+*    BufferIndex  Index of the buffer to renamed.
+*    sName        Pointer to a constant name string.
+*
+*  Return value
+*    >= 0  O.K.
+*     < 0  Error
+*/
+int SEGGER_RTT_SetNameUpBuffer(unsigned BufferIndex, const char* sName) {
+  int r;
+  volatile SEGGER_RTT_CB* pRTTCB;
+  volatile SEGGER_RTT_BUFFER_UP* pUp;
+
+  INIT();
+  pRTTCB = (volatile SEGGER_RTT_CB*)((unsigned char*)&_SEGGER_RTT + SEGGER_RTT_UNCACHED_OFF);  // Access RTTCB uncached to make sure we see changes made by the J-Link side and all of our changes go into HW directly
+  if (BufferIndex < SEGGER_RTT_MAX_NUM_UP_BUFFERS) {
+    SEGGER_RTT_LOCK();
+    pUp = &pRTTCB->aUp[BufferIndex];
+    pUp->sName = sName;
+    SEGGER_RTT_UNLOCK();
+    r =  0;
+  } else {
+    r = -1;
+  }
+  return r;
+}
+
+/*********************************************************************
+*
+*       SEGGER_RTT_SetNameDownBuffer
+*
+*  Function description
+*    Run-time configuration of a specific Down-buffer name (T->H).
+*    Buffer to be configured is specified by index.
+*
+*  Parameters
+*    BufferIndex  Index of the buffer to renamed.
+*    sName        Pointer to a constant name string.
+*
+*  Return value
+*    >= 0  O.K.
+*     < 0  Error
+*/
+int SEGGER_RTT_SetNameDownBuffer(unsigned BufferIndex, const char* sName) {
+  int r;
+  volatile SEGGER_RTT_CB* pRTTCB;
+  volatile SEGGER_RTT_BUFFER_DOWN* pDown;
+
+  INIT();
+  pRTTCB = (volatile SEGGER_RTT_CB*)((unsigned char*)&_SEGGER_RTT + SEGGER_RTT_UNCACHED_OFF);  // Access RTTCB uncached to make sure we see changes made by the J-Link side and all of our changes go into HW directly
+  if (BufferIndex < SEGGER_RTT_MAX_NUM_DOWN_BUFFERS) {
+    SEGGER_RTT_LOCK();
+    pDown = &pRTTCB->aDown[BufferIndex];
+    pDown->sName = sName;
+    SEGGER_RTT_UNLOCK();
+    r =  0;
+  } else {
+    r = -1;
+  }
+  return r;
+}
+
+/*********************************************************************
+*
+*       SEGGER_RTT_SetFlagsUpBuffer
+*
+*  Function description
+*    Run-time configuration of specific up-buffer flags (T->H).
+*    Buffer to be configured is specified by index.
+*
+*  Parameters
+*    BufferIndex  Index of the buffer.
+*    Flags        Flags to set for the buffer.
+*                 Flags[31:24] are used for validity check and must be zero. Flags[23:2] are reserved for future use. Flags[1:0] = RTT operating mode.
+*
+*  Return value
+*    >= 0  O.K.
+*     < 0  Error
+*/
+int SEGGER_RTT_SetFlagsUpBuffer(unsigned BufferIndex, unsigned Flags) {
+  int r;
+  volatile SEGGER_RTT_CB* pRTTCB;
+  volatile SEGGER_RTT_BUFFER_UP* pUp;
+
+  INIT();
+  pRTTCB = (volatile SEGGER_RTT_CB*)((unsigned char*)&_SEGGER_RTT + SEGGER_RTT_UNCACHED_OFF);  // Access RTTCB uncached to make sure we see changes made by the J-Link side and all of our changes go into HW directly
+  if (BufferIndex < SEGGER_RTT_MAX_NUM_UP_BUFFERS) {
+    SEGGER_RTT_LOCK();
+    pUp = &pRTTCB->aUp[BufferIndex];
+    pUp->Flags = Flags;
+    SEGGER_RTT_UNLOCK();
+    r =  0;
+  } else {
+    r = -1;
+  }
+  return r;
+}
+
+/*********************************************************************
+*
+*       SEGGER_RTT_SetFlagsDownBuffer
+*
+*  Function description
+*    Run-time configuration of specific Down-buffer flags (T->H).
+*    Buffer to be configured is specified by index.
+*
+*  Parameters
+*    BufferIndex  Index of the buffer to renamed.
+*    Flags        Flags to set for the buffer.
+*                 Flags[31:24] are used for validity check and must be zero. Flags[23:2] are reserved for future use. Flags[1:0] = RTT operating mode.
+*
+*  Return value
+*    >= 0  O.K.
+*     < 0  Error
+*/
+int SEGGER_RTT_SetFlagsDownBuffer(unsigned BufferIndex, unsigned Flags) {
+  int r;
+  volatile SEGGER_RTT_CB* pRTTCB;
+  volatile SEGGER_RTT_BUFFER_DOWN* pDown;
+
+  INIT();
+  pRTTCB = (volatile SEGGER_RTT_CB*)((unsigned char*)&_SEGGER_RTT + SEGGER_RTT_UNCACHED_OFF);  // Access RTTCB uncached to make sure we see changes made by the J-Link side and all of our changes go into HW directly
+  if (BufferIndex < SEGGER_RTT_MAX_NUM_DOWN_BUFFERS) {
+    SEGGER_RTT_LOCK();
+    pDown = &pRTTCB->aDown[BufferIndex];
+    pDown->Flags = Flags;
+    SEGGER_RTT_UNLOCK();
+    r =  0;
+  } else {
+    r = -1;
+  }
+  return r;
+}
+
+/*********************************************************************
+*
+*       SEGGER_RTT_Init
+*
+*  Function description
+*    Initializes the RTT Control Block.
+*    Should be used in RAM targets, at start of the application.
+*
+*/
+void SEGGER_RTT_Init (void) {
+  _DoInit();
+}
+
+/*********************************************************************
+*
+*       SEGGER_RTT_SetTerminal
+*
+*  Function description
+*    Sets the terminal to be used for output on channel 0.
+*
+*  Parameters
+*    TerminalId  Index of the terminal.
+*
+*  Return value
+*    >= 0  O.K.
+*     < 0  Error (e.g. if RTT is configured for non-blocking mode and there was no space in the buffer to set the new terminal Id)
+*
+*  Notes
+*    (1) Buffer 0 is always reserved for terminal I/O, so we can use index 0 here, fixed
+*/
+int SEGGER_RTT_SetTerminal (unsigned char TerminalId) {
+  unsigned char         ac[2];
+  SEGGER_RTT_BUFFER_UP* pRing;
+  unsigned Avail;
+  int r;
+
+  INIT();
+  r = 0;
+  ac[0] = 0xFFu;
+  if (TerminalId < sizeof(_aTerminalId)) { // We only support a certain number of channels
+    ac[1] = _aTerminalId[TerminalId];
+    pRing = (SEGGER_RTT_BUFFER_UP*)((char*)&_SEGGER_RTT.aUp[0] + SEGGER_RTT_UNCACHED_OFF);  // Access uncached to make sure we see changes made by the J-Link side and all of our changes go into HW directly
+    SEGGER_RTT_LOCK();                     // Lock to make sure that no other task is writing into buffer, while we are and number of free bytes in buffer does not change downwards after checking and before writing
+    if ((pRing->Flags & SEGGER_RTT_MODE_MASK) == SEGGER_RTT_MODE_BLOCK_IF_FIFO_FULL) {
+      _ActiveTerminal = TerminalId;
+      _WriteBlocking(pRing, (const char*)ac, 2u);
+    } else {                                                                            // Skipping mode or trim mode? => We cannot trim this command so handling is the same for both modes
+      Avail = _GetAvailWriteSpace(pRing);
+      if (Avail >= 2) {
+        _ActiveTerminal = TerminalId;    // Only change active terminal in case of success
+        _WriteNoCheck(pRing, (const char*)ac, 2u);
+      } else {
+        r = -1;
+      }
+    }
+    SEGGER_RTT_UNLOCK();
+  } else {
+    r = -1;
+  }
+  return r;
+}
+
+/*********************************************************************
+*
+*       SEGGER_RTT_TerminalOut
+*
+*  Function description
+*    Writes a string to the given terminal
+*     without changing the terminal for channel 0.
+*
+*  Parameters
+*    TerminalId   Index of the terminal.
+*    s            String to be printed on the terminal.
+*
+*  Return value
+*    >= 0 - Number of bytes written.
+*     < 0 - Error.
+*
+*/
+int SEGGER_RTT_TerminalOut (unsigned char TerminalId, const char* s) {
+  int                   Status;
+  unsigned              FragLen;
+  unsigned              Avail;
+  SEGGER_RTT_BUFFER_UP* pRing;
+  //
+  INIT();
+  //
+  // Validate terminal ID.
+  //
+  if (TerminalId < (char)sizeof(_aTerminalId)) { // We only support a certain number of channels
+    //
+    // Get "to-host" ring buffer.
+    //
+    pRing = (SEGGER_RTT_BUFFER_UP*)((char*)&_SEGGER_RTT.aUp[0] + SEGGER_RTT_UNCACHED_OFF);  // Access uncached to make sure we see changes made by the J-Link side and all of our changes go into HW directly
+    //
+    // Need to be able to change terminal, write data, change back.
+    // Compute the fixed and variable sizes.
+    //
+    FragLen = STRLEN(s);
+    //
+    // How we output depends upon the mode...
+    //
+    SEGGER_RTT_LOCK();
+    Avail = _GetAvailWriteSpace(pRing);
+    switch (pRing->Flags & SEGGER_RTT_MODE_MASK) {
+    case SEGGER_RTT_MODE_NO_BLOCK_SKIP:
+      //
+      // If we are in skip mode and there is no space for the whole
+      // of this output, don't bother switching terminals at all.
+      //
+      if (Avail < (FragLen + 4u)) {
+        Status = 0;
+      } else {
+        _PostTerminalSwitch(pRing, TerminalId);
+        Status = (int)_WriteBlocking(pRing, s, FragLen);
+        _PostTerminalSwitch(pRing, _ActiveTerminal);
+      }
+      break;
+    case SEGGER_RTT_MODE_NO_BLOCK_TRIM:
+      //
+      // If we are in trim mode and there is not enough space for everything,
+      // trim the output but always include the terminal switch.  If no room
+      // for terminal switch, skip that totally.
+      //
+      if (Avail < 4u) {
+        Status = -1;
+      } else {
+        _PostTerminalSwitch(pRing, TerminalId);
+        Status = (int)_WriteBlocking(pRing, s, (FragLen < (Avail - 4u)) ? FragLen : (Avail - 4u));
+        _PostTerminalSwitch(pRing, _ActiveTerminal);
+      }
+      break;
+    case SEGGER_RTT_MODE_BLOCK_IF_FIFO_FULL:
+      //
+      // If we are in blocking mode, output everything.
+      //
+      _PostTerminalSwitch(pRing, TerminalId);
+      Status = (int)_WriteBlocking(pRing, s, FragLen);
+      _PostTerminalSwitch(pRing, _ActiveTerminal);
+      break;
+    default:
+      Status = -1;
+      break;
+    }
+    //
+    // Finish up.
+    //
+    SEGGER_RTT_UNLOCK();
+  } else {
+    Status = -1;
+  }
+  return Status;
+}
+
+/*********************************************************************
+*
+*       SEGGER_RTT_GetAvailWriteSpace
+*
+*  Function description
+*    Returns the number of bytes available in the ring buffer.
+*
+*  Parameters
+*    BufferIndex  Index of the up buffer.
+*
+*  Return value
+*    Number of bytes that are free in the selected up buffer.
+*/
+unsigned SEGGER_RTT_GetAvailWriteSpace (unsigned BufferIndex) {
+  SEGGER_RTT_BUFFER_UP* pRing;
+
+  pRing = (SEGGER_RTT_BUFFER_UP*)((char*)&_SEGGER_RTT.aUp[BufferIndex] + SEGGER_RTT_UNCACHED_OFF);  // Access uncached to make sure we see changes made by the J-Link side and all of our changes go into HW directly
+  return _GetAvailWriteSpace(pRing);
+}
+
+
+/*********************************************************************
+*
+*       SEGGER_RTT_GetBytesInBuffer()
+*
+*  Function description
+*    Returns the number of bytes currently used in the up buffer.
+*
+*  Parameters
+*    BufferIndex  Index of the up buffer.
+*
+*  Return value
+*    Number of bytes that are used in the buffer.
+*/
+unsigned SEGGER_RTT_GetBytesInBuffer(unsigned BufferIndex) {
+  unsigned RdOff;
+  unsigned WrOff;
+  unsigned r;
+  volatile SEGGER_RTT_CB* pRTTCB;
+  //
+  // Avoid warnings regarding volatile access order.  It's not a problem
+  // in this case, but dampen compiler enthusiasm.
+  //
+  pRTTCB = (volatile SEGGER_RTT_CB*)((unsigned char*)&_SEGGER_RTT + SEGGER_RTT_UNCACHED_OFF);  // Access RTTCB uncached to make sure we see changes made by the J-Link side and all of our changes go into HW directly
+  RdOff = pRTTCB->aUp[BufferIndex].RdOff;
+  WrOff = pRTTCB->aUp[BufferIndex].WrOff;
+  if (RdOff <= WrOff) {
+    r = WrOff - RdOff;
+  } else {
+    r = pRTTCB->aUp[BufferIndex].SizeOfBuffer - (WrOff - RdOff);
+  }
+  return r;
+}
+
+/*************************** End of file ****************************/

+ 492 - 0
code/debug/SEGGER/SEGGER_RTT.h

@@ -0,0 +1,492 @@
+/*********************************************************************
+*                    SEGGER Microcontroller GmbH                     *
+*                        The Embedded Experts                        *
+**********************************************************************
+*                                                                    *
+*            (c) 1995 - 2021 SEGGER Microcontroller GmbH             *
+*                                                                    *
+*       www.segger.com     Support: support@segger.com               *
+*                                                                    *
+**********************************************************************
+*                                                                    *
+*       SEGGER SystemView * Real-time application analysis           *
+*                                                                    *
+**********************************************************************
+*                                                                    *
+* All rights reserved.                                               *
+*                                                                    *
+* SEGGER strongly recommends to not make any changes                 *
+* to or modify the source code of this software in order to stay     *
+* compatible with the SystemView and RTT protocol, and J-Link.       *
+*                                                                    *
+* Redistribution and use in source and binary forms, with or         *
+* without modification, are permitted provided that the following    *
+* condition is met:                                                  *
+*                                                                    *
+* o Redistributions of source code must retain the above copyright   *
+*   notice, this condition and the following disclaimer.             *
+*                                                                    *
+* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND             *
+* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,        *
+* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF           *
+* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE           *
+* DISCLAIMED. IN NO EVENT SHALL SEGGER Microcontroller BE LIABLE FOR *
+* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR           *
+* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT  *
+* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;    *
+* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF      *
+* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT          *
+* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE  *
+* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH   *
+* DAMAGE.                                                            *
+*                                                                    *
+**********************************************************************
+*                                                                    *
+*       SystemView version: 3.32                                    *
+*                                                                    *
+**********************************************************************
+---------------------------END-OF-HEADER------------------------------
+File    : SEGGER_RTT.h
+Purpose : Implementation of SEGGER real-time transfer which allows
+          real-time communication on targets which support debugger 
+          memory accesses while the CPU is running.
+Revision: $Rev: 25842 $
+----------------------------------------------------------------------
+*/
+
+#ifndef SEGGER_RTT_H
+#define SEGGER_RTT_H
+
+#include "SEGGER_RTT_Conf.h"
+
+/*********************************************************************
+*
+*       Defines, defaults
+*
+**********************************************************************
+*/
+
+#ifndef RTT_USE_ASM
+  //
+  // Some cores support out-of-order memory accesses (reordering of memory accesses in the core)
+  // For such cores, we need to define a memory barrier to guarantee the order of certain accesses to the RTT ring buffers.
+  // Needed for:
+  //   Cortex-M7 (ARMv7-M)
+  //   Cortex-M23 (ARM-v8M)
+  //   Cortex-M33 (ARM-v8M)
+  //   Cortex-A/R (ARM-v7A/R)
+  //
+  // We do not explicitly check for "Embedded Studio" as the compiler in use determines what we support.
+  // You can use an external toolchain like IAR inside ES. So there is no point in checking for "Embedded Studio"
+  //
+  #if (defined __CROSSWORKS_ARM)                  // Rowley Crossworks
+    #define _CC_HAS_RTT_ASM_SUPPORT 1
+    #if (defined __ARM_ARCH_7M__)                 // Cortex-M3
+      #define _CORE_HAS_RTT_ASM_SUPPORT 1
+    #elif (defined __ARM_ARCH_7EM__)              // Cortex-M4/M7
+      #define _CORE_HAS_RTT_ASM_SUPPORT 1
+      #define _CORE_NEEDS_DMB           1
+      #define RTT__DMB() __asm volatile ("dmb\n" : : :);
+    #elif (defined __ARM_ARCH_8M_BASE__)          // Cortex-M23
+      #define _CORE_HAS_RTT_ASM_SUPPORT 0
+      #define _CORE_NEEDS_DMB           1
+      #define RTT__DMB() __asm volatile ("dmb\n" : : :);
+    #elif (defined __ARM_ARCH_8M_MAIN__)          // Cortex-M33
+      #define _CORE_HAS_RTT_ASM_SUPPORT 1
+      #define _CORE_NEEDS_DMB           1
+      #define RTT__DMB() __asm volatile ("dmb\n" : : :);
+    #else
+      #define _CORE_HAS_RTT_ASM_SUPPORT 0
+    #endif
+  #elif (defined __ARMCC_VERSION)
+    //
+    // ARM compiler
+    // ARM compiler V6.0 and later is clang based.
+    // Our ASM part is compatible to clang.
+    //
+    #if (__ARMCC_VERSION >= 6000000)
+      #define _CC_HAS_RTT_ASM_SUPPORT 1
+    #else
+      #define _CC_HAS_RTT_ASM_SUPPORT 0
+    #endif
+    #if (defined __ARM_ARCH_6M__)                 // Cortex-M0 / M1
+      #define _CORE_HAS_RTT_ASM_SUPPORT 0         // No ASM support for this architecture
+    #elif (defined __ARM_ARCH_7M__)               // Cortex-M3
+      #define _CORE_HAS_RTT_ASM_SUPPORT 1
+    #elif (defined __ARM_ARCH_7EM__)              // Cortex-M4/M7
+      #define _CORE_HAS_RTT_ASM_SUPPORT 1
+      #define _CORE_NEEDS_DMB           1
+      #define RTT__DMB() __asm volatile ("dmb\n" : : :);
+    #elif (defined __ARM_ARCH_8M_BASE__)          // Cortex-M23
+      #define _CORE_HAS_RTT_ASM_SUPPORT 0
+      #define _CORE_NEEDS_DMB           1
+      #define RTT__DMB() __asm volatile ("dmb\n" : : :);
+    #elif (defined __ARM_ARCH_8M_MAIN__)          // Cortex-M33
+      #define _CORE_HAS_RTT_ASM_SUPPORT 1
+      #define _CORE_NEEDS_DMB           1
+      #define RTT__DMB() __asm volatile ("dmb\n" : : :);
+    #elif ((defined __ARM_ARCH_7A__) || (defined __ARM_ARCH_7R__))  // Cortex-A/R 32-bit ARMv7-A/R
+      #define _CORE_NEEDS_DMB           1
+      #define RTT__DMB() __asm volatile ("dmb\n" : : :);
+    #else
+      #define _CORE_HAS_RTT_ASM_SUPPORT 0
+    #endif
+  #elif ((defined __GNUC__) || (defined __clang__))
+    //
+    // GCC / Clang
+    //
+    #define _CC_HAS_RTT_ASM_SUPPORT 1
+    // ARM 7/9: __ARM_ARCH_5__ / __ARM_ARCH_5E__ / __ARM_ARCH_5T__ / __ARM_ARCH_5T__ / __ARM_ARCH_5TE__
+    #if (defined __ARM_ARCH_7M__)                 // Cortex-M3
+      #define _CORE_HAS_RTT_ASM_SUPPORT 1
+    #elif (defined __ARM_ARCH_7EM__)              // Cortex-M4/M7
+      #define _CORE_HAS_RTT_ASM_SUPPORT 1
+      #define _CORE_NEEDS_DMB           1         // Only Cortex-M7 needs a DMB but we cannot distinguish M4 and M7 here...
+      #define RTT__DMB() __asm volatile ("dmb\n" : : :);
+    #elif (defined __ARM_ARCH_8M_BASE__)          // Cortex-M23
+      #define _CORE_HAS_RTT_ASM_SUPPORT 0
+      #define _CORE_NEEDS_DMB           1
+      #define RTT__DMB() __asm volatile ("dmb\n" : : :);
+    #elif (defined __ARM_ARCH_8M_MAIN__)          // Cortex-M33
+      #define _CORE_HAS_RTT_ASM_SUPPORT 1
+      #define _CORE_NEEDS_DMB           1
+      #define RTT__DMB() __asm volatile ("dmb\n" : : :);
+    #elif ((defined __ARM_ARCH_7A__) || (defined __ARM_ARCH_7R__))  // Cortex-A/R 32-bit ARMv7-A/R
+      #define _CORE_NEEDS_DMB           1
+      #define RTT__DMB() __asm volatile ("dmb\n" : : :);
+    #else
+      #define _CORE_HAS_RTT_ASM_SUPPORT 0
+    #endif
+  #elif ((defined __IASMARM__) || (defined __ICCARM__))
+    //
+    // IAR assembler/compiler
+    //
+    #define _CC_HAS_RTT_ASM_SUPPORT 1
+    #if (__VER__ < 6300000)
+      #define VOLATILE
+    #else
+      #define VOLATILE volatile
+    #endif
+    #if (defined __ARM7M__)                            // Needed for old versions that do not know the define yet
+      #if (__CORE__ == __ARM7M__)                      // Cortex-M3
+        #define _CORE_HAS_RTT_ASM_SUPPORT 1
+      #endif
+    #endif
+    #if (defined __ARM7EM__)
+      #if (__CORE__ == __ARM7EM__)                     // Cortex-M4/M7
+        #define _CORE_HAS_RTT_ASM_SUPPORT 1
+        #define _CORE_NEEDS_DMB 1
+        #define RTT__DMB() asm VOLATILE ("DMB");
+      #endif
+    #endif
+    #if (defined __ARM8M_BASELINE__)
+      #if (__CORE__ == __ARM8M_BASELINE__)             // Cortex-M23
+        #define _CORE_HAS_RTT_ASM_SUPPORT 0
+        #define _CORE_NEEDS_DMB 1
+        #define RTT__DMB() asm VOLATILE ("DMB");
+      #endif
+    #endif
+    #if (defined __ARM8M_MAINLINE__)
+      #if (__CORE__ == __ARM8M_MAINLINE__)             // Cortex-M33
+        #define _CORE_HAS_RTT_ASM_SUPPORT 1
+        #define _CORE_NEEDS_DMB 1
+        #define RTT__DMB() asm VOLATILE ("DMB");
+      #endif
+    #endif
+    #if (defined __ARM8EM_MAINLINE__)
+      #if (__CORE__ == __ARM8EM_MAINLINE__)            // Cortex-???
+        #define _CORE_HAS_RTT_ASM_SUPPORT 1
+        #define _CORE_NEEDS_DMB 1
+        #define RTT__DMB() asm VOLATILE ("DMB");
+      #endif
+    #endif
+    #if (defined __ARM7A__)
+      #if (__CORE__ == __ARM7A__)                      // Cortex-A 32-bit ARMv7-A
+        #define _CORE_NEEDS_DMB 1
+        #define RTT__DMB() asm VOLATILE ("DMB");
+      #endif
+    #endif
+    #if (defined __ARM7R__)
+      #if (__CORE__ == __ARM7R__)                      // Cortex-R 32-bit ARMv7-R
+        #define _CORE_NEEDS_DMB 1
+        #define RTT__DMB() asm VOLATILE ("DMB");
+      #endif
+    #endif
+// TBD: __ARM8A__ => Cortex-A 64-bit ARMv8-A
+// TBD: __ARM8R__ => Cortex-R 64-bit ARMv8-R
+  #else
+    //
+    // Other compilers
+    //
+    #define _CC_HAS_RTT_ASM_SUPPORT   0
+    #define _CORE_HAS_RTT_ASM_SUPPORT 0
+  #endif
+  //
+  // If IDE and core support the ASM version, enable ASM version by default
+  //
+  #ifndef _CORE_HAS_RTT_ASM_SUPPORT
+    #define _CORE_HAS_RTT_ASM_SUPPORT 0              // Default for unknown cores
+  #endif
+  #if (_CC_HAS_RTT_ASM_SUPPORT && _CORE_HAS_RTT_ASM_SUPPORT)
+    #define RTT_USE_ASM                           (0)
+  #else
+    #define RTT_USE_ASM                           (0)
+  #endif
+#endif
+
+#ifndef _CORE_NEEDS_DMB
+  #define _CORE_NEEDS_DMB 0
+#endif
+
+#ifndef RTT__DMB
+  #if _CORE_NEEDS_DMB
+    #error "Don't know how to place inline assembly for DMB"
+  #else
+    #define RTT__DMB()
+  #endif
+#endif
+
+#ifndef SEGGER_RTT_CPU_CACHE_LINE_SIZE
+  #define SEGGER_RTT_CPU_CACHE_LINE_SIZE (0)   // On most target systems where RTT is used, we do not have a CPU cache, therefore 0 is a good default here
+#endif
+
+#ifndef SEGGER_RTT_UNCACHED_OFF
+  #if SEGGER_RTT_CPU_CACHE_LINE_SIZE
+    #error "SEGGER_RTT_UNCACHED_OFF must be defined when setting SEGGER_RTT_CPU_CACHE_LINE_SIZE != 0"
+  #else
+    #define SEGGER_RTT_UNCACHED_OFF (0)
+  #endif
+#endif
+#if RTT_USE_ASM
+  #if SEGGER_RTT_CPU_CACHE_LINE_SIZE
+    #error "RTT_USE_ASM is not available if SEGGER_RTT_CPU_CACHE_LINE_SIZE != 0"
+  #endif
+#endif
+
+#ifndef SEGGER_RTT_ASM  // defined when SEGGER_RTT.h is included from assembly file
+#include <stdlib.h>
+#include <stdarg.h>
+
+/*********************************************************************
+*
+*       Defines, fixed
+*
+**********************************************************************
+*/
+
+//
+// Determine how much we must pad the control block to make it a multiple of a cache line in size
+// Assuming: U8 = 1B
+//           U16 = 2B
+//           U32 = 4B
+//           U8/U16/U32* = 4B
+//
+#if SEGGER_RTT_CPU_CACHE_LINE_SIZE    // Avoid division by zero in case we do not have any cache
+  #define SEGGER_RTT__ROUND_UP_2_CACHE_LINE_SIZE(NumBytes) (((NumBytes + SEGGER_RTT_CPU_CACHE_LINE_SIZE - 1) / SEGGER_RTT_CPU_CACHE_LINE_SIZE) * SEGGER_RTT_CPU_CACHE_LINE_SIZE)
+#else
+  #define SEGGER_RTT__ROUND_UP_2_CACHE_LINE_SIZE(NumBytes) (NumBytes)
+#endif
+#define SEGGER_RTT__CB_SIZE                              (16 + 4 + 4 + (SEGGER_RTT_MAX_NUM_UP_BUFFERS * 24) + (SEGGER_RTT_MAX_NUM_DOWN_BUFFERS * 24))
+#define SEGGER_RTT__CB_PADDING                           (SEGGER_RTT__ROUND_UP_2_CACHE_LINE_SIZE(SEGGER_RTT__CB_SIZE) - SEGGER_RTT__CB_SIZE)
+
+/*********************************************************************
+*
+*       Types
+*
+**********************************************************************
+*/
+
+//
+// Description for a circular buffer (also called "ring buffer")
+// which is used as up-buffer (T->H)
+//
+typedef struct {
+  const     char*    sName;         // Optional name. Standard names so far are: "Terminal", "SysView", "J-Scope_t4i4"
+            char*    pBuffer;       // Pointer to start of buffer
+            unsigned SizeOfBuffer;  // Buffer size in bytes. Note that one byte is lost, as this implementation does not fill up the buffer in order to avoid the problem of being unable to distinguish between full and empty.
+            unsigned WrOff;         // Position of next item to be written by either target.
+  volatile  unsigned RdOff;         // Position of next item to be read by host. Must be volatile since it may be modified by host.
+            unsigned Flags;         // Contains configuration flags. Flags[31:24] are used for validity check and must be zero. Flags[23:2] are reserved for future use. Flags[1:0] = RTT operating mode.
+} SEGGER_RTT_BUFFER_UP;
+
+//
+// Description for a circular buffer (also called "ring buffer")
+// which is used as down-buffer (H->T)
+//
+typedef struct {
+  const     char*    sName;         // Optional name. Standard names so far are: "Terminal", "SysView", "J-Scope_t4i4"
+            char*    pBuffer;       // Pointer to start of buffer
+            unsigned SizeOfBuffer;  // Buffer size in bytes. Note that one byte is lost, as this implementation does not fill up the buffer in order to avoid the problem of being unable to distinguish between full and empty.
+  volatile  unsigned WrOff;         // Position of next item to be written by host. Must be volatile since it may be modified by host.
+            unsigned RdOff;         // Position of next item to be read by target (down-buffer).
+            unsigned Flags;         // Contains configuration flags. Flags[31:24] are used for validity check and must be zero. Flags[23:2] are reserved for future use. Flags[1:0] = RTT operating mode. 
+} SEGGER_RTT_BUFFER_DOWN;
+
+//
+// RTT control block which describes the number of buffers available
+// as well as the configuration for each buffer
+//
+//
+typedef struct {
+  char                    acID[16];                                 // Initialized to "SEGGER RTT"
+  int                     MaxNumUpBuffers;                          // Initialized to SEGGER_RTT_MAX_NUM_UP_BUFFERS (type. 2)
+  int                     MaxNumDownBuffers;                        // Initialized to SEGGER_RTT_MAX_NUM_DOWN_BUFFERS (type. 2)
+  SEGGER_RTT_BUFFER_UP    aUp[SEGGER_RTT_MAX_NUM_UP_BUFFERS];       // Up buffers, transferring information up from target via debug probe to host
+  SEGGER_RTT_BUFFER_DOWN  aDown[SEGGER_RTT_MAX_NUM_DOWN_BUFFERS];   // Down buffers, transferring information down from host via debug probe to target
+#if SEGGER_RTT__CB_PADDING
+  unsigned char           aDummy[SEGGER_RTT__CB_PADDING];
+#endif
+} SEGGER_RTT_CB;
+
+/*********************************************************************
+*
+*       Global data
+*
+**********************************************************************
+*/
+extern SEGGER_RTT_CB _SEGGER_RTT;
+
+/*********************************************************************
+*
+*       RTT API functions
+*
+**********************************************************************
+*/
+#ifdef __cplusplus
+  extern "C" {
+#endif
+int          SEGGER_RTT_AllocDownBuffer         (const char* sName, void* pBuffer, unsigned BufferSize, unsigned Flags);
+int          SEGGER_RTT_AllocUpBuffer           (const char* sName, void* pBuffer, unsigned BufferSize, unsigned Flags);
+int          SEGGER_RTT_ConfigUpBuffer          (unsigned BufferIndex, const char* sName, void* pBuffer, unsigned BufferSize, unsigned Flags);
+int          SEGGER_RTT_ConfigDownBuffer        (unsigned BufferIndex, const char* sName, void* pBuffer, unsigned BufferSize, unsigned Flags);
+int          SEGGER_RTT_GetKey                  (void);
+unsigned     SEGGER_RTT_HasData                 (unsigned BufferIndex);
+int          SEGGER_RTT_HasKey                  (void);
+unsigned     SEGGER_RTT_HasDataUp               (unsigned BufferIndex);
+void         SEGGER_RTT_Init                    (void);
+unsigned     SEGGER_RTT_Read                    (unsigned BufferIndex,       void* pBuffer, unsigned BufferSize);
+unsigned     SEGGER_RTT_ReadNoLock              (unsigned BufferIndex,       void* pData,   unsigned BufferSize);
+int          SEGGER_RTT_SetNameDownBuffer       (unsigned BufferIndex, const char* sName);
+int          SEGGER_RTT_SetNameUpBuffer         (unsigned BufferIndex, const char* sName);
+int          SEGGER_RTT_SetFlagsDownBuffer      (unsigned BufferIndex, unsigned Flags);
+int          SEGGER_RTT_SetFlagsUpBuffer        (unsigned BufferIndex, unsigned Flags);
+int          SEGGER_RTT_WaitKey                 (void);
+unsigned     SEGGER_RTT_Write                   (unsigned BufferIndex, const void* pBuffer, unsigned NumBytes);
+unsigned     SEGGER_RTT_WriteNoLock             (unsigned BufferIndex, const void* pBuffer, unsigned NumBytes);
+unsigned     SEGGER_RTT_WriteSkipNoLock         (unsigned BufferIndex, const void* pBuffer, unsigned NumBytes);
+unsigned     SEGGER_RTT_ASM_WriteSkipNoLock     (unsigned BufferIndex, const void* pBuffer, unsigned NumBytes);
+unsigned     SEGGER_RTT_WriteString             (unsigned BufferIndex, const char* s);
+void         SEGGER_RTT_WriteWithOverwriteNoLock(unsigned BufferIndex, const void* pBuffer, unsigned NumBytes);
+unsigned     SEGGER_RTT_PutChar                 (unsigned BufferIndex, char c);
+unsigned     SEGGER_RTT_PutCharSkip             (unsigned BufferIndex, char c);
+unsigned     SEGGER_RTT_PutCharSkipNoLock       (unsigned BufferIndex, char c);
+unsigned     SEGGER_RTT_GetAvailWriteSpace      (unsigned BufferIndex);
+unsigned     SEGGER_RTT_GetBytesInBuffer        (unsigned BufferIndex);
+//
+// Function macro for performance optimization
+//
+#define      SEGGER_RTT_HASDATA(n)       (((SEGGER_RTT_BUFFER_DOWN*)((char*)&_SEGGER_RTT.aDown[n] + SEGGER_RTT_UNCACHED_OFF))->WrOff - ((SEGGER_RTT_BUFFER_DOWN*)((char*)&_SEGGER_RTT.aDown[n] + SEGGER_RTT_UNCACHED_OFF))->RdOff)
+
+#if RTT_USE_ASM
+  #define SEGGER_RTT_WriteSkipNoLock  SEGGER_RTT_ASM_WriteSkipNoLock
+#endif
+
+/*********************************************************************
+*
+*       RTT transfer functions to send RTT data via other channels.
+*
+**********************************************************************
+*/
+unsigned     SEGGER_RTT_ReadUpBuffer            (unsigned BufferIndex, void* pBuffer, unsigned BufferSize);
+unsigned     SEGGER_RTT_ReadUpBufferNoLock      (unsigned BufferIndex, void* pData, unsigned BufferSize);
+unsigned     SEGGER_RTT_WriteDownBuffer         (unsigned BufferIndex, const void* pBuffer, unsigned NumBytes);
+unsigned     SEGGER_RTT_WriteDownBufferNoLock   (unsigned BufferIndex, const void* pBuffer, unsigned NumBytes);
+
+#define      SEGGER_RTT_HASDATA_UP(n)    (((SEGGER_RTT_BUFFER_UP*)((char*)&_SEGGER_RTT.aUp[n] + SEGGER_RTT_UNCACHED_OFF))->WrOff - ((SEGGER_RTT_BUFFER_UP*)((char*)&_SEGGER_RTT.aUp[n] + SEGGER_RTT_UNCACHED_OFF))->RdOff)   // Access uncached to make sure we see changes made by the J-Link side and all of our changes go into HW directly
+
+/*********************************************************************
+*
+*       RTT "Terminal" API functions
+*
+**********************************************************************
+*/
+int     SEGGER_RTT_SetTerminal        (unsigned char TerminalId);
+int     SEGGER_RTT_TerminalOut        (unsigned char TerminalId, const char* s);
+
+/*********************************************************************
+*
+*       RTT printf functions (require SEGGER_RTT_printf.c)
+*
+**********************************************************************
+*/
+int SEGGER_RTT_printf(const char * sFormat, ...);
+int SEGGER_RTT_vprintf(unsigned BufferIndex, const char * sFormat, va_list * pParamList);
+
+#ifdef __cplusplus
+  }
+#endif
+
+#endif // ifndef(SEGGER_RTT_ASM)
+
+/*********************************************************************
+*
+*       Defines
+*
+**********************************************************************
+*/
+
+//
+// Operating modes. Define behavior if buffer is full (not enough space for entire message)
+//
+#define SEGGER_RTT_MODE_NO_BLOCK_SKIP         (0)     // Skip. Do not block, output nothing. (Default)
+#define SEGGER_RTT_MODE_NO_BLOCK_TRIM         (1)     // Trim: Do not block, output as much as fits.
+#define SEGGER_RTT_MODE_BLOCK_IF_FIFO_FULL    (2)     // Block: Wait until there is space in the buffer.
+#define SEGGER_RTT_MODE_MASK                  (3)
+
+//
+// Control sequences, based on ANSI.
+// Can be used to control color, and clear the screen
+//
+#define RTT_CTRL_RESET                "\x1B[0m"         // Reset to default colors
+#define RTT_CTRL_CLEAR                "\x1B[2J"         // Clear screen, reposition cursor to top left
+
+#define RTT_CTRL_TEXT_BLACK           "\x1B[2;30m"
+#define RTT_CTRL_TEXT_RED             "\x1B[2;31m"
+#define RTT_CTRL_TEXT_GREEN           "\x1B[2;32m"
+#define RTT_CTRL_TEXT_YELLOW          "\x1B[2;33m"
+#define RTT_CTRL_TEXT_BLUE            "\x1B[2;34m"
+#define RTT_CTRL_TEXT_MAGENTA         "\x1B[2;35m"
+#define RTT_CTRL_TEXT_CYAN            "\x1B[2;36m"
+#define RTT_CTRL_TEXT_WHITE           "\x1B[2;37m"
+
+#define RTT_CTRL_TEXT_BRIGHT_BLACK    "\x1B[1;30m"
+#define RTT_CTRL_TEXT_BRIGHT_RED      "\x1B[1;31m"
+#define RTT_CTRL_TEXT_BRIGHT_GREEN    "\x1B[1;32m"
+#define RTT_CTRL_TEXT_BRIGHT_YELLOW   "\x1B[1;33m"
+#define RTT_CTRL_TEXT_BRIGHT_BLUE     "\x1B[1;34m"
+#define RTT_CTRL_TEXT_BRIGHT_MAGENTA  "\x1B[1;35m"
+#define RTT_CTRL_TEXT_BRIGHT_CYAN     "\x1B[1;36m"
+#define RTT_CTRL_TEXT_BRIGHT_WHITE    "\x1B[1;37m"
+
+#define RTT_CTRL_BG_BLACK             "\x1B[24;40m"
+#define RTT_CTRL_BG_RED               "\x1B[24;41m"
+#define RTT_CTRL_BG_GREEN             "\x1B[24;42m"
+#define RTT_CTRL_BG_YELLOW            "\x1B[24;43m"
+#define RTT_CTRL_BG_BLUE              "\x1B[24;44m"
+#define RTT_CTRL_BG_MAGENTA           "\x1B[24;45m"
+#define RTT_CTRL_BG_CYAN              "\x1B[24;46m"
+#define RTT_CTRL_BG_WHITE             "\x1B[24;47m"
+
+#define RTT_CTRL_BG_BRIGHT_BLACK      "\x1B[4;40m"
+#define RTT_CTRL_BG_BRIGHT_RED        "\x1B[4;41m"
+#define RTT_CTRL_BG_BRIGHT_GREEN      "\x1B[4;42m"
+#define RTT_CTRL_BG_BRIGHT_YELLOW     "\x1B[4;43m"
+#define RTT_CTRL_BG_BRIGHT_BLUE       "\x1B[4;44m"
+#define RTT_CTRL_BG_BRIGHT_MAGENTA    "\x1B[4;45m"
+#define RTT_CTRL_BG_BRIGHT_CYAN       "\x1B[4;46m"
+#define RTT_CTRL_BG_BRIGHT_WHITE      "\x1B[4;47m"
+
+
+#endif
+
+/*************************** End of file ****************************/

+ 428 - 0
code/debug/SEGGER/SEGGER_RTT_Conf.h

@@ -0,0 +1,428 @@
+/*********************************************************************
+*                    SEGGER Microcontroller GmbH                     *
+*                        The Embedded Experts                        *
+**********************************************************************
+*                                                                    *
+*            (c) 1995 - 2021 SEGGER Microcontroller GmbH             *
+*                                                                    *
+*       www.segger.com     Support: support@segger.com               *
+*                                                                    *
+**********************************************************************
+*                                                                    *
+*       SEGGER SystemView * Real-time application analysis           *
+*                                                                    *
+**********************************************************************
+*                                                                    *
+* All rights reserved.                                               *
+*                                                                    *
+* SEGGER strongly recommends to not make any changes                 *
+* to or modify the source code of this software in order to stay     *
+* compatible with the SystemView and RTT protocol, and J-Link.       *
+*                                                                    *
+* Redistribution and use in source and binary forms, with or         *
+* without modification, are permitted provided that the following    *
+* condition is met:                                                  *
+*                                                                    *
+* o Redistributions of source code must retain the above copyright   *
+*   notice, this condition and the following disclaimer.             *
+*                                                                    *
+* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND             *
+* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,        *
+* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF           *
+* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE           *
+* DISCLAIMED. IN NO EVENT SHALL SEGGER Microcontroller BE LIABLE FOR *
+* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR           *
+* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT  *
+* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;    *
+* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF      *
+* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT          *
+* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE  *
+* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH   *
+* DAMAGE.                                                            *
+*                                                                    *
+**********************************************************************
+*                                                                    *
+*       SystemView version: 3.32                                    *
+*                                                                    *
+**********************************************************************
+---------------------------END-OF-HEADER------------------------------
+File    : SEGGER_RTT_Conf.h
+Purpose : Implementation of SEGGER real-time transfer (RTT) which
+          allows real-time communication on targets which support
+          debugger memory accesses while the CPU is running.
+Revision: $Rev: 24316 $
+
+*/
+
+#ifndef SEGGER_RTT_CONF_H
+#define SEGGER_RTT_CONF_H
+
+#ifdef __IAR_SYSTEMS_ICC__
+  #include <intrinsics.h>
+#endif
+
+/*********************************************************************
+*
+*       Defines, configurable
+*
+**********************************************************************
+*/
+
+//
+// Take in and set to correct values for Cortex-A systems with CPU cache
+//
+//#define SEGGER_RTT_CPU_CACHE_LINE_SIZE            (32)          // Largest cache line size (in bytes) in the current system
+//#define SEGGER_RTT_UNCACHED_OFF                   (0xFB000000)  // Address alias where RTT CB and buffers can be accessed uncached
+//
+// Most common case:
+// Up-channel 0: RTT
+// Up-channel 1: SystemView
+//
+#ifndef   SEGGER_RTT_MAX_NUM_UP_BUFFERS
+  #define SEGGER_RTT_MAX_NUM_UP_BUFFERS             (3)     // Max. number of up-buffers (T->H) available on this target    (Default: 3)
+#endif
+//
+// Most common case:
+// Down-channel 0: RTT
+// Down-channel 1: SystemView
+//
+#ifndef   SEGGER_RTT_MAX_NUM_DOWN_BUFFERS
+  #define SEGGER_RTT_MAX_NUM_DOWN_BUFFERS           (3)     // Max. number of down-buffers (H->T) available on this target  (Default: 3)
+#endif
+
+#ifndef   BUFFER_SIZE_UP
+  #define BUFFER_SIZE_UP                            (1024)  // Size of the buffer for terminal output of target, up to host (Default: 1k)
+#endif
+
+#ifndef   BUFFER_SIZE_DOWN
+  #define BUFFER_SIZE_DOWN                          (16)    // Size of the buffer for terminal input to target from host (Usually keyboard input) (Default: 16)
+#endif
+
+#ifndef   SEGGER_RTT_PRINTF_BUFFER_SIZE
+  #define SEGGER_RTT_PRINTF_BUFFER_SIZE             (64u)    // Size of buffer for RTT printf to bulk-send chars via RTT     (Default: 64)
+#endif
+
+#ifndef   SEGGER_RTT_MODE_DEFAULT
+  #define SEGGER_RTT_MODE_DEFAULT                   SEGGER_RTT_MODE_NO_BLOCK_SKIP // Mode for pre-initialized terminal channel (buffer 0)
+#endif
+
+/*********************************************************************
+*
+*       RTT memcpy configuration
+*
+*       memcpy() is good for large amounts of data,
+*       but the overhead is big for small amounts, which are usually stored via RTT.
+*       With SEGGER_RTT_MEMCPY_USE_BYTELOOP a simple byte loop can be used instead.
+*
+*       SEGGER_RTT_MEMCPY() can be used to replace standard memcpy() in RTT functions.
+*       This is may be required with memory access restrictions,
+*       such as on Cortex-A devices with MMU.
+*/
+#ifndef   SEGGER_RTT_MEMCPY_USE_BYTELOOP
+  #define SEGGER_RTT_MEMCPY_USE_BYTELOOP              0 // 0: Use memcpy/SEGGER_RTT_MEMCPY, 1: Use a simple byte-loop
+#endif
+//
+// Example definition of SEGGER_RTT_MEMCPY to external memcpy with GCC toolchains and Cortex-A targets
+//
+//#if ((defined __SES_ARM) || (defined __CROSSWORKS_ARM) || (defined __GNUC__)) && (defined (__ARM_ARCH_7A__))
+//  #define SEGGER_RTT_MEMCPY(pDest, pSrc, NumBytes)      SEGGER_memcpy((pDest), (pSrc), (NumBytes))
+//#endif
+
+//
+// Target is not allowed to perform other RTT operations while string still has not been stored completely.
+// Otherwise we would probably end up with a mixed string in the buffer.
+// If using  RTT from within interrupts, multiple tasks or multi processors, define the SEGGER_RTT_LOCK() and SEGGER_RTT_UNLOCK() function here.
+//
+// SEGGER_RTT_MAX_INTERRUPT_PRIORITY can be used in the sample lock routines on Cortex-M3/4.
+// Make sure to mask all interrupts which can send RTT data, i.e. generate SystemView events, or cause task switches.
+// When high-priority interrupts must not be masked while sending RTT data, SEGGER_RTT_MAX_INTERRUPT_PRIORITY needs to be adjusted accordingly.
+// (Higher priority = lower priority number)
+// Default value for embOS: 128u
+// Default configuration in FreeRTOS: configMAX_SYSCALL_INTERRUPT_PRIORITY: ( configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY << (8 - configPRIO_BITS) )
+// In case of doubt mask all interrupts: 1 << (8 - BASEPRI_PRIO_BITS) i.e. 1 << 5 when 3 bits are implemented in NVIC
+// or define SEGGER_RTT_LOCK() to completely disable interrupts.
+//
+#ifndef   SEGGER_RTT_MAX_INTERRUPT_PRIORITY
+  #define SEGGER_RTT_MAX_INTERRUPT_PRIORITY         (0x20)   // Interrupt priority to lock on SEGGER_RTT_LOCK on Cortex-M3/4 (Default: 0x20)
+#endif
+
+/*********************************************************************
+*
+*       RTT lock configuration for SEGGER Embedded Studio,
+*       Rowley CrossStudio and GCC
+*/
+#if ((defined(__SES_ARM) || defined(__SES_RISCV) || defined(__CROSSWORKS_ARM) || defined(__GNUC__) || defined(__clang__)) && !defined (__CC_ARM) && !defined(WIN32))
+  #if (defined(__ARM_ARCH_6M__) || defined(__ARM_ARCH_8M_BASE__))
+    #define SEGGER_RTT_LOCK()   {                                                                   \
+                                    unsigned int _SEGGER_RTT__LockState;                                         \
+                                  __asm volatile ("mrs   %0, primask  \n\t"                         \
+                                                  "movs  r1, #1       \n\t"                         \
+                                                  "msr   primask, r1  \n\t"                         \
+                                                  : "=r" (_SEGGER_RTT__LockState)                                \
+                                                  :                                                 \
+                                                  : "r1", "cc"                                      \
+                                                  );
+
+    #define SEGGER_RTT_UNLOCK()   __asm volatile ("msr   primask, %0  \n\t"                         \
+                                                  :                                                 \
+                                                  : "r" (_SEGGER_RTT__LockState)                                 \
+                                                  :                                                 \
+                                                  );                                                \
+                                }
+  #elif (defined(__ARM_ARCH_7M__) || defined(__ARM_ARCH_7EM__) || defined(__ARM_ARCH_8M_MAIN__))
+    #ifndef   SEGGER_RTT_MAX_INTERRUPT_PRIORITY
+      #define SEGGER_RTT_MAX_INTERRUPT_PRIORITY   (0x20)
+    #endif
+    #define SEGGER_RTT_LOCK()   {                                                                   \
+                                    unsigned int _SEGGER_RTT__LockState;                                         \
+                                  __asm volatile ("mrs   %0, basepri  \n\t"                         \
+                                                  "mov   r1, %1       \n\t"                         \
+                                                  "msr   basepri, r1  \n\t"                         \
+                                                  : "=r" (_SEGGER_RTT__LockState)                                \
+                                                  : "i"(SEGGER_RTT_MAX_INTERRUPT_PRIORITY)          \
+                                                  : "r1", "cc"                                      \
+                                                  );
+
+    #define SEGGER_RTT_UNLOCK()   __asm volatile ("msr   basepri, %0  \n\t"                         \
+                                                  :                                                 \
+                                                  : "r" (_SEGGER_RTT__LockState)                                 \
+                                                  :                                                 \
+                                                  );                                                \
+                                }
+
+  #elif (defined(__ARM_ARCH_7A__) || defined(__ARM_ARCH_7R__))
+    #define SEGGER_RTT_LOCK() {                                                \
+                                 unsigned int _SEGGER_RTT__LockState;                       \
+                                 __asm volatile ("mrs r1, CPSR \n\t"           \
+                                                 "mov %0, r1 \n\t"             \
+                                                 "orr r1, r1, #0xC0 \n\t"      \
+                                                 "msr CPSR_c, r1 \n\t"         \
+                                                 : "=r" (_SEGGER_RTT__LockState)            \
+                                                 :                             \
+                                                 : "r1", "cc"                  \
+                                                 );
+
+    #define SEGGER_RTT_UNLOCK() __asm volatile ("mov r0, %0 \n\t"              \
+                                                "mrs r1, CPSR \n\t"            \
+                                                "bic r1, r1, #0xC0 \n\t"       \
+                                                "and r0, r0, #0xC0 \n\t"       \
+                                                "orr r1, r1, r0 \n\t"          \
+                                                "msr CPSR_c, r1 \n\t"          \
+                                                :                              \
+                                                : "r" (_SEGGER_RTT__LockState)              \
+                                                : "r0", "r1", "cc"             \
+                                                );                             \
+                            }
+  #elif defined(__riscv) || defined(__riscv_xlen)
+    #define SEGGER_RTT_LOCK()  {                                               \
+                                 unsigned int _SEGGER_RTT__LockState;                       \
+                                 __asm volatile ("csrr  %0, mstatus  \n\t"     \
+                                                 "csrci mstatus, 8   \n\t"     \
+                                                 "andi  %0, %0,  8   \n\t"     \
+                                                 : "=r" (_SEGGER_RTT__LockState)            \
+                                                 :                             \
+                                                 :                             \
+                                                );
+
+  #define SEGGER_RTT_UNLOCK()    __asm volatile ("csrr  a1, mstatus  \n\t"     \
+                                                 "or    %0, %0, a1   \n\t"     \
+                                                 "csrs  mstatus, %0  \n\t"     \
+                                                 :                             \
+                                                 : "r"  (_SEGGER_RTT__LockState)            \
+                                                 : "a1"                        \
+                                                );                             \
+                               }
+  #else
+    #define SEGGER_RTT_LOCK()
+    #define SEGGER_RTT_UNLOCK()
+  #endif
+#endif
+
+/*********************************************************************
+*
+*       RTT lock configuration for IAR EWARM
+*/
+#ifdef __ICCARM__
+  #if (defined (__ARM6M__)          && (__CORE__ == __ARM6M__))             ||                      \
+      (defined (__ARM8M_BASELINE__) && (__CORE__ == __ARM8M_BASELINE__))
+    #define SEGGER_RTT_LOCK()   {                                                                   \
+                                  unsigned int _SEGGER_RTT__LockState;                                           \
+                                  _SEGGER_RTT__LockState = __get_PRIMASK();                                      \
+                                  __set_PRIMASK(1);
+
+    #define SEGGER_RTT_UNLOCK()   __set_PRIMASK(_SEGGER_RTT__LockState);                                         \
+                                }
+  #elif (defined (__ARM7EM__)         && (__CORE__ == __ARM7EM__))          ||                      \
+        (defined (__ARM7M__)          && (__CORE__ == __ARM7M__))           ||                      \
+        (defined (__ARM8M_MAINLINE__) && (__CORE__ == __ARM8M_MAINLINE__))  ||                      \
+        (defined (__ARM8M_MAINLINE__) && (__CORE__ == __ARM8M_MAINLINE__))
+    #ifndef   SEGGER_RTT_MAX_INTERRUPT_PRIORITY
+      #define SEGGER_RTT_MAX_INTERRUPT_PRIORITY   (0x20)
+    #endif
+    #define SEGGER_RTT_LOCK()   {                                                                   \
+                                  unsigned int _SEGGER_RTT__LockState;                                           \
+                                  _SEGGER_RTT__LockState = __get_BASEPRI();                                      \
+                                  __set_BASEPRI(SEGGER_RTT_MAX_INTERRUPT_PRIORITY);
+
+    #define SEGGER_RTT_UNLOCK()   __set_BASEPRI(_SEGGER_RTT__LockState);                                         \
+                                }
+  #elif (defined (__ARM7A__) && (__CORE__ == __ARM7A__))                    ||                      \
+        (defined (__ARM7R__) && (__CORE__ == __ARM7R__))
+    #define SEGGER_RTT_LOCK() {                                                                     \
+                                 unsigned int _SEGGER_RTT__LockState;                                            \
+                                 __asm volatile ("mrs r1, CPSR \n\t"                                \
+                                                 "mov %0, r1 \n\t"                                  \
+                                                 "orr r1, r1, #0xC0 \n\t"                           \
+                                                 "msr CPSR_c, r1 \n\t"                              \
+                                                 : "=r" (_SEGGER_RTT__LockState)                                 \
+                                                 :                                                  \
+                                                 : "r1", "cc"                                       \
+                                                 );
+
+    #define SEGGER_RTT_UNLOCK() __asm volatile ("mov r0, %0 \n\t"                                   \
+                                                "mrs r1, CPSR \n\t"                                 \
+                                                "bic r1, r1, #0xC0 \n\t"                            \
+                                                "and r0, r0, #0xC0 \n\t"                            \
+                                                "orr r1, r1, r0 \n\t"                               \
+                                                "msr CPSR_c, r1 \n\t"                               \
+                                                :                                                   \
+                                                : "r" (_SEGGER_RTT__LockState)                                   \
+                                                : "r0", "r1", "cc"                                  \
+                                                );                                                  \
+                            }
+  #endif
+#endif
+
+/*********************************************************************
+*
+*       RTT lock configuration for IAR RX
+*/
+#ifdef __ICCRX__
+  #define SEGGER_RTT_LOCK()   {                                                                     \
+                                unsigned long _SEGGER_RTT__LockState;                                            \
+                                _SEGGER_RTT__LockState = __get_interrupt_state();                                \
+                                __disable_interrupt();
+
+  #define SEGGER_RTT_UNLOCK()   __set_interrupt_state(_SEGGER_RTT__LockState);                                   \
+                              }
+#endif
+
+/*********************************************************************
+*
+*       RTT lock configuration for IAR RL78
+*/
+#ifdef __ICCRL78__
+  #define SEGGER_RTT_LOCK()   {                                                                     \
+                                __istate_t _SEGGER_RTT__LockState;                                               \
+                                _SEGGER_RTT__LockState = __get_interrupt_state();                                \
+                                __disable_interrupt();
+
+  #define SEGGER_RTT_UNLOCK()   __set_interrupt_state(_SEGGER_RTT__LockState);                                   \
+                              }
+#endif
+
+/*********************************************************************
+*
+*       RTT lock configuration for KEIL ARM
+*/
+#ifdef __CC_ARM
+  #if (defined __TARGET_ARCH_6S_M)
+    #define SEGGER_RTT_LOCK()   {                                                                   \
+                                  unsigned int _SEGGER_RTT__LockState;                                           \
+                                  register unsigned char _SEGGER_RTT__PRIMASK __asm( "primask");                 \
+                                  _SEGGER_RTT__LockState = _SEGGER_RTT__PRIMASK;                                              \
+                                  _SEGGER_RTT__PRIMASK = 1u;                                                     \
+                                  __schedule_barrier();
+
+    #define SEGGER_RTT_UNLOCK()   _SEGGER_RTT__PRIMASK = _SEGGER_RTT__LockState;                                              \
+                                  __schedule_barrier();                                             \
+                                }
+  #elif (defined(__TARGET_ARCH_7_M) || defined(__TARGET_ARCH_7E_M))
+    #ifndef   SEGGER_RTT_MAX_INTERRUPT_PRIORITY
+      #define SEGGER_RTT_MAX_INTERRUPT_PRIORITY   (0x20)
+    #endif
+    #define SEGGER_RTT_LOCK()   {                                                                   \
+                                  unsigned int _SEGGER_RTT__LockState;                                           \
+                                  register unsigned char BASEPRI __asm( "basepri");                 \
+                                  _SEGGER_RTT__LockState = BASEPRI;                                              \
+                                  BASEPRI = SEGGER_RTT_MAX_INTERRUPT_PRIORITY;                      \
+                                  __schedule_barrier();
+
+    #define SEGGER_RTT_UNLOCK()   BASEPRI = _SEGGER_RTT__LockState;                                              \
+                                  __schedule_barrier();                                             \
+                                }
+  #endif
+#endif
+
+/*********************************************************************
+*
+*       RTT lock configuration for TI ARM
+*/
+#ifdef __TI_ARM__
+  #if defined (__TI_ARM_V6M0__)
+    #define SEGGER_RTT_LOCK()   {                                                                   \
+                                  unsigned int _SEGGER_RTT__LockState;                                           \
+                                  _SEGGER_RTT__LockState = __get_PRIMASK();                                      \
+                                  __set_PRIMASK(1);
+
+    #define SEGGER_RTT_UNLOCK()   __set_PRIMASK(_SEGGER_RTT__LockState);                                         \
+                                }
+  #elif (defined (__TI_ARM_V7M3__) || defined (__TI_ARM_V7M4__))
+    #ifndef   SEGGER_RTT_MAX_INTERRUPT_PRIORITY
+      #define SEGGER_RTT_MAX_INTERRUPT_PRIORITY   (0x20)
+    #endif
+    #define SEGGER_RTT_LOCK()   {                                                                   \
+                                  unsigned int _SEGGER_RTT__LockState;                                           \
+                                  _SEGGER_RTT__LockState = _set_interrupt_priority(SEGGER_RTT_MAX_INTERRUPT_PRIORITY);
+
+    #define SEGGER_RTT_UNLOCK()   _set_interrupt_priority(_SEGGER_RTT__LockState);                               \
+                                }
+  #endif
+#endif
+
+/*********************************************************************
+*
+*       RTT lock configuration for CCRX
+*/
+#ifdef __RX
+  #include <machine.h>
+  #define SEGGER_RTT_LOCK()   {                                                                     \
+                                unsigned long _SEGGER_RTT__LockState;                                            \
+                                _SEGGER_RTT__LockState = get_psw() & 0x010000;                                   \
+                                clrpsw_i();
+
+  #define SEGGER_RTT_UNLOCK()   set_psw(get_psw() | _SEGGER_RTT__LockState);                                     \
+                              }
+#endif
+
+/*********************************************************************
+*
+*       RTT lock configuration for embOS Simulation on Windows
+*       (Can also be used for generic RTT locking with embOS)
+*/
+#if defined(WIN32) || defined(SEGGER_RTT_LOCK_EMBOS)
+
+void OS_SIM_EnterCriticalSection(void);
+void OS_SIM_LeaveCriticalSection(void);
+
+#define SEGGER_RTT_LOCK()       {                                                                   \
+                                  OS_SIM_EnterCriticalSection();
+
+#define SEGGER_RTT_UNLOCK()       OS_SIM_LeaveCriticalSection();                                    \
+                                }
+#endif
+
+/*********************************************************************
+*
+*       RTT lock configuration fallback
+*/
+#ifndef   SEGGER_RTT_LOCK
+  #define SEGGER_RTT_LOCK()                // Lock RTT (nestable)   (i.e. disable interrupts)
+#endif
+
+#ifndef   SEGGER_RTT_UNLOCK
+  #define SEGGER_RTT_UNLOCK()              // Unlock RTT (nestable) (i.e. enable previous interrupt lock state)
+#endif
+
+#endif
+/*************************** End of file ****************************/

+ 124 - 0
code/debug/SEGGER/SEGGER_RTT_Syscalls_GCC.c

@@ -0,0 +1,124 @@
+/*********************************************************************
+*                    SEGGER Microcontroller GmbH                     *
+*                        The Embedded Experts                        *
+**********************************************************************
+*                                                                    *
+*            (c) 1995 - 2021 SEGGER Microcontroller GmbH             *
+*                                                                    *
+*       www.segger.com     Support: support@segger.com               *
+*                                                                    *
+**********************************************************************
+*                                                                    *
+*       SEGGER SystemView * Real-time application analysis           *
+*                                                                    *
+**********************************************************************
+*                                                                    *
+* All rights reserved.                                               *
+*                                                                    *
+* SEGGER strongly recommends to not make any changes                 *
+* to or modify the source code of this software in order to stay     *
+* compatible with the SystemView and RTT protocol, and J-Link.       *
+*                                                                    *
+* Redistribution and use in source and binary forms, with or         *
+* without modification, are permitted provided that the following    *
+* condition is met:                                                  *
+*                                                                    *
+* o Redistributions of source code must retain the above copyright   *
+*   notice, this condition and the following disclaimer.             *
+*                                                                    *
+* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND             *
+* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,        *
+* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF           *
+* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE           *
+* DISCLAIMED. IN NO EVENT SHALL SEGGER Microcontroller BE LIABLE FOR *
+* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR           *
+* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT  *
+* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;    *
+* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF      *
+* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT          *
+* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE  *
+* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH   *
+* DAMAGE.                                                            *
+*                                                                    *
+**********************************************************************
+*                                                                    *
+*       SystemView version: 3.32                                    *
+*                                                                    *
+**********************************************************************
+---------------------------END-OF-HEADER------------------------------
+File    : SEGGER_RTT_Syscalls_GCC.c
+Purpose : Low-level functions for using printf() via RTT in GCC.
+          To use RTT for printf output, include this file in your 
+          application.
+Revision: $Rev: 24316 $
+----------------------------------------------------------------------
+*/
+#if (defined __GNUC__) && !(defined __SES_ARM) && !(defined __CROSSWORKS_ARM) && !(defined __ARMCC_VERSION) && !(defined __CC_ARM)
+
+#include <reent.h>  // required for _write_r
+#include "SEGGER_RTT.h"
+
+
+/*********************************************************************
+*
+*       Types
+*
+**********************************************************************
+*/
+//
+// If necessary define the _reent struct
+// to match the one passed by the used standard library.
+//
+struct _reent;
+
+/*********************************************************************
+*
+*       Function prototypes
+*
+**********************************************************************
+*/
+_ssize_t _write  (int file, const void *ptr, size_t len);
+_ssize_t _write_r(struct _reent *r, int file, const void *ptr, size_t len);
+
+/*********************************************************************
+*
+*       Global functions
+*
+**********************************************************************
+*/
+
+/*********************************************************************
+*
+*       _write()
+*
+* Function description
+*   Low-level write function.
+*   libc subroutines will use this system routine for output to all files,
+*   including stdout.
+*   Write data via RTT.
+*/
+_ssize_t _write(int file, const void *ptr, size_t len) {
+  (void) file;  /* Not used, avoid warning */
+  SEGGER_RTT_Write(0, ptr, len);
+  return len;
+}
+
+/*********************************************************************
+*
+*       _write_r()
+*
+* Function description
+*   Low-level reentrant write function.
+*   libc subroutines will use this system routine for output to all files,
+*   including stdout.
+*   Write data via RTT.
+*/
+_ssize_t _write_r(struct _reent *r, int file, const void *ptr, size_t len) {
+  (void) file;  /* Not used, avoid warning */
+  (void) r;     /* Not used, avoid warning */
+  SEGGER_RTT_Write(0, ptr, len);
+  return len;
+}
+
+#endif
+/****** End Of File *************************************************/

+ 119 - 0
code/debug/SEGGER/SEGGER_RTT_Syscalls_IAR.c

@@ -0,0 +1,119 @@
+/*********************************************************************
+*                    SEGGER Microcontroller GmbH                     *
+*                        The Embedded Experts                        *
+**********************************************************************
+*                                                                    *
+*            (c) 1995 - 2021 SEGGER Microcontroller GmbH             *
+*                                                                    *
+*       www.segger.com     Support: support@segger.com               *
+*                                                                    *
+**********************************************************************
+*                                                                    *
+*       SEGGER SystemView * Real-time application analysis           *
+*                                                                    *
+**********************************************************************
+*                                                                    *
+* All rights reserved.                                               *
+*                                                                    *
+* SEGGER strongly recommends to not make any changes                 *
+* to or modify the source code of this software in order to stay     *
+* compatible with the SystemView and RTT protocol, and J-Link.       *
+*                                                                    *
+* Redistribution and use in source and binary forms, with or         *
+* without modification, are permitted provided that the following    *
+* condition is met:                                                  *
+*                                                                    *
+* o Redistributions of source code must retain the above copyright   *
+*   notice, this condition and the following disclaimer.             *
+*                                                                    *
+* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND             *
+* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,        *
+* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF           *
+* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE           *
+* DISCLAIMED. IN NO EVENT SHALL SEGGER Microcontroller BE LIABLE FOR *
+* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR           *
+* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT  *
+* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;    *
+* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF      *
+* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT          *
+* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE  *
+* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH   *
+* DAMAGE.                                                            *
+*                                                                    *
+**********************************************************************
+*                                                                    *
+*       SystemView version: 3.32                                    *
+*                                                                    *
+**********************************************************************
+---------------------------END-OF-HEADER------------------------------
+File    : SEGGER_RTT_Syscalls_IAR.c
+Purpose : Low-level functions for using printf() via RTT in IAR.
+          To use RTT for printf output, include this file in your
+          application and set the Library Configuration to Normal.
+Revision: $Rev: 24316 $
+----------------------------------------------------------------------
+*/
+#ifdef __IAR_SYSTEMS_ICC__
+
+//
+// Since IAR EWARM V8 and EWRX V4, yfuns.h is considered as deprecated and LowLevelIOInterface.h
+// shall be used instead. To not break any compatibility with older compiler versions, we have a
+// version check in here.
+//
+#if ((defined __ICCARM__) && (__VER__ >= 8000000)) || ((defined __ICCRX__)  && (__VER__ >= 400))
+  #include <LowLevelIOInterface.h>
+#else
+  #include <yfuns.h>
+#endif
+
+#include "SEGGER_RTT.h"
+#pragma module_name = "?__write"
+
+/*********************************************************************
+*
+*       Function prototypes
+*
+**********************************************************************
+*/
+size_t __write(int handle, const unsigned char * buffer, size_t size);
+
+/*********************************************************************
+*
+*       Global functions
+*
+**********************************************************************
+*/
+/*********************************************************************
+*
+*       __write()
+*
+* Function description
+*   Low-level write function.
+*   Standard library subroutines will use this system routine
+*   for output to all files, including stdout.
+*   Write data via RTT.
+*/
+size_t __write(int handle, const unsigned char * buffer, size_t size) {
+  (void) handle;  /* Not used, avoid warning */
+  SEGGER_RTT_Write(0, (const char*)buffer, size);
+  return size;
+}
+
+/*********************************************************************
+*
+*       __write_buffered()
+*
+* Function description
+*   Low-level write function.
+*   Standard library subroutines will use this system routine
+*   for output to all files, including stdout.
+*   Write data via RTT.
+*/
+size_t __write_buffered(int handle, const unsigned char * buffer, size_t size) {
+  (void) handle;  /* Not used, avoid warning */
+  SEGGER_RTT_Write(0, (const char*)buffer, size);
+  return size;
+}
+
+#endif
+/****** End Of File *************************************************/

+ 393 - 0
code/debug/SEGGER/SEGGER_RTT_Syscalls_KEIL.c

@@ -0,0 +1,393 @@
+/*********************************************************************
+*                    SEGGER Microcontroller GmbH                     *
+*                        The Embedded Experts                        *
+**********************************************************************
+*                                                                    *
+*            (c) 1995 - 2021 SEGGER Microcontroller GmbH             *
+*                                                                    *
+*       www.segger.com     Support: support@segger.com               *
+*                                                                    *
+**********************************************************************
+*                                                                    *
+*       SEGGER SystemView * Real-time application analysis           *
+*                                                                    *
+**********************************************************************
+*                                                                    *
+* All rights reserved.                                               *
+*                                                                    *
+* SEGGER strongly recommends to not make any changes                 *
+* to or modify the source code of this software in order to stay     *
+* compatible with the SystemView and RTT protocol, and J-Link.       *
+*                                                                    *
+* Redistribution and use in source and binary forms, with or         *
+* without modification, are permitted provided that the following    *
+* condition is met:                                                  *
+*                                                                    *
+* o Redistributions of source code must retain the above copyright   *
+*   notice, this condition and the following disclaimer.             *
+*                                                                    *
+* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND             *
+* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,        *
+* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF           *
+* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE           *
+* DISCLAIMED. IN NO EVENT SHALL SEGGER Microcontroller BE LIABLE FOR *
+* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR           *
+* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT  *
+* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;    *
+* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF      *
+* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT          *
+* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE  *
+* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH   *
+* DAMAGE.                                                            *
+*                                                                    *
+**********************************************************************
+*                                                                    *
+*       SystemView version: 3.32                                    *
+*                                                                    *
+**********************************************************************
+---------------------------END-OF-HEADER------------------------------
+File    : RTT_Syscalls_KEIL.c
+Purpose : Retargeting module for KEIL MDK-CM3.
+          Low-level functions for using printf() via RTT
+Revision: $Rev: 24316 $
+Notes   : (1) https://wiki.segger.com/Keil_MDK-ARM#RTT_in_uVision
+----------------------------------------------------------------------
+*/
+#if (defined __CC_ARM) || (defined __ARMCC_VERSION)
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <rt_sys.h>
+#include <rt_misc.h>
+
+#include "SEGGER_RTT.h"
+/*********************************************************************
+*
+*       #pragmas
+*
+**********************************************************************
+*/
+#if __ARMCC_VERSION < 6000000
+#pragma import(__use_no_semihosting)
+#endif
+
+#ifdef _MICROLIB
+  #pragma import(__use_full_stdio)
+#endif
+
+/*********************************************************************
+*
+*       Defines non-configurable
+*
+**********************************************************************
+*/
+
+/* Standard IO device handles - arbitrary, but any real file system handles must be
+   less than 0x8000. */
+#define STDIN             0x8001    // Standard Input Stream
+#define STDOUT            0x8002    // Standard Output Stream
+#define STDERR            0x8003    // Standard Error Stream
+
+/*********************************************************************
+*
+*       Public const
+*
+**********************************************************************
+*/
+#if __ARMCC_VERSION < 5000000
+//const char __stdin_name[]  = "STDIN";
+const char __stdout_name[] = "STDOUT";
+const char __stderr_name[] = "STDERR";
+#endif
+
+/*********************************************************************
+*
+*       Public code
+*
+**********************************************************************
+*/
+
+/*********************************************************************
+*
+*       _ttywrch
+*
+*  Function description:
+*    Outputs a character to the console
+*
+*  Parameters:
+*    c    - character to output
+*  
+*/
+void _ttywrch(int c) {
+  fputc(c, stdout); // stdout
+  fflush(stdout);
+}
+
+/*********************************************************************
+*
+*       _sys_open
+*
+*  Function description:
+*    Opens the device/file in order to do read/write operations
+*
+*  Parameters:
+*    sName        - sName of the device/file to open
+*    OpenMode    - This parameter is currently ignored
+*  
+*  Return value:
+*    != 0     - Handle to the object to open, otherwise 
+*    == 0     -"device" is not handled by this module
+*
+*/
+FILEHANDLE _sys_open(const char * sName, int OpenMode) {
+  (void)OpenMode;
+  // Register standard Input Output devices.
+  if (strcmp(sName, __stdout_name) == 0) {
+    return (STDOUT);
+  } else if (strcmp(sName, __stderr_name) == 0) {
+    return (STDERR);
+  } else
+  return (0);  // Not implemented
+}
+
+/*********************************************************************
+*
+*       _sys_close
+*
+*  Function description:
+*    Closes the handle to the open device/file
+*
+*  Parameters:
+*    hFile    - Handle to a file opened via _sys_open
+*  
+*  Return value:
+*    0     - device/file closed
+*
+*/
+int _sys_close(FILEHANDLE hFile) {
+  (void)hFile;
+  return 0;  // Not implemented
+}
+
+/*********************************************************************
+*
+*       _sys_write
+*
+*  Function description:
+*    Writes the data to an open handle.
+*    Currently this function only outputs data to the console
+*
+*  Parameters:
+*    hFile    - Handle to a file opened via _sys_open
+*    pBuffer  - Pointer to the data that shall be written
+*    NumBytes      - Number of bytes to write
+*    Mode     - The Mode that shall be used
+*  
+*  Return value:
+*    Number of bytes *not* written to the file/device
+*
+*/
+int _sys_write(FILEHANDLE hFile, const unsigned char * pBuffer, unsigned NumBytes, int Mode) {
+  int r = 0;
+
+  (void)Mode;
+  if (hFile == STDOUT) {
+    SEGGER_RTT_Write(0, (const char*)pBuffer, NumBytes);
+		return 0;
+  }
+  return r;
+}
+
+/*********************************************************************
+*
+*       _sys_read
+*
+*  Function description:
+*    Reads data from an open handle.
+*    Currently this modules does nothing.
+*
+*  Parameters:
+*    hFile    - Handle to a file opened via _sys_open
+*    pBuffer  - Pointer to buffer to store the read data
+*    NumBytes      - Number of bytes to read
+*    Mode     - The Mode that shall be used
+*  
+*  Return value:
+*    Number of bytes read from the file/device
+*
+*/
+int _sys_read(FILEHANDLE hFile, unsigned char * pBuffer, unsigned NumBytes, int Mode) {
+  (void)hFile;
+  (void)pBuffer;
+  (void)NumBytes;
+  (void)Mode;
+  return (0);  // Not implemented
+}
+
+/*********************************************************************
+*
+*       _sys_istty
+*
+*  Function description:
+*    This function shall return whether the opened file 
+*    is a console device or not.
+*
+*  Parameters:
+*    hFile    - Handle to a file opened via _sys_open
+*  
+*  Return value:
+*    1       - Device is     a console
+*    0       - Device is not a console
+*
+*/
+int _sys_istty(FILEHANDLE hFile) {
+  if (hFile > 0x8000) {
+    return (1);
+  }
+  return (0);  // Not implemented
+}
+
+/*********************************************************************
+*
+*       _sys_seek
+*
+*  Function description:
+*    Seeks via the file to a specific position
+*
+*  Parameters:
+*    hFile  - Handle to a file opened via _sys_open
+*    Pos    - 
+*  
+*  Return value:
+*    int       - 
+*
+*/
+int _sys_seek(FILEHANDLE hFile, long Pos) {
+  (void)hFile;
+  (void)Pos;
+  return (0);  // Not implemented
+}
+
+/*********************************************************************
+*
+*       _sys_ensure
+*
+*  Function description:
+*    
+*
+*  Parameters:
+*    hFile    - Handle to a file opened via _sys_open
+*  
+*  Return value:
+*    int       - 
+*
+*/
+int _sys_ensure(FILEHANDLE hFile) {
+  (void)hFile;
+  return (-1);  // Not implemented
+}
+
+/*********************************************************************
+*
+*       _sys_flen
+*
+*  Function description:
+*    Returns the length of the opened file handle
+*
+*  Parameters:
+*    hFile    - Handle to a file opened via _sys_open
+*  
+*  Return value:
+*    Length of the file
+*
+*/
+long _sys_flen(FILEHANDLE hFile) {
+  (void)hFile;
+  return (0);  // Not implemented
+}
+
+/*********************************************************************
+*
+*       _sys_tmpnam
+*
+*  Function description:
+*    This function converts the file number fileno for a temporary 
+*    file to a unique filename, for example, tmp0001.
+*
+*  Parameters:
+*    pBuffer    - Pointer to a buffer to store the name
+*    FileNum    - file number to convert
+*    MaxLen     - Size of the buffer
+*  
+*  Return value:
+*     1 - Error
+*     0 - Success  
+*
+*/
+int _sys_tmpnam(char * pBuffer, int FileNum, unsigned MaxLen) {
+  (void)pBuffer;
+  (void)FileNum;
+  (void)MaxLen;
+  return (1);  // Not implemented
+}
+
+/*********************************************************************
+*
+*       _sys_command_string
+*
+*  Function description:
+*    This function shall execute a system command.
+*
+*  Parameters:
+*    cmd    - Pointer to the command string
+*    len    - Length of the string
+*  
+*  Return value:
+*    == NULL - Command was not successfully executed
+*    == sCmd - Command was passed successfully
+*
+*/
+char * _sys_command_string(char * cmd, int len) {
+  (void)len;
+  return cmd;  // Not implemented
+}
+
+/*********************************************************************
+*
+*       _sys_exit
+*
+*  Function description:
+*    This function is called when the application returns from main
+*
+*  Parameters:
+*    ReturnCode    - Return code from the main function
+*  
+*
+*/
+void _sys_exit(int ReturnCode) {
+  (void)ReturnCode;
+  while (1);  // Not implemented
+}
+
+#if __ARMCC_VERSION >= 5000000
+/*********************************************************************
+*
+*       stdout_putchar
+*
+*  Function description:
+*    Put a character to the stdout
+*
+*  Parameters:
+*    ch    - Character to output
+*  
+*
+*/
+int stdout_putchar(int ch) {
+  (void)ch;
+  return ch;  // Not implemented
+}
+#endif
+
+#endif
+/*************************** End of file ****************************/

+ 251 - 0
code/debug/SEGGER/SEGGER_RTT_Syscalls_SES.c

@@ -0,0 +1,251 @@
+/*********************************************************************
+*                    SEGGER Microcontroller GmbH                     *
+*                        The Embedded Experts                        *
+**********************************************************************
+*                                                                    *
+*            (c) 1995 - 2021 SEGGER Microcontroller GmbH             *
+*                                                                    *
+*       www.segger.com     Support: support@segger.com               *
+*                                                                    *
+**********************************************************************
+*                                                                    *
+*       SEGGER SystemView * Real-time application analysis           *
+*                                                                    *
+**********************************************************************
+*                                                                    *
+* All rights reserved.                                               *
+*                                                                    *
+* SEGGER strongly recommends to not make any changes                 *
+* to or modify the source code of this software in order to stay     *
+* compatible with the SystemView and RTT protocol, and J-Link.       *
+*                                                                    *
+* Redistribution and use in source and binary forms, with or         *
+* without modification, are permitted provided that the following    *
+* condition is met:                                                  *
+*                                                                    *
+* o Redistributions of source code must retain the above copyright   *
+*   notice, this condition and the following disclaimer.             *
+*                                                                    *
+* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND             *
+* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,        *
+* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF           *
+* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE           *
+* DISCLAIMED. IN NO EVENT SHALL SEGGER Microcontroller BE LIABLE FOR *
+* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR           *
+* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT  *
+* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;    *
+* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF      *
+* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT          *
+* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE  *
+* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH   *
+* DAMAGE.                                                            *
+*                                                                    *
+**********************************************************************
+*                                                                    *
+*       SystemView version: 3.32                                    *
+*                                                                    *
+**********************************************************************
+---------------------------END-OF-HEADER------------------------------
+File    : SEGGER_RTT_Syscalls_SES.c
+Purpose : Reimplementation of printf, puts and __getchar using RTT
+          in SEGGER Embedded Studio.
+          To use RTT for printf output, include this file in your
+          application.
+Revision: $Rev: 24316 $
+----------------------------------------------------------------------
+*/
+#if (defined __SES_ARM) || (defined __SES_RISCV) || (defined __CROSSWORKS_ARM)
+
+#include "SEGGER_RTT.h"
+#include <stdarg.h>
+#include <stdio.h>
+#include "limits.h"
+#include "__libc.h"
+#include "__vfprintf.h"
+
+/*********************************************************************
+*
+*       Defines, configurable
+*
+**********************************************************************
+*/
+//
+// Select string formatting implementation.
+//
+// RTT printf formatting
+//  - Configurable stack usage. (SEGGER_RTT_PRINTF_BUFFER_SIZE in SEGGER_RTT_Conf.h)
+//  - No maximum string length.
+//  - Limited conversion specifiers and flags. (See SEGGER_RTT_printf.c)
+// Standard library printf formatting
+//  - Configurable formatting capabilities.
+//  - Full conversion specifier and flag support.
+//  - Maximum string length has to be known or (slightly) slower character-wise output.
+//
+// #define PRINTF_USE_SEGGER_RTT_FORMATTING    0 // Use standard library formatting
+// #define PRINTF_USE_SEGGER_RTT_FORMATTING    1 // Use RTT formatting
+//
+#ifndef   PRINTF_USE_SEGGER_RTT_FORMATTING
+  #define PRINTF_USE_SEGGER_RTT_FORMATTING    0
+#endif
+//
+// If using standard library formatting,
+// select maximum output string buffer size or character-wise output.
+//
+// #define PRINTF_BUFFER_SIZE                  0 // Use character-wise output
+// #define PRINTF_BUFFER_SIZE                128 // Default maximum string length
+//
+#ifndef   PRINTF_BUFFER_SIZE
+  #define PRINTF_BUFFER_SIZE                128
+#endif
+
+#if PRINTF_USE_SEGGER_RTT_FORMATTING  // Use SEGGER RTT formatting implementation
+/*********************************************************************
+*
+*       Function prototypes
+*
+**********************************************************************
+*/
+int SEGGER_RTT_vprintf(unsigned BufferIndex, const char * sFormat, va_list * pParamList);
+
+/*********************************************************************
+*
+*       Global functions, printf
+*
+**********************************************************************
+*/
+/*********************************************************************
+*
+*       printf()
+*
+*  Function description
+*    print a formatted string using RTT and SEGGER RTT formatting.
+*/
+int printf(const char *fmt,...) {
+  int     n;
+  va_list args;
+
+  va_start (args, fmt);
+  n = SEGGER_RTT_vprintf(0, fmt, &args);
+  va_end(args);
+  return n;
+}
+
+#elif PRINTF_BUFFER_SIZE == 0 // Use standard library formatting with character-wise output
+
+/*********************************************************************
+*
+*       Static functions
+*
+**********************************************************************
+*/
+static int _putchar(int x, __printf_tag_ptr ctx) {
+  (void)ctx;
+  SEGGER_RTT_Write(0, (char *)&x, 1);
+  return x;
+}
+
+/*********************************************************************
+*
+*       Global functions, printf
+*
+**********************************************************************
+*/
+/*********************************************************************
+*
+*       printf()
+*
+*  Function description
+*    print a formatted string character-wise, using RTT and standard
+*    library formatting.
+*/
+int printf(const char *fmt, ...) {
+  int         n;
+  va_list     args;
+  __printf_t  iod;
+
+  va_start(args, fmt);
+  iod.string    = 0;
+  iod.maxchars  = INT_MAX;
+  iod.output_fn = _putchar;
+  SEGGER_RTT_LOCK();
+  n = __vfprintf(&iod, fmt, args);
+  SEGGER_RTT_UNLOCK();
+  va_end(args);
+  return n;
+}
+
+#else // Use standard library formatting with static buffer
+
+/*********************************************************************
+*
+*       Global functions, printf
+*
+**********************************************************************
+*/
+/*********************************************************************
+*
+*       printf()
+*
+*  Function description
+*    print a formatted string using RTT and standard library formatting.
+*/
+int printf(const char *fmt,...) {
+  int     n;
+  char    aBuffer[PRINTF_BUFFER_SIZE];
+  va_list args;
+
+  va_start (args, fmt);
+  n = vsnprintf(aBuffer, sizeof(aBuffer), fmt, args);
+  if (n > (int)sizeof(aBuffer)) {
+    SEGGER_RTT_Write(0, aBuffer, sizeof(aBuffer));
+  } else if (n > 0) {
+    SEGGER_RTT_Write(0, aBuffer, n);
+  }
+  va_end(args);
+  return n;
+}
+#endif
+
+/*********************************************************************
+*
+*       Global functions
+*
+**********************************************************************
+*/
+/*********************************************************************
+*
+*       puts()
+*
+*  Function description
+*    print a string using RTT.
+*/
+int puts(const char *s) {
+  return SEGGER_RTT_WriteString(0, s);
+}
+
+/*********************************************************************
+*
+*       __putchar()
+*
+*  Function description
+*    Write one character via RTT.
+*/
+int __putchar(int x, __printf_tag_ptr ctx) {
+  (void)ctx;
+  SEGGER_RTT_Write(0, (char *)&x, 1);
+  return x;
+}
+
+/*********************************************************************
+*
+*       __getchar()
+*
+*  Function description
+*    Wait for and get a character via RTT.
+*/
+int __getchar() {
+  return SEGGER_RTT_WaitKey();
+}
+
+#endif
+/****** End Of File *************************************************/

+ 504 - 0
code/debug/SEGGER/SEGGER_RTT_printf.c

@@ -0,0 +1,504 @@
+/*********************************************************************
+*                    SEGGER Microcontroller GmbH                     *
+*                        The Embedded Experts                        *
+**********************************************************************
+*                                                                    *
+*            (c) 1995 - 2021 SEGGER Microcontroller GmbH             *
+*                                                                    *
+*       www.segger.com     Support: support@segger.com               *
+*                                                                    *
+**********************************************************************
+*                                                                    *
+*       SEGGER SystemView * Real-time application analysis           *
+*                                                                    *
+**********************************************************************
+*                                                                    *
+* All rights reserved.                                               *
+*                                                                    *
+* SEGGER strongly recommends to not make any changes                 *
+* to or modify the source code of this software in order to stay     *
+* compatible with the SystemView and RTT protocol, and J-Link.       *
+*                                                                    *
+* Redistribution and use in source and binary forms, with or         *
+* without modification, are permitted provided that the following    *
+* condition is met:                                                  *
+*                                                                    *
+* o Redistributions of source code must retain the above copyright   *
+*   notice, this condition and the following disclaimer.             *
+*                                                                    *
+* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND             *
+* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,        *
+* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF           *
+* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE           *
+* DISCLAIMED. IN NO EVENT SHALL SEGGER Microcontroller BE LIABLE FOR *
+* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR           *
+* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT  *
+* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;    *
+* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF      *
+* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT          *
+* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE  *
+* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH   *
+* DAMAGE.                                                            *
+*                                                                    *
+**********************************************************************
+*                                                                    *
+*       SystemView version: 3.32                                    *
+*                                                                    *
+**********************************************************************
+---------------------------END-OF-HEADER------------------------------
+File    : SEGGER_RTT_printf.c
+Purpose : Replacement for printf to write formatted data via RTT
+Revision: $Rev: 17697 $
+----------------------------------------------------------------------
+*/
+#include "SEGGER_RTT.h"
+#include "SEGGER_RTT_Conf.h"
+
+/*********************************************************************
+*
+*       Defines, configurable
+*
+**********************************************************************
+*/
+
+#ifndef SEGGER_RTT_PRINTF_BUFFER_SIZE
+  #define SEGGER_RTT_PRINTF_BUFFER_SIZE (64)
+#endif
+
+#include <stdlib.h>
+#include <stdarg.h>
+
+
+#define FORMAT_FLAG_LEFT_JUSTIFY   (1u << 0)
+#define FORMAT_FLAG_PAD_ZERO       (1u << 1)
+#define FORMAT_FLAG_PRINT_SIGN     (1u << 2)
+#define FORMAT_FLAG_ALTERNATE      (1u << 3)
+
+/*********************************************************************
+*
+*       Types
+*
+**********************************************************************
+*/
+
+typedef struct {
+  char*     pBuffer;
+  unsigned  BufferSize;
+  unsigned  Cnt;
+
+  int   ReturnValue;
+
+  unsigned RTTBufferIndex;
+} SEGGER_RTT_PRINTF_DESC;
+
+/*********************************************************************
+*
+*       Function prototypes
+*
+**********************************************************************
+*/
+
+/*********************************************************************
+*
+*       Static code
+*
+**********************************************************************
+*/
+/*********************************************************************
+*
+*       _StoreChar
+*/
+static void _StoreChar(SEGGER_RTT_PRINTF_DESC * p, char c) {
+  unsigned Cnt;
+
+  Cnt = p->Cnt;
+  if ((Cnt + 1u) <= p->BufferSize) {
+    *(p->pBuffer + Cnt) = c;
+    p->Cnt = Cnt + 1u;
+    p->ReturnValue++;
+  }
+  //
+  // Write part of string, when the buffer is full
+  //
+  if (p->Cnt == p->BufferSize) {
+    if (SEGGER_RTT_Write(p->RTTBufferIndex, p->pBuffer, p->Cnt) != p->Cnt) {
+      p->ReturnValue = -1;
+    } else {
+      p->Cnt = 0u;
+    }
+  }
+}
+
+/*********************************************************************
+*
+*       _PrintUnsigned
+*/
+static void _PrintUnsigned(SEGGER_RTT_PRINTF_DESC * pBufferDesc, unsigned v, unsigned Base, unsigned NumDigits, unsigned FieldWidth, unsigned FormatFlags) {
+  static const char _aV2C[16] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
+  unsigned Div;
+  unsigned Digit;
+  unsigned Number;
+  unsigned Width;
+  char c;
+
+  Number = v;
+  Digit = 1u;
+  //
+  // Get actual field width
+  //
+  Width = 1u;
+  while (Number >= Base) {
+    Number = (Number / Base);
+    Width++;
+  }
+  if (NumDigits > Width) {
+    Width = NumDigits;
+  }
+  //
+  // Print leading chars if necessary
+  //
+  if ((FormatFlags & FORMAT_FLAG_LEFT_JUSTIFY) == 0u) {
+    if (FieldWidth != 0u) {
+      if (((FormatFlags & FORMAT_FLAG_PAD_ZERO) == FORMAT_FLAG_PAD_ZERO) && (NumDigits == 0u)) {
+        c = '0';
+      } else {
+        c = ' ';
+      }
+      while ((FieldWidth != 0u) && (Width < FieldWidth)) {
+        FieldWidth--;
+        _StoreChar(pBufferDesc, c);
+        if (pBufferDesc->ReturnValue < 0) {
+          break;
+        }
+      }
+    }
+  }
+  if (pBufferDesc->ReturnValue >= 0) {
+    //
+    // Compute Digit.
+    // Loop until Digit has the value of the highest digit required.
+    // Example: If the output is 345 (Base 10), loop 2 times until Digit is 100.
+    //
+    while (1) {
+      if (NumDigits > 1u) {       // User specified a min number of digits to print? => Make sure we loop at least that often, before checking anything else (> 1 check avoids problems with NumDigits being signed / unsigned)
+        NumDigits--;
+      } else {
+        Div = v / Digit;
+        if (Div < Base) {        // Is our divider big enough to extract the highest digit from value? => Done
+          break;
+        }
+      }
+      Digit *= Base;
+    }
+    //
+    // Output digits
+    //
+    do {
+      Div = v / Digit;
+      v -= Div * Digit;
+      _StoreChar(pBufferDesc, _aV2C[Div]);
+      if (pBufferDesc->ReturnValue < 0) {
+        break;
+      }
+      Digit /= Base;
+    } while (Digit);
+    //
+    // Print trailing spaces if necessary
+    //
+    if ((FormatFlags & FORMAT_FLAG_LEFT_JUSTIFY) == FORMAT_FLAG_LEFT_JUSTIFY) {
+      if (FieldWidth != 0u) {
+        while ((FieldWidth != 0u) && (Width < FieldWidth)) {
+          FieldWidth--;
+          _StoreChar(pBufferDesc, ' ');
+          if (pBufferDesc->ReturnValue < 0) {
+            break;
+          }
+        }
+      }
+    }
+  }
+}
+
+/*********************************************************************
+*
+*       _PrintInt
+*/
+static void _PrintInt(SEGGER_RTT_PRINTF_DESC * pBufferDesc, int v, unsigned Base, unsigned NumDigits, unsigned FieldWidth, unsigned FormatFlags) {
+  unsigned Width;
+  int Number;
+
+  Number = (v < 0) ? -v : v;
+
+  //
+  // Get actual field width
+  //
+  Width = 1u;
+  while (Number >= (int)Base) {
+    Number = (Number / (int)Base);
+    Width++;
+  }
+  if (NumDigits > Width) {
+    Width = NumDigits;
+  }
+  if ((FieldWidth > 0u) && ((v < 0) || ((FormatFlags & FORMAT_FLAG_PRINT_SIGN) == FORMAT_FLAG_PRINT_SIGN))) {
+    FieldWidth--;
+  }
+
+  //
+  // Print leading spaces if necessary
+  //
+  if ((((FormatFlags & FORMAT_FLAG_PAD_ZERO) == 0u) || (NumDigits != 0u)) && ((FormatFlags & FORMAT_FLAG_LEFT_JUSTIFY) == 0u)) {
+    if (FieldWidth != 0u) {
+      while ((FieldWidth != 0u) && (Width < FieldWidth)) {
+        FieldWidth--;
+        _StoreChar(pBufferDesc, ' ');
+        if (pBufferDesc->ReturnValue < 0) {
+          break;
+        }
+      }
+    }
+  }
+  //
+  // Print sign if necessary
+  //
+  if (pBufferDesc->ReturnValue >= 0) {
+    if (v < 0) {
+      v = -v;
+      _StoreChar(pBufferDesc, '-');
+    } else if ((FormatFlags & FORMAT_FLAG_PRINT_SIGN) == FORMAT_FLAG_PRINT_SIGN) {
+      _StoreChar(pBufferDesc, '+');
+    } else {
+
+    }
+    if (pBufferDesc->ReturnValue >= 0) {
+      //
+      // Print leading zeros if necessary
+      //
+      if (((FormatFlags & FORMAT_FLAG_PAD_ZERO) == FORMAT_FLAG_PAD_ZERO) && ((FormatFlags & FORMAT_FLAG_LEFT_JUSTIFY) == 0u) && (NumDigits == 0u)) {
+        if (FieldWidth != 0u) {
+          while ((FieldWidth != 0u) && (Width < FieldWidth)) {
+            FieldWidth--;
+            _StoreChar(pBufferDesc, '0');
+            if (pBufferDesc->ReturnValue < 0) {
+              break;
+            }
+          }
+        }
+      }
+      if (pBufferDesc->ReturnValue >= 0) {
+        //
+        // Print number without sign
+        //
+        _PrintUnsigned(pBufferDesc, (unsigned)v, Base, NumDigits, FieldWidth, FormatFlags);
+      }
+    }
+  }
+}
+
+/*********************************************************************
+*
+*       Public code
+*
+**********************************************************************
+*/
+/*********************************************************************
+*
+*       SEGGER_RTT_vprintf
+*
+*  Function description
+*    Stores a formatted string in SEGGER RTT control block.
+*    This data is read by the host.
+*
+*  Parameters
+*    BufferIndex  Index of "Up"-buffer to be used. (e.g. 0 for "Terminal")
+*    sFormat      Pointer to format string
+*    pParamList   Pointer to the list of arguments for the format string
+*
+*  Return values
+*    >= 0:  Number of bytes which have been stored in the "Up"-buffer.
+*     < 0:  Error
+*/
+int SEGGER_RTT_vprintf(unsigned BufferIndex, const char * sFormat, va_list * pParamList) {
+  char c;
+  SEGGER_RTT_PRINTF_DESC BufferDesc;
+  int v;
+  unsigned NumDigits;
+  unsigned FormatFlags;
+  unsigned FieldWidth;
+  char acBuffer[SEGGER_RTT_PRINTF_BUFFER_SIZE];
+
+  BufferDesc.pBuffer        = acBuffer;
+  BufferDesc.BufferSize     = SEGGER_RTT_PRINTF_BUFFER_SIZE;
+  BufferDesc.Cnt            = 0u;
+  BufferDesc.RTTBufferIndex = BufferIndex;
+  BufferDesc.ReturnValue    = 0;
+
+  do {
+    c = *sFormat;
+    sFormat++;
+    if (c == 0u) {
+      break;
+    }
+    if (c == '%') {
+      //
+      // Filter out flags
+      //
+      FormatFlags = 0u;
+      v = 1;
+      do {
+        c = *sFormat;
+        switch (c) {
+        case '-': FormatFlags |= FORMAT_FLAG_LEFT_JUSTIFY; sFormat++; break;
+        case '0': FormatFlags |= FORMAT_FLAG_PAD_ZERO;     sFormat++; break;
+        case '+': FormatFlags |= FORMAT_FLAG_PRINT_SIGN;   sFormat++; break;
+        case '#': FormatFlags |= FORMAT_FLAG_ALTERNATE;    sFormat++; break;
+        default:  v = 0; break;
+        }
+      } while (v);
+      //
+      // filter out field with
+      //
+      FieldWidth = 0u;
+      do {
+        c = *sFormat;
+        if ((c < '0') || (c > '9')) {
+          break;
+        }
+        sFormat++;
+        FieldWidth = (FieldWidth * 10u) + ((unsigned)c - '0');
+      } while (1);
+
+      //
+      // Filter out precision (number of digits to display)
+      //
+      NumDigits = 0u;
+      c = *sFormat;
+      if (c == '.') {
+        sFormat++;
+        do {
+          c = *sFormat;
+          if ((c < '0') || (c > '9')) {
+            break;
+          }
+          sFormat++;
+          NumDigits = NumDigits * 10u + ((unsigned)c - '0');
+        } while (1);
+      }
+      //
+      // Filter out length modifier
+      //
+      c = *sFormat;
+      do {
+        if ((c == 'l') || (c == 'h')) {
+          sFormat++;
+          c = *sFormat;
+        } else {
+          break;
+        }
+      } while (1);
+      //
+      // Handle specifiers
+      //
+      switch (c) {
+      case 'c': {
+        char c0;
+        v = va_arg(*pParamList, int);
+        c0 = (char)v;
+        _StoreChar(&BufferDesc, c0);
+        break;
+      }
+      case 'd':
+        v = va_arg(*pParamList, int);
+        _PrintInt(&BufferDesc, v, 10u, NumDigits, FieldWidth, FormatFlags);
+        break;
+      case 'u':
+        v = va_arg(*pParamList, int);
+        _PrintUnsigned(&BufferDesc, (unsigned)v, 10u, NumDigits, FieldWidth, FormatFlags);
+        break;
+      case 'x':
+      case 'X':
+        v = va_arg(*pParamList, int);
+        _PrintUnsigned(&BufferDesc, (unsigned)v, 16u, NumDigits, FieldWidth, FormatFlags);
+        break;
+      case 's':
+        {
+          const char * s = va_arg(*pParamList, const char *);
+          do {
+            c = *s;
+            s++;
+            if (c == '\0') {
+              break;
+            }
+           _StoreChar(&BufferDesc, c);
+          } while (BufferDesc.ReturnValue >= 0);
+        }
+        break;
+      case 'p':
+        v = va_arg(*pParamList, int);
+        _PrintUnsigned(&BufferDesc, (unsigned)v, 16u, 8u, 8u, 0u);
+        break;
+      case '%':
+        _StoreChar(&BufferDesc, '%');
+        break;
+      default:
+        break;
+      }
+      sFormat++;
+    } else {
+      _StoreChar(&BufferDesc, c);
+    }
+  } while (BufferDesc.ReturnValue >= 0);
+
+  if (BufferDesc.ReturnValue > 0) {
+    //
+    // Write remaining data, if any
+    //
+    if (BufferDesc.Cnt != 0u) {
+      SEGGER_RTT_Write(BufferIndex, acBuffer, BufferDesc.Cnt);
+    }
+    BufferDesc.ReturnValue += (int)BufferDesc.Cnt;
+  }
+  return BufferDesc.ReturnValue;
+}
+
+/*********************************************************************
+*
+*       SEGGER_RTT_printf
+*
+*  Function description
+*    Stores a formatted string in SEGGER RTT control block.
+*    This data is read by the host.
+*
+*  Parameters
+*    BufferIndex  Index of "Up"-buffer to be used. (e.g. 0 for "Terminal")
+*    sFormat      Pointer to format string, followed by the arguments for conversion
+*
+*  Return values
+*    >= 0:  Number of bytes which have been stored in the "Up"-buffer.
+*     < 0:  Error
+*
+*  Notes
+*    (1) Conversion specifications have following syntax:
+*          %[flags][FieldWidth][.Precision]ConversionSpecifier
+*    (2) Supported flags:
+*          -: Left justify within the field width
+*          +: Always print sign extension for signed conversions
+*          0: Pad with 0 instead of spaces. Ignored when using '-'-flag or precision
+*        Supported conversion specifiers:
+*          c: Print the argument as one char
+*          d: Print the argument as a signed integer
+*          u: Print the argument as an unsigned integer
+*          x: Print the argument as an hexadecimal integer
+*          s: Print the string pointed to by the argument
+*          p: Print the argument as an 8-digit hexadecimal integer. (Argument shall be a pointer to void.)
+*/
+int SEGGER_RTT_printf(const char * sFormat, ...) {
+  int r;
+  va_list ParamList;
+
+  va_start(ParamList, sFormat);
+  r = SEGGER_RTT_vprintf(0, sFormat, &ParamList);
+  va_end(ParamList);
+  return r;
+}
+/*************************** End of file ****************************/

+ 3102 - 0
code/debug/SEGGER/SEGGER_SYSVIEW.c

@@ -0,0 +1,3102 @@
+/*********************************************************************
+*                    SEGGER Microcontroller GmbH                     *
+*                        The Embedded Experts                        *
+**********************************************************************
+*                                                                    *
+*            (c) 1995 - 2021 SEGGER Microcontroller GmbH             *
+*                                                                    *
+*       www.segger.com     Support: support@segger.com               *
+*                                                                    *
+**********************************************************************
+*                                                                    *
+*       SEGGER SystemView * Real-time application analysis           *
+*                                                                    *
+**********************************************************************
+*                                                                    *
+* All rights reserved.                                               *
+*                                                                    *
+* SEGGER strongly recommends to not make any changes                 *
+* to or modify the source code of this software in order to stay     *
+* compatible with the SystemView and RTT protocol, and J-Link.       *
+*                                                                    *
+* Redistribution and use in source and binary forms, with or         *
+* without modification, are permitted provided that the following    *
+* condition is met:                                                  *
+*                                                                    *
+* o Redistributions of source code must retain the above copyright   *
+*   notice, this condition and the following disclaimer.             *
+*                                                                    *
+* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND             *
+* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,        *
+* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF           *
+* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE           *
+* DISCLAIMED. IN NO EVENT SHALL SEGGER Microcontroller BE LIABLE FOR *
+* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR           *
+* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT  *
+* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;    *
+* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF      *
+* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT          *
+* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE  *
+* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH   *
+* DAMAGE.                                                            *
+*                                                                    *
+**********************************************************************
+*                                                                    *
+*       SystemView version: 3.32                                    *
+*                                                                    *
+**********************************************************************
+-------------------------- END-OF-HEADER -----------------------------
+
+File    : SEGGER_SYSVIEW.c
+Purpose : System visualization API implementation.
+Revision: $Rev: 26232 $
+
+Additional information:
+  Packet format:
+    Packets with IDs 0..23 are standard packets with known structure.
+    For efficiency, they do *NOT* contain a length field.
+    <ID><Data><TimeStampDelta>
+
+    Packets with IDs 24..31 are standard packets with extendible
+    structure and contain a length field.
+    <ID><Lenght><Data><TimeStampDelta>
+
+    Packet ID 31 is used for SystemView extended events.
+    <ID><Lenght><ID_EX><Data><TimeStampDelta>
+
+    Packets with IDs >= 32 always contain a length field.
+    <ID><Length><Data><TimeStampDelta>
+
+  Packet IDs:
+       0..  31 : Standard packets, known by SystemView.
+      32..1023 : OS-definable packets, described in a SystemView description file.
+    1024..2047 : User-definable packets, described in a SystemView description file.
+    2048..32767: Undefined.
+
+  Data encoding:
+    Basic types (int, short, char, ...):
+      Basic types are encoded little endian with most-significant bit variant
+      encoding.
+      Each encoded byte contains 7 data bits [6:0] and the MSB continuation bit.
+      The continuation bit indicates whether the next byte belongs to the data
+      (bit set) or this is the last byte (bit clear).
+      The most significant bits of data are encoded first, proceeding to the
+      least significant bits in the final byte (little endian).
+
+      Example encoding:
+        Data: 0x1F4 (500)
+        Encoded: 0xF4 (First 7 data bits 74 | Continuation bit)
+                 0x03 (Second 7 data bits 03, no continuation)
+
+        Data: 0xFFFFFFFF
+        Encoded: 0xFF 0xFF 0xFF 0xFF 0x0F
+
+        Data: 0xA2 (162),   0x03 (3), 0x7000
+        Encoded: 0xA2 0x01  0x03      0x80 0xE0 0x01
+
+    Byte arrays and strings:
+      Byte arrays and strings are encoded as <NumBytes> followed by the raw data.
+      NumBytes is encoded as a basic type with a theoretical maximum of 4G.
+
+      Example encoding:
+        Data: "Hello World\0" (0x48 0x65 0x6C 0x6C 0x6F 0x20 0x57 0x6F 0x72 0x6C 0x64 0x00)
+        Encoded: 0x0B 0x48 0x65 0x6C 0x6C 0x6F 0x20 0x57 0x6F 0x72 0x6C 0x64
+
+  Examples packets:
+  01 F4 03 80 80 10 // Overflow packet. Data is a single U32.
+                       This packet means: 500 packets lost, Timestamp is 0x40000
+
+  02 0F 50          // ISR(15) Enter. Timestamp 80 (0x50)
+
+  03 20             // ISR Exit. Timestamp 32 (0x20) (Shortest possible packet.)
+
+  Sample code for user defined Packets:
+    #define MY_ID   0x400                // Any value between 0x400 and 0x7FF
+    void SendMyPacket(unsigned Para0, unsigned Para1, const char* s) {
+      U8  aPacket[SEGGER_SYSVIEW_INFO_SIZE + 2 * SEGGER_SYSVIEW_QUANTA_U32 + MAX_STR_LEN + 1];
+      U8* pPayload;
+      //
+      pPayload = SEGGER_SYSVIEW_PPREPARE_PACKET(aPacket);               // Prepare the packet for SystemView
+      pPayload = SEGGER_SYSVIEW_EncodeU32(pPayload, Para0);             // Add the first parameter to the packet
+      pPayload = SEGGER_SYSVIEW_EncodeU32(pPayload, Para1);             // Add the second parameter to the packet
+      pPayload = SEGGER_SYSVIEW_EncodeString(pPayload, s, MAX_STR_LEN); // Add the string to the packet
+      //
+      SEGGER_SYSVIEW_SendPacket(&aPacket[0], pPayload, MY_ID);          // Send the packet with EventId = MY_ID
+    }
+
+    #define MY_ID_1 0x401
+    void SendOnePara(unsigned Para0) {
+      SEGGER_SYSVIEW_RecordU32(MY_ID_1, Para0);
+    }
+
+*/
+
+/*********************************************************************
+*
+*       #include section
+*
+**********************************************************************
+*/
+
+#define SEGGER_SYSVIEW_C  // For EXTERN statements in SEGGER_SYSVIEW.h
+
+#include <string.h>
+#include <stdlib.h>
+#include <stdarg.h>
+#include "SEGGER_SYSVIEW_Int.h"
+#include "SEGGER_RTT.h"
+
+/*********************************************************************
+*
+*       Defines, fixed
+*
+**********************************************************************
+*/
+#if SEGGER_SYSVIEW_ID_SHIFT
+  #define SHRINK_ID(Id)   (((Id) - _SYSVIEW_Globals.RAMBaseAddress) >> SEGGER_SYSVIEW_ID_SHIFT)
+#else
+  #define SHRINK_ID(Id)   ((Id) - _SYSVIEW_Globals.RAMBaseAddress)
+#endif
+
+#if SEGGER_SYSVIEW_RTT_CHANNEL > 0
+  #define CHANNEL_ID_UP   SEGGER_SYSVIEW_RTT_CHANNEL
+  #define CHANNEL_ID_DOWN SEGGER_SYSVIEW_RTT_CHANNEL
+#else
+  #define CHANNEL_ID_UP   _SYSVIEW_Globals.UpChannel
+  #define CHANNEL_ID_DOWN _SYSVIEW_Globals.DownChannel
+#endif
+
+#if SEGGER_SYSVIEW_CPU_CACHE_LINE_SIZE
+  #if (SEGGER_SYSVIEW_RTT_BUFFER_SIZE % SEGGER_SYSVIEW_CPU_CACHE_LINE_SIZE)
+    #error "SEGGER_SYSVIEW_RTT_BUFFER_SIZE must be a multiple of SEGGER_SYSVIEW_CPU_CACHE_LINE_SIZE"
+  #endif
+#endif
+
+/*********************************************************************
+*
+*       Defines, configurable
+*
+**********************************************************************
+*/
+// Timestamps may be less than full 32-bits, in which case we need to zero
+// the unused bits to properly handle overflows.
+// Note that this is a quite common scenario, as a 32-bit time such as
+// SysTick might be scaled down to reduce bandwith
+// or a 16-bit hardware time might be used.
+#if SEGGER_SYSVIEW_TIMESTAMP_BITS < 32  // Eliminate unused bits in case hardware timestamps are less than 32 bits
+  #define MAKE_DELTA_32BIT(Delta) Delta <<= 32 - SEGGER_SYSVIEW_TIMESTAMP_BITS; \
+                                  Delta >>= 32 - SEGGER_SYSVIEW_TIMESTAMP_BITS;
+#else
+  #define MAKE_DELTA_32BIT(Delta)
+#endif
+
+#if SEGGER_SYSVIEW_SUPPORT_LONG_ID
+  #define _MAX_ID_BYTES       5u
+#else
+  #define _MAX_ID_BYTES       2u
+#endif
+
+#if SEGGER_SYSVIEW_SUPPORT_LONG_DATA
+  #define _MAX_DATA_BYTES     5u
+#else
+  #define _MAX_DATA_BYTES     2u
+#endif
+
+/*********************************************************************
+*
+*       Defines, fixed
+*
+**********************************************************************
+*/
+#define ENABLE_STATE_OFF        0
+#define ENABLE_STATE_ON         1
+#define ENABLE_STATE_DROPPING   2
+
+#define FORMAT_FLAG_LEFT_JUSTIFY   (1u << 0)
+#define FORMAT_FLAG_PAD_ZERO       (1u << 1)
+#define FORMAT_FLAG_PRINT_SIGN     (1u << 2)
+#define FORMAT_FLAG_ALTERNATE      (1u << 3)
+
+#define MODULE_EVENT_OFFSET        (512)
+
+/*********************************************************************
+*
+*       Types, local
+*
+**********************************************************************
+*/
+typedef struct {
+  U8*       pBuffer;
+  U8*       pPayload;
+  U8*       pPayloadStart;
+  U32       Options;
+  unsigned  Cnt;
+} SEGGER_SYSVIEW_PRINTF_DESC;
+
+typedef struct {
+        U8                      EnableState;   // 0: Disabled, 1: Enabled, (2: Dropping)
+        U8                      UpChannel;
+        U8                      RecursionCnt;
+        U32                     SysFreq;
+        U32                     CPUFreq;
+        U32                     LastTxTimeStamp;
+        U32                     RAMBaseAddress;
+#if (SEGGER_SYSVIEW_POST_MORTEM_MODE == 1)
+        U32                     PacketCount;
+#else
+        U32                     DropCount;
+        U8                      DownChannel;
+#endif
+        U32                     DisabledEvents;
+  const SEGGER_SYSVIEW_OS_API*  pOSAPI;
+        SEGGER_SYSVIEW_SEND_SYS_DESC_FUNC*   pfSendSysDesc;
+} SEGGER_SYSVIEW_GLOBALS;
+
+/*********************************************************************
+*
+*       Function prototypes, required
+*
+**********************************************************************
+*/
+static void _SendPacket(U8* pStartPacket, U8* pEndPacket, unsigned int EventId);
+
+/*********************************************************************
+*
+*       Static data
+*
+**********************************************************************
+*/
+static const U8 _abSync[10] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
+
+#if SEGGER_SYSVIEW_CPU_CACHE_LINE_SIZE
+  #ifdef SEGGER_SYSVIEW_SECTION
+    //
+    // Alignment + special section required
+    //
+    #if (defined __GNUC__)
+      __attribute__ ((section (SEGGER_SYSVIEW_SECTION), aligned (SEGGER_SYSVIEW_CPU_CACHE_LINE_SIZE))) static char _UpBuffer  [SEGGER_SYSVIEW_RTT_BUFFER_SIZE];
+      #if (SEGGER_SYSVIEW_POST_MORTEM_MODE != 1)
+        __attribute__ ((section (SEGGER_SYSVIEW_SECTION), aligned (SEGGER_SYSVIEW_CPU_CACHE_LINE_SIZE))) static char _DownBuffer[8];  // Small, fixed-size buffer, for back-channel comms
+      #endif
+    #elif (defined __ICCARM__) || (defined __ICCRX__)
+      #pragma location=SEGGER_SYSVIEW_SECTION
+      #pragma data_alignment=SEGGER_RTT_CPU_CACHE_LINE_SIZE
+      static char _UpBuffer  [SEGGER_SYSVIEW_RTT_BUFFER_SIZE];
+      #if (SEGGER_SYSVIEW_POST_MORTEM_MODE != 1)
+        #pragma location=SEGGER_SYSVIEW_SECTION
+        #pragma data_alignment=SEGGER_RTT_CPU_CACHE_LINE_SIZE
+        static char _DownBuffer[8];  // Small, fixed-size buffer, for back-channel comms
+      #endif
+    #elif (defined __CC_ARM)
+      __attribute__ ((section (SEGGER_SYSVIEW_SECTION), aligned (SEGGER_SYSVIEW_CPU_CACHE_LINE_SIZE), zero_init)) static char _UpBuffer  [SEGGER_SYSVIEW_RTT_BUFFER_SIZE];
+      #if (SEGGER_SYSVIEW_POST_MORTEM_MODE != 1)
+        __attribute__ ((section (SEGGER_SYSVIEW_SECTION), aligned (SEGGER_SYSVIEW_CPU_CACHE_LINE_SIZE), zero_init)) static char _DownBuffer[8];  // Small, fixed-size buffer, for back-channel comms
+      #endif
+    #else
+      #error "Do not know how to place SystemView buffers in specific section"
+    #endif
+  #else
+    //
+    // Only alignment required
+    //
+    #if (defined __GNUC__)
+      __attribute__ ((aligned (SEGGER_SYSVIEW_CPU_CACHE_LINE_SIZE))) static char _UpBuffer  [SEGGER_SYSVIEW_RTT_BUFFER_SIZE];
+      #if (SEGGER_SYSVIEW_POST_MORTEM_MODE != 1)
+        __attribute__ ((aligned (SEGGER_SYSVIEW_CPU_CACHE_LINE_SIZE))) static char _DownBuffer[8];  // Small, fixed-size buffer, for back-channel comms
+      #endif
+    #elif (defined __ICCARM__) || (defined __ICCRX__)
+      #pragma data_alignment=SEGGER_RTT_CPU_CACHE_LINE_SIZE
+      static char _UpBuffer  [SEGGER_SYSVIEW_RTT_BUFFER_SIZE];
+      #if (SEGGER_SYSVIEW_POST_MORTEM_MODE != 1)
+        #pragma data_alignment=SEGGER_RTT_CPU_CACHE_LINE_SIZE
+        static char _DownBuffer[8];  // Small, fixed-size buffer, for back-channel comms
+      #endif
+    #elif (defined __CC_ARM)
+      __attribute__ ((aligned (SEGGER_SYSVIEW_CPU_CACHE_LINE_SIZE), zero_init)) static char _UpBuffer  [SEGGER_SYSVIEW_RTT_BUFFER_SIZE];
+      #if (SEGGER_SYSVIEW_POST_MORTEM_MODE != 1)
+        __attribute__ ((aligned (SEGGER_SYSVIEW_CPU_CACHE_LINE_SIZE), zero_init)) static char _DownBuffer[8];  // Small, fixed-size buffer, for back-channel comms
+      #endif
+    #else
+      #error "Do not know how to align SystemView buffers to cache line size"
+    #endif
+  #endif
+#else
+  #ifdef SEGGER_SYSVIEW_SECTION
+    //
+    // Only special section required
+    //
+    #if (defined __GNUC__)
+      __attribute__ ((section (SEGGER_SYSVIEW_SECTION))) static char _UpBuffer  [SEGGER_SYSVIEW_RTT_BUFFER_SIZE];
+      #if (SEGGER_SYSVIEW_POST_MORTEM_MODE != 1)
+        __attribute__ ((section (SEGGER_SYSVIEW_SECTION))) static char _DownBuffer[8];  // Small, fixed-size buffer, for back-channel comms
+      #endif
+    #elif (defined __ICCARM__) || (defined __ICCRX__)
+      #pragma location=SEGGER_SYSVIEW_SECTION
+      static char _UpBuffer  [SEGGER_SYSVIEW_RTT_BUFFER_SIZE];
+      #if (SEGGER_SYSVIEW_POST_MORTEM_MODE != 1)
+        #pragma location=SEGGER_SYSVIEW_SECTION
+        static char _DownBuffer[8];  // Small, fixed-size buffer, for back-channel comms
+      #endif
+    #elif (defined __CC_ARM)
+      __attribute__ ((section (SEGGER_SYSVIEW_SECTION), zero_init)) static char _UpBuffer  [SEGGER_SYSVIEW_RTT_BUFFER_SIZE];
+      #if (SEGGER_SYSVIEW_POST_MORTEM_MODE != 1)
+        __attribute__ ((section (SEGGER_SYSVIEW_SECTION), zero_init)) static char _DownBuffer[8];  // Small, fixed-size buffer, for back-channel comms
+      #endif
+    #else
+      #error "Do not know how to place SystemView buffers in specific section"
+    #endif
+  #else
+    //
+    // Neither special section nor alignment required
+    //
+    static char _UpBuffer  [SEGGER_SYSVIEW_RTT_BUFFER_SIZE];
+    #if (SEGGER_SYSVIEW_POST_MORTEM_MODE != 1)
+      static char _DownBuffer[8];  // Small, fixed-size buffer, for back-channel comms
+    #endif
+  #endif
+#endif
+
+static SEGGER_SYSVIEW_GLOBALS _SYSVIEW_Globals;
+
+static SEGGER_SYSVIEW_MODULE* _pFirstModule;
+static U8                     _NumModules;
+
+/*********************************************************************
+*
+*       Static code
+*
+**********************************************************************
+*/
+
+#define ENCODE_U32(pDest, Value) {                                                  \
+                                   U8* pSysviewPointer;                             \
+                                   U32 SysViewData;                                 \
+                                   pSysviewPointer = pDest;                         \
+                                   SysViewData = Value;                             \
+                                   while(SysViewData > 0x7F) {                      \
+                                     *pSysviewPointer++ = (U8)(SysViewData | 0x80); \
+                                     SysViewData >>= 7;                             \
+                                   };                                               \
+                                   *pSysviewPointer++ = (U8)SysViewData;            \
+                                   pDest = pSysviewPointer;                         \
+                                 };
+
+
+
+#if (SEGGER_SYSVIEW_USE_STATIC_BUFFER == 1)
+static U8 _aPacket[SEGGER_SYSVIEW_MAX_PACKET_SIZE];
+
+#define RECORD_START(PacketSize)  SEGGER_SYSVIEW_LOCK();                            \
+                                  pPayloadStart = _PreparePacket(_aPacket);
+
+#define RECORD_END()              SEGGER_SYSVIEW_UNLOCK()
+
+#else
+
+#define RECORD_START(PacketSize)  U8 aPacket[(PacketSize)];                         \
+                                  pPayloadStart = _PreparePacket(aPacket);          \
+
+#define RECORD_END()
+
+#endif
+
+/*********************************************************************
+*
+*       _EncodeData()
+*
+*  Function description
+*    Encode a byte buffer in variable-length format.
+*
+*  Parameters
+*    pPayload - Pointer to where string will be encoded.
+*    pSrc     - Pointer to data buffer to be encoded.
+*    NumBytes - Number of bytes in the buffer to be encoded.
+*
+*  Return value
+*    Pointer to the byte following the value, i.e. the first free
+*    byte in the payload and the next position to store payload
+*    content.
+*
+*  Additional information
+*    The data is encoded as a count byte followed by the contents
+*    of the data buffer.
+*    Make sure NumBytes + 1 bytes are free for the payload.
+*/
+static U8* _EncodeData(U8* pPayload, const char* pSrc, unsigned int NumBytes) {
+  unsigned int  n;
+  const U8*     p;
+  //
+  n = 0;
+  p = (const U8*)pSrc;
+  //
+  // Write Len
+  //
+  if (NumBytes < 255)  {
+    *pPayload++ = (U8)NumBytes;
+  } else {
+    *pPayload++ = 255;
+    *pPayload++ = (NumBytes & 255);
+    *pPayload++ = ((NumBytes >> 8) & 255);
+  }
+  while (n < NumBytes) {
+    *pPayload++ = *p++;
+    n++;
+  }
+  return pPayload;
+}
+
+/*********************************************************************
+*
+*       _EncodeStr()
+*
+*  Function description
+*    Encode a string in variable-length format.
+*
+*  Parameters
+*    pPayload - Pointer to where string will be encoded.
+*    pText    - String to encode.
+*    Limit    - Maximum number of characters to encode from string.
+*
+*  Return value
+*    Pointer to the byte following the value, i.e. the first free
+*    byte in the payload and the next position to store payload
+*    content.
+*
+*  Additional information
+*    The string is encoded as a count byte followed by the contents
+*    of the string.
+*    No more than 1 + Limit bytes will be encoded to the payload.
+*/
+static U8 *_EncodeStr(U8 *pPayload, const char *pText, unsigned int Limit) {
+  unsigned int n;
+  unsigned int Len;
+  //
+  // Compute string len
+  //
+  Len = 0;
+  if (pText != NULL) {
+    while(*(pText + Len) != 0) {
+      Len++;
+    }
+    if (Len > Limit) {
+      Len = Limit;
+    }
+  }
+  //
+  // Write Len
+  //
+  if (Len < 255)  {
+    *pPayload++ = (U8)Len;
+  } else {
+    *pPayload++ = 255;
+    *pPayload++ = (Len & 255);
+    *pPayload++ = ((Len >> 8) & 255);
+  }
+  //
+  // copy string
+  //
+  n = 0;
+  while (n < Len) {
+    *pPayload++ = *pText++;
+    n++;
+  }
+  return pPayload;
+}
+
+/*********************************************************************
+*
+*       _PreparePacket()
+*
+*  Function description
+*    Prepare a SystemView event packet header.
+*
+*  Parameters
+*    pPacket - Pointer to start of packet to initialize.
+*
+*  Return value
+*    Pointer to first byte of packet payload.
+*
+*  Additional information
+*    The payload length and evnetId are not initialized.
+*    PreparePacket only reserves space for them and they are
+*    computed and filled in by the sending function.
+*/
+static U8* _PreparePacket(U8* pPacket) {
+  return pPacket + _MAX_ID_BYTES + _MAX_DATA_BYTES;
+}
+
+/*********************************************************************
+*
+*       _HandleIncomingPacket()
+*
+*  Function description
+*    Read an incoming command from the down channel and process it.
+*
+*  Additional information
+*    This function is called each time after sending a packet.
+*    Processing incoming packets is done asynchronous. SystemView might
+*    already have sent event packets after the host has sent a command.
+*/
+#if (SEGGER_SYSVIEW_POST_MORTEM_MODE != 1)
+static void _HandleIncomingPacket(void) {
+  U8  Cmd;
+  unsigned int Status;
+  //
+  Status = SEGGER_RTT_ReadNoLock(CHANNEL_ID_DOWN, &Cmd, 1);
+  if (Status > 0) {
+    switch (Cmd) {
+    case SEGGER_SYSVIEW_COMMAND_ID_START:
+      SEGGER_SYSVIEW_Start();
+      break;
+    case SEGGER_SYSVIEW_COMMAND_ID_STOP:
+      SEGGER_SYSVIEW_Stop();
+      break;
+    case SEGGER_SYSVIEW_COMMAND_ID_GET_SYSTIME:
+      SEGGER_SYSVIEW_RecordSystime();
+      break;
+    case SEGGER_SYSVIEW_COMMAND_ID_GET_TASKLIST:
+      SEGGER_SYSVIEW_SendTaskList();
+      break;
+    case SEGGER_SYSVIEW_COMMAND_ID_GET_SYSDESC:
+      SEGGER_SYSVIEW_GetSysDesc();
+      break;
+    case SEGGER_SYSVIEW_COMMAND_ID_GET_NUMMODULES:
+      SEGGER_SYSVIEW_SendNumModules();
+      break;
+    case SEGGER_SYSVIEW_COMMAND_ID_GET_MODULEDESC:
+      SEGGER_SYSVIEW_SendModuleDescription();
+      break;
+    case SEGGER_SYSVIEW_COMMAND_ID_GET_MODULE:
+      Status = SEGGER_RTT_ReadNoLock(CHANNEL_ID_DOWN, &Cmd, 1);
+      if (Status > 0) {
+        SEGGER_SYSVIEW_SendModule(Cmd);
+      }
+      break;
+    case SEGGER_SYSVIEW_COMMAND_ID_HEARTBEAT:
+      break;
+    default:
+      if (Cmd >= 128) { // Unknown extended command. Dummy read its parameter.
+        SEGGER_RTT_ReadNoLock(CHANNEL_ID_DOWN, &Cmd, 1);
+      }
+      break;
+    }
+  }
+}
+#endif // (SEGGER_SYSVIEW_POST_MORTEM_MODE != 1)
+
+/*********************************************************************
+*
+*       _TrySendOverflowPacket()
+*
+*  Function description
+*    Try to transmit an SystemView Overflow packet containing the
+*    number of dropped packets.
+*
+*  Additional information
+*    Format as follows:
+*      01 <DropCnt><TimeStamp>  Max. packet len is 1 + 5 + 5 = 11
+*
+*    Example packets sent
+*      01 20 40
+*
+*  Return value
+*    !=0:  Success, Message sent (stored in RTT-Buffer)
+*    ==0:  Buffer full, Message *NOT* stored
+*
+*/
+#if (SEGGER_SYSVIEW_POST_MORTEM_MODE != 1)
+static int _TrySendOverflowPacket(void) {
+  U32 TimeStamp;
+  I32 Delta;
+  int Status;
+  U8  aPacket[11];
+  U8* pPayload;
+
+  aPacket[0] = SYSVIEW_EVTID_OVERFLOW;      // 1
+  pPayload   = &aPacket[1];
+  ENCODE_U32(pPayload, _SYSVIEW_Globals.DropCount);
+  //
+  // Compute time stamp delta and append it to packet.
+  //
+  TimeStamp  = SEGGER_SYSVIEW_GET_TIMESTAMP();
+  Delta = TimeStamp - _SYSVIEW_Globals.LastTxTimeStamp;
+  MAKE_DELTA_32BIT(Delta);
+  ENCODE_U32(pPayload, Delta);
+  //
+  // Try to store packet in RTT buffer and update time stamp when this was successful
+  //
+  Status = (int)SEGGER_RTT_WriteSkipNoLock(CHANNEL_ID_UP, aPacket, (unsigned int)(pPayload - aPacket));
+  SEGGER_SYSVIEW_ON_EVENT_RECORDED(pPayload - aPacket);
+  if (Status) {
+    _SYSVIEW_Globals.LastTxTimeStamp = TimeStamp;
+    _SYSVIEW_Globals.EnableState--; // EnableState has been 2, will be 1. Always.
+  } else {
+    _SYSVIEW_Globals.DropCount++;
+  }
+  //
+  return Status;
+}
+#endif  // (SEGGER_SYSVIEW_POST_MORTEM_MODE != 1)
+
+/*********************************************************************
+*
+*       _SendSyncInfo()
+*
+*  Function description
+*    Send SystemView sync packet and system information in
+*    post mortem mode.
+*
+*  Additional information
+*    Sync is 10 * 0x00 without timestamp
+*/
+#if (SEGGER_SYSVIEW_POST_MORTEM_MODE == 1)
+static void _SendSyncInfo(void) {
+  //
+  // Add sync packet ( 10 * 0x00)
+  // Send system description
+  // Send system time
+  // Send task list
+  // Send module description
+  // Send module information
+  //
+  SEGGER_RTT_WriteWithOverwriteNoLock(CHANNEL_ID_UP, _abSync, 10);
+  SEGGER_SYSVIEW_ON_EVENT_RECORDED(10);
+  SEGGER_SYSVIEW_RecordVoid(SYSVIEW_EVTID_TRACE_START);
+  {
+    U8* pPayload;
+    U8* pPayloadStart;
+    RECORD_START(SEGGER_SYSVIEW_INFO_SIZE + 4 * SEGGER_SYSVIEW_QUANTA_U32);
+    //
+    pPayload = pPayloadStart;
+    ENCODE_U32(pPayload, _SYSVIEW_Globals.SysFreq);
+    ENCODE_U32(pPayload, _SYSVIEW_Globals.CPUFreq);
+    ENCODE_U32(pPayload, _SYSVIEW_Globals.RAMBaseAddress);
+    ENCODE_U32(pPayload, SEGGER_SYSVIEW_ID_SHIFT);
+    _SendPacket(pPayloadStart, pPayload, SYSVIEW_EVTID_INIT);
+    RECORD_END();
+  }
+  if (_SYSVIEW_Globals.pfSendSysDesc) {
+    _SYSVIEW_Globals.pfSendSysDesc();
+  }
+  SEGGER_SYSVIEW_RecordSystime();
+  SEGGER_SYSVIEW_SendTaskList();
+  if (_NumModules > 0) {
+    int n;
+    SEGGER_SYSVIEW_SendNumModules();
+    for (n = 0; n < _NumModules; n++) {
+      SEGGER_SYSVIEW_SendModule(n);
+    }
+    SEGGER_SYSVIEW_SendModuleDescription();
+  }
+}
+#endif  // (SEGGER_SYSVIEW_POST_MORTEM_MODE == 1)
+
+/*********************************************************************
+*
+*       _SendPacket()
+*
+*  Function description
+*    Send a SystemView packet over RTT. RTT channel and mode are
+*    configured by macros when the SystemView component is initialized.
+*    This function takes care of maintaining the packet drop count
+*    and sending overflow packets when necessary.
+*    The packet must be passed without Id and Length because this
+*    function prepends it to the packet before transmission.
+*
+*  Parameters
+*    pStartPacket - Pointer to start of packet payload.
+*                   There must be at least 4 bytes free to prepend Id and Length.
+*    pEndPacket   - Pointer to end of packet payload.
+*    EventId      - Id of the event to send.
+*
+*/
+static void _SendPacket(U8* pStartPacket, U8* pEndPacket, unsigned int EventId) {
+  unsigned int  NumBytes;
+  U32           TimeStamp;
+  U32           Delta;
+#if (SEGGER_SYSVIEW_POST_MORTEM_MODE != 1)
+  unsigned int  Status;
+#endif
+
+#if (SEGGER_SYSVIEW_USE_STATIC_BUFFER == 0)
+  SEGGER_SYSVIEW_LOCK();
+#endif
+
+#if (SEGGER_SYSVIEW_POST_MORTEM_MODE == 1)
+  if (_SYSVIEW_Globals.EnableState == 0) {
+    goto SendDone;
+  }
+#else
+  if (_SYSVIEW_Globals.EnableState == 1) {  // Enabled, no dropped packets remaining
+    goto Send;
+  }
+  if (_SYSVIEW_Globals.EnableState == 0) {
+    goto SendDone;
+  }
+  //
+  // Handle buffer full situations:
+  // Have packets been dropped before because buffer was full?
+  // In this case try to send and overflow packet.
+  //
+  if (_SYSVIEW_Globals.EnableState == 2) {
+    _TrySendOverflowPacket();
+    if (_SYSVIEW_Globals.EnableState != 1) {
+      goto SendDone;
+    }
+  }
+Send:
+#endif
+  //
+  // Check if event is disabled from being recorded.
+  //
+  if (EventId < 32) {
+    if (_SYSVIEW_Globals.DisabledEvents & ((U32)1u << EventId)) {
+      goto SendDone;
+    }
+  }
+  //
+  // Prepare actual packet.
+  // If it is a known packet, prepend eventId only,
+  // otherwise prepend packet length and eventId.
+  //
+  if (EventId < 24) {
+    *--pStartPacket = (U8)EventId;
+  } else {
+    //
+    // Get data length and prepend it.
+    //
+    NumBytes = (unsigned int)(pEndPacket - pStartPacket);
+#if SEGGER_SYSVIEW_SUPPORT_LONG_DATA
+    if (NumBytes < 127) {
+      *--pStartPacket = EventId;
+    } else {
+      //
+      // Backwards U32 encode EventId.
+      //
+      if (NumBytes < (1u << 14)) { // Encodes in 2 bytes
+        *--pStartPacket = (U8)(NumBytes >>  7);
+        *--pStartPacket = (U8)(NumBytes | 0x80);
+      } else if (NumBytes < (1u << 21)) {    // Encodes in 3 bytes
+        *--pStartPacket = (U8)(NumBytes >> 14);
+        *--pStartPacket = (U8)((NumBytes >>  7) | 0x80);
+        *--pStartPacket = (U8)(NumBytes | 0x80);
+      } else if (NumBytes < (1u << 28)) {    // Encodes in 4 bytes
+        *--pStartPacket = (U8)(NumBytes >> 21);
+        *--pStartPacket = (U8)((NumBytes >> 14) | 0x80);
+        *--pStartPacket = (U8)((NumBytes >>  7) | 0x80);
+        *--pStartPacket = (U8)(NumBytes | 0x80);
+      } else {                              // Encodes in 5 bytes
+        *--pStartPacket = (U8)(NumBytes >> 28);
+        *--pStartPacket = (U8)((NumBytes >> 21) | 0x80);
+        *--pStartPacket = (U8)((NumBytes >> 14) | 0x80);
+        *--pStartPacket = (U8)((NumBytes >>  7) | 0x80);
+        *--pStartPacket = (U8)(NumBytes | 0x80);
+      }
+    }
+#else
+    if (NumBytes > 127) {
+      *--pStartPacket = (U8)(NumBytes >> 7);
+      *--pStartPacket = (U8)(NumBytes | 0x80);
+    } else {
+      *--pStartPacket = (U8)NumBytes;
+    }
+#endif
+    //
+    // Prepend EventId.
+    //
+#if SEGGER_SYSVIEW_SUPPORT_LONG_ID
+    if (EventId < 127) {
+      *--pStartPacket = (U8)EventId;
+    } else {
+      //
+      // Backwards U32 encode EventId.
+      //
+      if (EventId < (1u << 14)) { // Encodes in 2 bytes
+        *--pStartPacket = (U8)(EventId >>  7);
+        *--pStartPacket = (U8)(EventId | 0x80);
+      } else if (EventId < (1u << 21)) {    // Encodes in 3 bytes
+        *--pStartPacket = (U8)(EventId >> 14);
+        *--pStartPacket = (U8)((EventId >>  7) | 0x80);
+        *--pStartPacket = (U8)(EventId | 0x80);
+      } else if (EventId < (1u << 28)) {    // Encodes in 4 bytes
+        *--pStartPacket = (U8)(EventId >> 21);
+        *--pStartPacket = (U8)((EventId >> 14) | 0x80);
+        *--pStartPacket = (U8)((EventId >>  7) | 0x80);
+        *--pStartPacket = (U8)(EventId | 0x80);
+      } else {                              // Encodes in 5 bytes
+        *--pStartPacket = (U8)(EventId >> 28);
+        *--pStartPacket = (U8)((EventId >> 21) | 0x80);
+        *--pStartPacket = (U8)((EventId >> 14) | 0x80);
+        *--pStartPacket = (U8)((EventId >>  7) | 0x80);
+        *--pStartPacket = (U8)(EventId | 0x80);
+      }
+    }
+#else
+    if (EventId > 127) {
+      *--pStartPacket = (U8)(EventId >> 7);
+      *--pStartPacket = (U8)(EventId | 0x80);
+    } else {
+      *--pStartPacket = (U8)EventId;
+    }
+#endif
+  }
+  //
+  // Compute time stamp delta and append it to packet.
+  //
+  TimeStamp  = SEGGER_SYSVIEW_GET_TIMESTAMP();
+  Delta = TimeStamp - _SYSVIEW_Globals.LastTxTimeStamp;
+  MAKE_DELTA_32BIT(Delta);
+  ENCODE_U32(pEndPacket, Delta);
+#if (SEGGER_SYSVIEW_POST_MORTEM_MODE == 1)
+  //
+  // Store packet in RTT buffer by overwriting old data and update time stamp
+  //
+  SEGGER_RTT_WriteWithOverwriteNoLock(CHANNEL_ID_UP, pStartPacket, pEndPacket - pStartPacket);
+  SEGGER_SYSVIEW_ON_EVENT_RECORDED(pEndPacket - pStartPacket);
+  _SYSVIEW_Globals.LastTxTimeStamp = TimeStamp;
+#else
+  //
+  // Try to store packet in RTT buffer and update time stamp when this was successful
+  //
+  Status = SEGGER_RTT_WriteSkipNoLock(CHANNEL_ID_UP, pStartPacket, (unsigned int)(pEndPacket - pStartPacket));
+  SEGGER_SYSVIEW_ON_EVENT_RECORDED(pEndPacket - pStartPacket);
+  if (Status) {
+    _SYSVIEW_Globals.LastTxTimeStamp = TimeStamp;
+  } else {
+    _SYSVIEW_Globals.EnableState++; // EnableState has been 1, will be 2. Always.
+  }
+#endif
+
+#if (SEGGER_SYSVIEW_POST_MORTEM_MODE == 1)
+  //
+  // Add sync and system information periodically if we are in post mortem mode
+  //
+  if (_SYSVIEW_Globals.RecursionCnt == 0) {   // Avoid uncontrolled nesting. This way, this routine can call itself once, but no more often than that.
+    _SYSVIEW_Globals.RecursionCnt = 1;
+    if (_SYSVIEW_Globals.PacketCount++ & (1 << SEGGER_SYSVIEW_SYNC_PERIOD_SHIFT)) {
+      _SendSyncInfo();
+      _SYSVIEW_Globals.PacketCount = 0;
+    }
+    _SYSVIEW_Globals.RecursionCnt = 0;
+  }
+SendDone:
+  ; // Avoid "label at end of compound statement" error when using static buffer
+#else
+SendDone:
+  //
+  // Check if host is sending data which needs to be processed.
+  // Note that since this code is called for every packet, it is very time critical, so we do
+  // only what is really needed here, which is checking if there is any data
+  //
+  if (SEGGER_RTT_HASDATA(CHANNEL_ID_DOWN)) {
+    if (_SYSVIEW_Globals.RecursionCnt == 0) {   // Avoid uncontrolled nesting. This way, this routine can call itself once, but no more often than that.
+      _SYSVIEW_Globals.RecursionCnt = 1;
+      _HandleIncomingPacket();
+      _SYSVIEW_Globals.RecursionCnt = 0;
+    }
+  }
+#endif
+  //
+#if (SEGGER_SYSVIEW_USE_STATIC_BUFFER == 0)
+  SEGGER_SYSVIEW_UNLOCK();  // We are done. Unlock and return
+#endif
+}
+
+#ifndef SEGGER_SYSVIEW_EXCLUDE_PRINTF // Define in project to avoid warnings about variable parameter list
+/*********************************************************************
+*
+*       _VPrintHost()
+*
+*  Function description
+*    Send a format string and its parameters to the host.
+*
+*  Parameters
+*    s            Pointer to format string.
+*    Options      Options to be sent to the host.
+*    pParamList   Pointer to the list of arguments for the format string.
+*/
+static int _VPrintHost(const char* s, U32 Options, va_list* pParamList) {
+  U32         aParas[SEGGER_SYSVIEW_MAX_ARGUMENTS];
+  U32*        pParas;
+  U32         NumArguments;
+  const char* p;
+  char        c;
+  U8*         pPayload;
+  U8*         pPayloadStart;
+#if SEGGER_SYSVIEW_PRINTF_IMPLICIT_FORMAT
+  U8 HasNonScalar;
+
+  HasNonScalar = 0;
+#endif
+  //
+  // Count number of arguments by counting '%' characters in string.
+  // If enabled, check for non-scalar modifier flags to format string on the target.
+  //
+  p = s;
+  NumArguments = 0;
+  for (;;) {
+    c = *p++;
+    if (c == 0) {
+      break;
+    }
+    if (c == '%') {
+      c = *p;
+#if SEGGER_SYSVIEW_PRINTF_IMPLICIT_FORMAT == 0
+      aParas[NumArguments++] = (U32)(va_arg(*pParamList, int));
+      if (NumArguments == SEGGER_SYSVIEW_MAX_ARGUMENTS) {
+        break;
+      }
+#else
+      if (c == 's') {
+        HasNonScalar = 1;
+        break;
+      } else {
+        aParas[NumArguments++] = (U32)(va_arg(*pParamList, int));
+        if (NumArguments == SEGGER_SYSVIEW_MAX_ARGUMENTS) {
+          break;
+        }
+      }
+#endif
+    }
+  }
+
+#if SEGGER_SYSVIEW_PRINTF_IMPLICIT_FORMAT
+  if (HasNonScalar) {
+    return -1;
+  }
+#endif
+  //
+  // Send string and parameters to host
+  //
+  {
+    RECORD_START(SEGGER_SYSVIEW_INFO_SIZE + SEGGER_SYSVIEW_MAX_STRING_LEN + 2 * SEGGER_SYSVIEW_QUANTA_U32 + SEGGER_SYSVIEW_MAX_ARGUMENTS * SEGGER_SYSVIEW_QUANTA_U32);
+    pPayload = _EncodeStr(pPayloadStart, s, SEGGER_SYSVIEW_MAX_STRING_LEN);
+    ENCODE_U32(pPayload, Options);
+    ENCODE_U32(pPayload, NumArguments);
+    pParas = aParas;
+    while (NumArguments--) {
+      ENCODE_U32(pPayload, (*pParas));
+      pParas++;
+    }
+    _SendPacket(pPayloadStart, pPayload, SYSVIEW_EVTID_PRINT_FORMATTED);
+    RECORD_END();
+  }
+  return 0;
+}
+
+/*********************************************************************
+*
+*       _StoreChar()
+*
+*  Function description
+*    Stores a character in the printf-buffer and sends the buffer when
+*     it is filled.
+*
+*  Parameters
+*    p            Pointer to the buffer description.
+*    c            Character to be printed.
+*/
+static void _StoreChar(SEGGER_SYSVIEW_PRINTF_DESC * p, char c) {
+  unsigned int  Cnt;
+  U8*           pPayload;
+  U32           Options;
+
+  Cnt = p->Cnt;
+  if ((Cnt + 1u) <= SEGGER_SYSVIEW_MAX_STRING_LEN) {
+    *(p->pPayload++) = (U8)c;
+    p->Cnt = Cnt + 1u;
+  }
+  //
+  // Write part of string, when the buffer is full
+  //
+  if (p->Cnt == SEGGER_SYSVIEW_MAX_STRING_LEN) {
+    *(p->pPayloadStart) = (U8)p->Cnt;
+    pPayload = p->pPayload;
+    Options = p->Options;
+    ENCODE_U32(pPayload, Options);
+    ENCODE_U32(pPayload, 0);
+    _SendPacket(p->pPayloadStart, pPayload, SYSVIEW_EVTID_PRINT_FORMATTED);
+    p->pPayloadStart = _PreparePacket(p->pBuffer);
+    p->pPayload = p->pPayloadStart + 1u;
+    p->Cnt = 0u;
+  }
+}
+
+/*********************************************************************
+*
+*       _PrintUnsigned()
+*
+*  Function description
+*    Print an unsigned integer with the given formatting into the
+*     formatted string.
+*
+*  Parameters
+*    pBufferDesc  Pointer to the buffer description.
+*    v            Value to be printed.
+*    Base         Base of the value.
+*    NumDigits    Number of digits to be printed.
+*    FieldWidth   Width of the printed field.
+*    FormatFlags  Flags for formatting the value.
+*/
+static void _PrintUnsigned(SEGGER_SYSVIEW_PRINTF_DESC * pBufferDesc, unsigned int v, unsigned int Base, unsigned int NumDigits, unsigned int FieldWidth, unsigned int FormatFlags) {
+  static const char _aV2C[16] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
+  unsigned int      Div;
+  unsigned int      Digit;
+  unsigned int      Number;
+  unsigned int      Width;
+  char              c;
+
+  Number = v;
+  Digit = 1u;
+  //
+  // Get actual field width
+  //
+  Width = 1u;
+  while (Number >= Base) {
+    Number = (Number / Base);
+    Width++;
+  }
+  if (NumDigits > Width) {
+    Width = NumDigits;
+  }
+  //
+  // Print leading chars if necessary
+  //
+  if ((FormatFlags & FORMAT_FLAG_LEFT_JUSTIFY) == 0u) {
+    if (FieldWidth != 0u) {
+      if (((FormatFlags & FORMAT_FLAG_PAD_ZERO) == FORMAT_FLAG_PAD_ZERO) && (NumDigits == 0u)) {
+        c = '0';
+      } else {
+        c = ' ';
+      }
+      while ((FieldWidth != 0u) && (Width < FieldWidth)) {
+        FieldWidth--;
+        _StoreChar(pBufferDesc, c);
+      }
+    }
+  }
+  //
+  // Compute Digit.
+  // Loop until Digit has the value of the highest digit required.
+  // Example: If the output is 345 (Base 10), loop 2 times until Digit is 100.
+  //
+  while (1) {
+    if (NumDigits > 1u) {       // User specified a min number of digits to print? => Make sure we loop at least that often, before checking anything else (> 1 check avoids problems with NumDigits being signed / unsigned)
+      NumDigits--;
+    } else {
+      Div = v / Digit;
+      if (Div < Base) {        // Is our divider big enough to extract the highest digit from value? => Done
+        break;
+      }
+    }
+    Digit *= Base;
+  }
+  //
+  // Output digits
+  //
+  do {
+    Div = v / Digit;
+    v -= Div * Digit;
+    _StoreChar(pBufferDesc, _aV2C[Div]);
+    Digit /= Base;
+  } while (Digit);
+  //
+  // Print trailing spaces if necessary
+  //
+  if ((FormatFlags & FORMAT_FLAG_LEFT_JUSTIFY) == FORMAT_FLAG_LEFT_JUSTIFY) {
+    if (FieldWidth != 0u) {
+      while ((FieldWidth != 0u) && (Width < FieldWidth)) {
+        FieldWidth--;
+        _StoreChar(pBufferDesc, ' ');
+      }
+    }
+  }
+}
+
+/*********************************************************************
+*
+*       _PrintInt()
+*
+*  Function description
+*    Print a signed integer with the given formatting into the
+*     formatted string.
+*
+*  Parameters
+*    pBufferDesc  Pointer to the buffer description.
+*    v            Value to be printed.
+*    Base         Base of the value.
+*    NumDigits    Number of digits to be printed.
+*    FieldWidth   Width of the printed field.
+*    FormatFlags  Flags for formatting the value.
+*/
+static void _PrintInt(SEGGER_SYSVIEW_PRINTF_DESC * pBufferDesc, int v, unsigned int Base, unsigned int NumDigits, unsigned int FieldWidth, unsigned int FormatFlags) {
+  unsigned int  Width;
+  int           Number;
+
+  Number = (v < 0) ? -v : v;
+
+  //
+  // Get actual field width
+  //
+  Width = 1u;
+  while (Number >= (int)Base) {
+    Number = (Number / (int)Base);
+    Width++;
+  }
+  if (NumDigits > Width) {
+    Width = NumDigits;
+  }
+  if ((FieldWidth > 0u) && ((v < 0) || ((FormatFlags & FORMAT_FLAG_PRINT_SIGN) == FORMAT_FLAG_PRINT_SIGN))) {
+    FieldWidth--;
+  }
+
+  //
+  // Print leading spaces if necessary
+  //
+  if ((((FormatFlags & FORMAT_FLAG_PAD_ZERO) == 0u) || (NumDigits != 0u)) && ((FormatFlags & FORMAT_FLAG_LEFT_JUSTIFY) == 0u)) {
+    if (FieldWidth != 0u) {
+      while ((FieldWidth != 0u) && (Width < FieldWidth)) {
+        FieldWidth--;
+        _StoreChar(pBufferDesc, ' ');
+      }
+    }
+  }
+  //
+  // Print sign if necessary
+  //
+  if (v < 0) {
+    v = -v;
+    _StoreChar(pBufferDesc, '-');
+  } else if ((FormatFlags & FORMAT_FLAG_PRINT_SIGN) == FORMAT_FLAG_PRINT_SIGN) {
+    _StoreChar(pBufferDesc, '+');
+  } else {
+
+  }
+  //
+  // Print leading zeros if necessary
+  //
+  if (((FormatFlags & FORMAT_FLAG_PAD_ZERO) == FORMAT_FLAG_PAD_ZERO) && ((FormatFlags & FORMAT_FLAG_LEFT_JUSTIFY) == 0u) && (NumDigits == 0u)) {
+    if (FieldWidth != 0u) {
+      while ((FieldWidth != 0u) && (Width < FieldWidth)) {
+        FieldWidth--;
+        _StoreChar(pBufferDesc, '0');
+      }
+    }
+  }
+  //
+  // Print number without sign
+  //
+  _PrintUnsigned(pBufferDesc, (unsigned int)v, Base, NumDigits, FieldWidth, FormatFlags);
+}
+
+/*********************************************************************
+*
+*       _VPrintTarget()
+*
+*  Function description
+*    Stores a formatted string.
+*    This data is read by the host.
+*
+*  Parameters
+*    sFormat      Pointer to format string.
+*    Options      Options to be sent to the host.
+*    pParamList   Pointer to the list of arguments for the format string.
+*/
+static void _VPrintTarget(const char* sFormat, U32 Options, va_list* pParamList) {
+  SEGGER_SYSVIEW_PRINTF_DESC BufferDesc;
+  char          c;
+  int           v;
+  unsigned int  NumDigits;
+  unsigned int  FormatFlags;
+  unsigned int  FieldWidth;
+  U8*           pPayloadStart;
+#if SEGGER_SYSVIEW_USE_STATIC_BUFFER == 0
+  RECORD_START(SEGGER_SYSVIEW_INFO_SIZE + SEGGER_SYSVIEW_MAX_STRING_LEN + 1 + 2 * SEGGER_SYSVIEW_QUANTA_U32);
+  SEGGER_SYSVIEW_LOCK();
+#else
+  RECORD_START(SEGGER_SYSVIEW_INFO_SIZE + SEGGER_SYSVIEW_MAX_STRING_LEN + 1 + 2 * SEGGER_SYSVIEW_QUANTA_U32);
+#endif
+
+#if SEGGER_SYSVIEW_USE_STATIC_BUFFER == 0
+  BufferDesc.pBuffer        = aPacket;
+#else
+  BufferDesc.pBuffer        = _aPacket;
+#endif
+  BufferDesc.Cnt            = 0u;
+  BufferDesc.pPayloadStart  = pPayloadStart;
+  BufferDesc.pPayload       = BufferDesc.pPayloadStart + 1u;
+  BufferDesc.Options        =  Options;
+
+  do {
+    c = *sFormat;
+    sFormat++;
+    if (c == 0u) {
+      break;
+    }
+    if (c == '%') {
+      //
+      // Filter out flags
+      //
+      FormatFlags = 0u;
+      v = 1;
+      do {
+        c = *sFormat;
+        switch (c) {
+        case '-': FormatFlags |= FORMAT_FLAG_LEFT_JUSTIFY; sFormat++; break;
+        case '0': FormatFlags |= FORMAT_FLAG_PAD_ZERO;     sFormat++; break;
+        case '+': FormatFlags |= FORMAT_FLAG_PRINT_SIGN;   sFormat++; break;
+        case '#': FormatFlags |= FORMAT_FLAG_ALTERNATE;    sFormat++; break;
+        default:  v = 0; break;
+        }
+      } while (v);
+      //
+      // filter out field with
+      //
+      FieldWidth = 0u;
+      do {
+        c = *sFormat;
+        if ((c < '0') || (c > '9')) {
+          break;
+        }
+        sFormat++;
+        FieldWidth = (FieldWidth * 10u) + ((unsigned int)c - '0');
+      } while (1);
+
+      //
+      // Filter out precision (number of digits to display)
+      //
+      NumDigits = 0u;
+      c = *sFormat;
+      if (c == '.') {
+        sFormat++;
+        do {
+          c = *sFormat;
+          if ((c < '0') || (c > '9')) {
+            break;
+          }
+          sFormat++;
+          NumDigits = NumDigits * 10u + ((unsigned int)c - '0');
+        } while (1);
+      }
+      //
+      // Filter out length modifier
+      //
+      c = *sFormat;
+      do {
+        if ((c == 'l') || (c == 'h')) {
+          c = *sFormat;
+          sFormat++;
+        } else {
+          break;
+        }
+      } while (1);
+      //
+      // Handle specifiers
+      //
+      switch (c) {
+      case 'c': {
+        char c0;
+        v = va_arg(*pParamList, int);
+        c0 = (char)v;
+        _StoreChar(&BufferDesc, c0);
+        break;
+      }
+      case 'd':
+        v = va_arg(*pParamList, int);
+        _PrintInt(&BufferDesc, v, 10u, NumDigits, FieldWidth, FormatFlags);
+        break;
+      case 'u':
+        v = va_arg(*pParamList, int);
+        _PrintUnsigned(&BufferDesc, (unsigned int)v, 10u, NumDigits, FieldWidth, FormatFlags);
+        break;
+      case 'x':
+      case 'X':
+        v = va_arg(*pParamList, int);
+        _PrintUnsigned(&BufferDesc, (unsigned int)v, 16u, NumDigits, FieldWidth, FormatFlags);
+        break;
+      case 'p':
+        v = va_arg(*pParamList, int);
+        _PrintUnsigned(&BufferDesc, (unsigned int)v, 16u, 8u, 8u, 0u);
+        break;
+      case '%':
+        _StoreChar(&BufferDesc, '%');
+        break;
+      default:
+        break;
+      }
+      sFormat++;
+    } else {
+      _StoreChar(&BufferDesc, c);
+    }
+  } while (*sFormat);
+
+  //
+  // Write remaining data, if any
+  //
+  if (BufferDesc.Cnt != 0u) {
+    *(BufferDesc.pPayloadStart) = (U8)BufferDesc.Cnt;
+    ENCODE_U32(BufferDesc.pPayload, BufferDesc.Options);
+    ENCODE_U32(BufferDesc.pPayload, 0);
+    _SendPacket(BufferDesc.pPayloadStart, BufferDesc.pPayload, SYSVIEW_EVTID_PRINT_FORMATTED);
+  }
+#if SEGGER_SYSVIEW_USE_STATIC_BUFFER == 0
+  SEGGER_SYSVIEW_UNLOCK();
+  RECORD_END();
+#else
+  RECORD_END();
+#endif
+}
+#endif // SEGGER_SYSVIEW_EXCLUDE_PRINTF
+
+/*********************************************************************
+*
+*       Public code
+*
+**********************************************************************
+*/
+
+/*********************************************************************
+*
+*       SEGGER_SYSVIEW_Init()
+*
+*  Function description
+*    Initializes the SYSVIEW module.
+*    Must be called before the Systemview Application connects to
+*    the system.
+*
+*  Parameters
+*    SysFreq        - Frequency of timestamp, usually CPU core clock frequency.
+*    CPUFreq        - CPU core clock frequency.
+*    pOSAPI         - Pointer to the API structure for OS-specific functions.
+*    pfSendSysDesc  - Pointer to record system description callback function.
+*
+*  Additional information
+*    This function initializes the RTT channel used to transport
+*    SEGGER SystemView packets.
+*    The channel is assigned the label "SysView" for client software
+*    to identify the SystemView channel.
+*
+*    The channel is configured with the macro SEGGER_SYSVIEW_RTT_CHANNEL.
+*/
+void SEGGER_SYSVIEW_Init(U32 SysFreq, U32 CPUFreq, const SEGGER_SYSVIEW_OS_API *pOSAPI, SEGGER_SYSVIEW_SEND_SYS_DESC_FUNC pfSendSysDesc) {
+#ifdef SEGGER_RTT_SECTION
+  //
+  // Explicitly initialize the RTT Control Block if it is in its dedicated section.
+  //
+  SEGGER_RTT_Init();
+#endif
+#if (SEGGER_SYSVIEW_POST_MORTEM_MODE == 1)
+#if SEGGER_SYSVIEW_RTT_CHANNEL > 0
+  SEGGER_RTT_ConfigUpBuffer(SEGGER_SYSVIEW_RTT_CHANNEL, "SysView", &_UpBuffer[0],   sizeof(_UpBuffer),   SEGGER_RTT_MODE_NO_BLOCK_SKIP);
+#else
+  _SYSVIEW_Globals.UpChannel = (U8)SEGGER_RTT_AllocUpBuffer  ("SysView", &_UpBuffer[0],   sizeof(_UpBuffer),   SEGGER_RTT_MODE_NO_BLOCK_SKIP);
+#endif
+  _SYSVIEW_Globals.RAMBaseAddress   = SEGGER_SYSVIEW_ID_BASE;
+  _SYSVIEW_Globals.LastTxTimeStamp  = SEGGER_SYSVIEW_GET_TIMESTAMP();
+  _SYSVIEW_Globals.pOSAPI           = pOSAPI;
+  _SYSVIEW_Globals.SysFreq          = SysFreq;
+  _SYSVIEW_Globals.CPUFreq          = CPUFreq;
+  _SYSVIEW_Globals.pfSendSysDesc    = pfSendSysDesc;
+  _SYSVIEW_Globals.EnableState      = 0;
+  _SYSVIEW_Globals.PacketCount      = 0;
+#else // (SEGGER_SYSVIEW_POST_MORTEM_MODE == 1)
+#if SEGGER_SYSVIEW_RTT_CHANNEL > 0
+  SEGGER_RTT_ConfigUpBuffer   (SEGGER_SYSVIEW_RTT_CHANNEL, "SysView", &_UpBuffer[0],   sizeof(_UpBuffer),   SEGGER_RTT_MODE_NO_BLOCK_SKIP);
+  SEGGER_RTT_ConfigDownBuffer (SEGGER_SYSVIEW_RTT_CHANNEL, "SysView", &_DownBuffer[0], sizeof(_DownBuffer), SEGGER_RTT_MODE_NO_BLOCK_SKIP);
+#else
+  _SYSVIEW_Globals.UpChannel = (U8)SEGGER_RTT_AllocUpBuffer  ("SysView", &_UpBuffer[0],   sizeof(_UpBuffer),   SEGGER_RTT_MODE_NO_BLOCK_SKIP);
+  _SYSVIEW_Globals.DownChannel = _SYSVIEW_Globals.UpChannel;
+  SEGGER_RTT_ConfigDownBuffer (_SYSVIEW_Globals.DownChannel, "SysView", &_DownBuffer[0], sizeof(_DownBuffer), SEGGER_RTT_MODE_NO_BLOCK_SKIP);
+#endif
+  _SYSVIEW_Globals.RAMBaseAddress   = SEGGER_SYSVIEW_ID_BASE;
+  _SYSVIEW_Globals.LastTxTimeStamp  = SEGGER_SYSVIEW_GET_TIMESTAMP();
+  _SYSVIEW_Globals.pOSAPI           = pOSAPI;
+  _SYSVIEW_Globals.SysFreq          = SysFreq;
+  _SYSVIEW_Globals.CPUFreq          = CPUFreq;
+  _SYSVIEW_Globals.pfSendSysDesc    = pfSendSysDesc;
+  _SYSVIEW_Globals.EnableState      = 0;
+#endif  // (SEGGER_SYSVIEW_POST_MORTEM_MODE == 1)
+}
+
+/*********************************************************************
+*
+*       SEGGER_SYSVIEW_SetRAMBase()
+*
+*  Function description
+*    Sets the RAM base address, which is subtracted from IDs in order
+*     to save bandwidth.
+*
+*  Parameters
+*    RAMBaseAddress - Lowest RAM Address. (i.e. 0x20000000 on most Cortex-M)
+*/
+void SEGGER_SYSVIEW_SetRAMBase(U32 RAMBaseAddress) {
+  _SYSVIEW_Globals.RAMBaseAddress = RAMBaseAddress;
+}
+
+/*********************************************************************
+*
+*       SEGGER_SYSVIEW_RecordVoid()
+*
+*  Function description
+*    Formats and sends a SystemView packet with an empty payload.
+*
+*  Parameters
+*    EventID - SystemView event ID.
+*/
+void SEGGER_SYSVIEW_RecordVoid(unsigned int EventID) {
+  U8* pPayloadStart;
+  RECORD_START(SEGGER_SYSVIEW_INFO_SIZE);
+  //
+  _SendPacket(pPayloadStart, pPayloadStart, EventID);
+  RECORD_END();
+}
+
+/*********************************************************************
+*
+*       SEGGER_SYSVIEW_RecordU32()
+*
+*  Function description
+*    Formats and sends a SystemView packet containing a single U32
+*    parameter payload.
+*
+*  Parameters
+*    EventID - SystemView event ID.
+*    Value   - The 32-bit parameter encoded to SystemView packet payload.
+*/
+void SEGGER_SYSVIEW_RecordU32(unsigned int EventID, U32 Value) {
+  U8* pPayload;
+  U8* pPayloadStart;
+  RECORD_START(SEGGER_SYSVIEW_INFO_SIZE + SEGGER_SYSVIEW_QUANTA_U32);
+  //
+  pPayload = pPayloadStart;
+  ENCODE_U32(pPayload, Value);
+  _SendPacket(pPayloadStart, pPayload, EventID);
+  RECORD_END();
+}
+
+/*********************************************************************
+*
+*       SEGGER_SYSVIEW_RecordU32x2()
+*
+*  Function description
+*    Formats and sends a SystemView packet containing 2 U32 parameter payload.
+*
+*  Parameters
+*    EventID - SystemView event ID.
+*    Para0   - The 32-bit parameter encoded to SystemView packet payload.
+*    Para1   - The 32-bit parameter encoded to SystemView packet payload.
+*/
+void SEGGER_SYSVIEW_RecordU32x2(unsigned int EventID, U32 Para0, U32 Para1) {
+  U8* pPayload;
+  U8* pPayloadStart;
+  RECORD_START(SEGGER_SYSVIEW_INFO_SIZE + 2 * SEGGER_SYSVIEW_QUANTA_U32);
+  //
+  pPayload = pPayloadStart;
+  ENCODE_U32(pPayload, Para0);
+  ENCODE_U32(pPayload, Para1);
+  _SendPacket(pPayloadStart, pPayload, EventID);
+  RECORD_END();
+}
+
+/*********************************************************************
+*
+*       SEGGER_SYSVIEW_RecordU32x3()
+*
+*  Function description
+*    Formats and sends a SystemView packet containing 3 U32 parameter payload.
+*
+*  Parameters
+*    EventID - SystemView event ID.
+*    Para0   - The 32-bit parameter encoded to SystemView packet payload.
+*    Para1   - The 32-bit parameter encoded to SystemView packet payload.
+*    Para2   - The 32-bit parameter encoded to SystemView packet payload.
+*/
+void SEGGER_SYSVIEW_RecordU32x3(unsigned int EventID, U32 Para0, U32 Para1, U32 Para2) {
+  U8* pPayload;
+  U8* pPayloadStart;
+  RECORD_START(SEGGER_SYSVIEW_INFO_SIZE + 3 * SEGGER_SYSVIEW_QUANTA_U32);
+  //
+  pPayload = pPayloadStart;
+  ENCODE_U32(pPayload, Para0);
+  ENCODE_U32(pPayload, Para1);
+  ENCODE_U32(pPayload, Para2);
+  _SendPacket(pPayloadStart, pPayload, EventID);
+  RECORD_END();
+}
+
+/*********************************************************************
+*
+*       SEGGER_SYSVIEW_RecordU32x4()
+*
+*  Function description
+*    Formats and sends a SystemView packet containing 4 U32 parameter payload.
+*
+*  Parameters
+*    EventID - SystemView event ID.
+*    Para0   - The 32-bit parameter encoded to SystemView packet payload.
+*    Para1   - The 32-bit parameter encoded to SystemView packet payload.
+*    Para2   - The 32-bit parameter encoded to SystemView packet payload.
+*    Para3   - The 32-bit parameter encoded to SystemView packet payload.
+*/
+void SEGGER_SYSVIEW_RecordU32x4(unsigned int EventID, U32 Para0, U32 Para1, U32 Para2, U32 Para3) {
+  U8* pPayload;
+  U8* pPayloadStart;
+  RECORD_START(SEGGER_SYSVIEW_INFO_SIZE + 4 * SEGGER_SYSVIEW_QUANTA_U32);
+  //
+  pPayload = pPayloadStart;
+  ENCODE_U32(pPayload, Para0);
+  ENCODE_U32(pPayload, Para1);
+  ENCODE_U32(pPayload, Para2);
+  ENCODE_U32(pPayload, Para3);
+  _SendPacket(pPayloadStart, pPayload, EventID);
+  RECORD_END();
+}
+
+/*********************************************************************
+*
+*       SEGGER_SYSVIEW_RecordU32x5()
+*
+*  Function description
+*    Formats and sends a SystemView packet containing 5 U32 parameter payload.
+*
+*  Parameters
+*    EventID - SystemView event ID.
+*    Para0   - The 32-bit parameter encoded to SystemView packet payload.
+*    Para1   - The 32-bit parameter encoded to SystemView packet payload.
+*    Para2   - The 32-bit parameter encoded to SystemView packet payload.
+*    Para3   - The 32-bit parameter encoded to SystemView packet payload.
+*    Para4   - The 32-bit parameter encoded to SystemView packet payload.
+*/
+void SEGGER_SYSVIEW_RecordU32x5(unsigned int EventID, U32 Para0, U32 Para1, U32 Para2, U32 Para3, U32 Para4) {
+  U8* pPayload;
+  U8* pPayloadStart;
+  RECORD_START(SEGGER_SYSVIEW_INFO_SIZE + 5 * SEGGER_SYSVIEW_QUANTA_U32);
+  //
+  pPayload = pPayloadStart;
+  ENCODE_U32(pPayload, Para0);
+  ENCODE_U32(pPayload, Para1);
+  ENCODE_U32(pPayload, Para2);
+  ENCODE_U32(pPayload, Para3);
+  ENCODE_U32(pPayload, Para4);
+  _SendPacket(pPayloadStart, pPayload, EventID);
+  RECORD_END();
+}
+
+/*********************************************************************
+*
+*       SEGGER_SYSVIEW_RecordU32x6()
+*
+*  Function description
+*    Formats and sends a SystemView packet containing 6 U32 parameter payload.
+*
+*  Parameters
+*    EventID - SystemView event ID.
+*    Para0   - The 32-bit parameter encoded to SystemView packet payload.
+*    Para1   - The 32-bit parameter encoded to SystemView packet payload.
+*    Para2   - The 32-bit parameter encoded to SystemView packet payload.
+*    Para3   - The 32-bit parameter encoded to SystemView packet payload.
+*    Para4   - The 32-bit parameter encoded to SystemView packet payload.
+*    Para5   - The 32-bit parameter encoded to SystemView packet payload.
+*/
+void SEGGER_SYSVIEW_RecordU32x6(unsigned int EventID, U32 Para0, U32 Para1, U32 Para2, U32 Para3, U32 Para4, U32 Para5) {
+  U8* pPayload;
+  U8* pPayloadStart;
+  RECORD_START(SEGGER_SYSVIEW_INFO_SIZE + 6 * SEGGER_SYSVIEW_QUANTA_U32);
+  //
+  pPayload = pPayloadStart;
+  ENCODE_U32(pPayload, Para0);
+  ENCODE_U32(pPayload, Para1);
+  ENCODE_U32(pPayload, Para2);
+  ENCODE_U32(pPayload, Para3);
+  ENCODE_U32(pPayload, Para4);
+  ENCODE_U32(pPayload, Para5);
+  _SendPacket(pPayloadStart, pPayload, EventID);
+  RECORD_END();
+}
+
+/*********************************************************************
+*
+*       SEGGER_SYSVIEW_RecordU32x7()
+*
+*  Function description
+*    Formats and sends a SystemView packet containing 7 U32 parameter payload.
+*
+*  Parameters
+*    EventID - SystemView event ID.
+*    Para0   - The 32-bit parameter encoded to SystemView packet payload.
+*    Para1   - The 32-bit parameter encoded to SystemView packet payload.
+*    Para2   - The 32-bit parameter encoded to SystemView packet payload.
+*    Para3   - The 32-bit parameter encoded to SystemView packet payload.
+*    Para4   - The 32-bit parameter encoded to SystemView packet payload.
+*    Para5   - The 32-bit parameter encoded to SystemView packet payload.
+*    Para6   - The 32-bit parameter encoded to SystemView packet payload.
+*/
+void SEGGER_SYSVIEW_RecordU32x7(unsigned int EventID, U32 Para0, U32 Para1, U32 Para2, U32 Para3, U32 Para4, U32 Para5, U32 Para6) {
+  U8* pPayload;
+  U8* pPayloadStart;
+  RECORD_START(SEGGER_SYSVIEW_INFO_SIZE + 7 * SEGGER_SYSVIEW_QUANTA_U32);
+  //
+  pPayload = pPayloadStart;
+  ENCODE_U32(pPayload, Para0);
+  ENCODE_U32(pPayload, Para1);
+  ENCODE_U32(pPayload, Para2);
+  ENCODE_U32(pPayload, Para3);
+  ENCODE_U32(pPayload, Para4);
+  ENCODE_U32(pPayload, Para5);
+  ENCODE_U32(pPayload, Para6);
+  _SendPacket(pPayloadStart, pPayload, EventID);
+  RECORD_END();
+}
+
+/*********************************************************************
+*
+*       SEGGER_SYSVIEW_RecordU32x8()
+*
+*  Function description
+*    Formats and sends a SystemView packet containing 8 U32 parameter payload.
+*
+*  Parameters
+*    EventID - SystemView event ID.
+*    Para0   - The 32-bit parameter encoded to SystemView packet payload.
+*    Para1   - The 32-bit parameter encoded to SystemView packet payload.
+*    Para2   - The 32-bit parameter encoded to SystemView packet payload.
+*    Para3   - The 32-bit parameter encoded to SystemView packet payload.
+*    Para4   - The 32-bit parameter encoded to SystemView packet payload.
+*    Para5   - The 32-bit parameter encoded to SystemView packet payload.
+*    Para6   - The 32-bit parameter encoded to SystemView packet payload.
+*    Para7   - The 32-bit parameter encoded to SystemView packet payload.
+*/
+void SEGGER_SYSVIEW_RecordU32x8(unsigned int EventID, U32 Para0, U32 Para1, U32 Para2, U32 Para3, U32 Para4, U32 Para5, U32 Para6, U32 Para7) {
+  U8* pPayload;
+  U8* pPayloadStart;
+  RECORD_START(SEGGER_SYSVIEW_INFO_SIZE + 8 * SEGGER_SYSVIEW_QUANTA_U32);
+  //
+  pPayload = pPayloadStart;
+  ENCODE_U32(pPayload, Para0);
+  ENCODE_U32(pPayload, Para1);
+  ENCODE_U32(pPayload, Para2);
+  ENCODE_U32(pPayload, Para3);
+  ENCODE_U32(pPayload, Para4);
+  ENCODE_U32(pPayload, Para5);
+  ENCODE_U32(pPayload, Para6);
+  ENCODE_U32(pPayload, Para7);
+  _SendPacket(pPayloadStart, pPayload, EventID);
+  RECORD_END();
+}
+
+/*********************************************************************
+*
+*       SEGGER_SYSVIEW_RecordU32x9()
+*
+*  Function description
+*    Formats and sends a SystemView packet containing 9 U32 parameter payload.
+*
+*  Parameters
+*    EventID - SystemView event ID.
+*    Para0   - The 32-bit parameter encoded to SystemView packet payload.
+*    Para1   - The 32-bit parameter encoded to SystemView packet payload.
+*    Para2   - The 32-bit parameter encoded to SystemView packet payload.
+*    Para3   - The 32-bit parameter encoded to SystemView packet payload.
+*    Para4   - The 32-bit parameter encoded to SystemView packet payload.
+*    Para5   - The 32-bit parameter encoded to SystemView packet payload.
+*    Para6   - The 32-bit parameter encoded to SystemView packet payload.
+*    Para7   - The 32-bit parameter encoded to SystemView packet payload.
+*    Para8   - The 32-bit parameter encoded to SystemView packet payload.
+*/
+void SEGGER_SYSVIEW_RecordU32x9(unsigned int EventID, U32 Para0, U32 Para1, U32 Para2, U32 Para3, U32 Para4, U32 Para5, U32 Para6, U32 Para7, U32 Para8) {
+  U8* pPayload;
+  U8* pPayloadStart;
+  RECORD_START(SEGGER_SYSVIEW_INFO_SIZE + 9 * SEGGER_SYSVIEW_QUANTA_U32);
+  //
+  pPayload = pPayloadStart;
+  ENCODE_U32(pPayload, Para0);
+  ENCODE_U32(pPayload, Para1);
+  ENCODE_U32(pPayload, Para2);
+  ENCODE_U32(pPayload, Para3);
+  ENCODE_U32(pPayload, Para4);
+  ENCODE_U32(pPayload, Para5);
+  ENCODE_U32(pPayload, Para6);
+  ENCODE_U32(pPayload, Para7);
+  ENCODE_U32(pPayload, Para8);
+  _SendPacket(pPayloadStart, pPayload, EventID);
+  RECORD_END();
+}
+
+/*********************************************************************
+*
+*       SEGGER_SYSVIEW_RecordU32x10()
+*
+*  Function description
+*    Formats and sends a SystemView packet containing 10 U32 parameter payload.
+*
+*  Parameters
+*    EventID - SystemView event ID.
+*    Para0   - The 32-bit parameter encoded to SystemView packet payload.
+*    Para1   - The 32-bit parameter encoded to SystemView packet payload.
+*    Para2   - The 32-bit parameter encoded to SystemView packet payload.
+*    Para3   - The 32-bit parameter encoded to SystemView packet payload.
+*    Para4   - The 32-bit parameter encoded to SystemView packet payload.
+*    Para5   - The 32-bit parameter encoded to SystemView packet payload.
+*    Para6   - The 32-bit parameter encoded to SystemView packet payload.
+*    Para7   - The 32-bit parameter encoded to SystemView packet payload.
+*    Para8   - The 32-bit parameter encoded to SystemView packet payload.
+*    Para9   - The 32-bit parameter encoded to SystemView packet payload.
+*/
+void SEGGER_SYSVIEW_RecordU32x10(unsigned int EventID, U32 Para0, U32 Para1, U32 Para2, U32 Para3, U32 Para4, U32 Para5, U32 Para6, U32 Para7, U32 Para8, U32 Para9) {
+  U8* pPayload;
+  U8* pPayloadStart;
+  RECORD_START(SEGGER_SYSVIEW_INFO_SIZE + 10 * SEGGER_SYSVIEW_QUANTA_U32);
+  //
+  pPayload = pPayloadStart;
+  ENCODE_U32(pPayload, Para0);
+  ENCODE_U32(pPayload, Para1);
+  ENCODE_U32(pPayload, Para2);
+  ENCODE_U32(pPayload, Para3);
+  ENCODE_U32(pPayload, Para4);
+  ENCODE_U32(pPayload, Para5);
+  ENCODE_U32(pPayload, Para6);
+  ENCODE_U32(pPayload, Para7);
+  ENCODE_U32(pPayload, Para8);
+  ENCODE_U32(pPayload, Para9);
+  _SendPacket(pPayloadStart, pPayload, EventID);
+  RECORD_END();
+}
+/*********************************************************************
+*
+*       SEGGER_SYSVIEW_RecordString()
+*
+*  Function description
+*    Formats and sends a SystemView packet containing a string.
+*
+*  Parameters
+*    EventID - SystemView event ID.
+*    pString - The string to be sent in the SystemView packet payload.
+*
+*  Additional information
+*    The string is encoded as a count byte followed by the contents
+*    of the string.
+*    No more than SEGGER_SYSVIEW_MAX_STRING_LEN bytes will be encoded to the payload.
+*/
+void SEGGER_SYSVIEW_RecordString(unsigned int EventID, const char* pString) {
+  U8* pPayload;
+  U8* pPayloadStart;
+  RECORD_START(SEGGER_SYSVIEW_INFO_SIZE + 1 + SEGGER_SYSVIEW_MAX_STRING_LEN);
+  //
+  pPayload = _EncodeStr(pPayloadStart, pString, SEGGER_SYSVIEW_MAX_STRING_LEN);
+  _SendPacket(pPayloadStart, pPayload, EventID);
+  RECORD_END();
+}
+
+/*********************************************************************
+*
+*       SEGGER_SYSVIEW_Start()
+*
+*  Function description
+*    Start recording SystemView events.
+*
+*    This function is triggered by the SystemView Application on connect.
+*    For single-shot or post-mortem mode recording, it needs to be called
+*    by the application.
+*
+*  Additional information
+*    This function enables transmission of SystemView packets recorded
+*    by subsequent trace calls and records a SystemView Start event.
+*
+*    As part of start, a SystemView Init packet is sent, containing the system
+*    frequency. The list of current tasks, the current system time and the
+*    system description string is sent, too.
+*
+*  Notes
+*    SEGGER_SYSVIEW_Start and SEGGER_SYSVIEW_Stop do not nest.
+*    When SEGGER_SYSVIEW_CAN_RESTART is 1, each received start command
+*    records the system information. This is required to enable restart
+*    of recordings when SystemView unexpectedly disconnects without sending
+*    a stop command before.
+*/
+void SEGGER_SYSVIEW_Start(void) {
+#if (SEGGER_SYSVIEW_CAN_RESTART == 0)
+  if (_SYSVIEW_Globals.EnableState == 0) {
+#endif
+    _SYSVIEW_Globals.EnableState = 1;
+#if (SEGGER_SYSVIEW_POST_MORTEM_MODE == 1)
+    _SendSyncInfo();
+#else
+    SEGGER_SYSVIEW_LOCK();
+    SEGGER_RTT_WriteSkipNoLock(CHANNEL_ID_UP, _abSync, 10);
+    SEGGER_SYSVIEW_UNLOCK();
+    SEGGER_SYSVIEW_ON_EVENT_RECORDED(10);
+    SEGGER_SYSVIEW_RecordVoid(SYSVIEW_EVTID_TRACE_START);
+    {
+      U8* pPayload;
+      U8* pPayloadStart;
+      RECORD_START(SEGGER_SYSVIEW_INFO_SIZE + 4 * SEGGER_SYSVIEW_QUANTA_U32);
+      //
+      pPayload = pPayloadStart;
+      ENCODE_U32(pPayload, _SYSVIEW_Globals.SysFreq);
+      ENCODE_U32(pPayload, _SYSVIEW_Globals.CPUFreq);
+      ENCODE_U32(pPayload, _SYSVIEW_Globals.RAMBaseAddress);
+      ENCODE_U32(pPayload, SEGGER_SYSVIEW_ID_SHIFT);
+      _SendPacket(pPayloadStart, pPayload, SYSVIEW_EVTID_INIT);
+      RECORD_END();
+    }
+    if (_SYSVIEW_Globals.pfSendSysDesc) {
+      _SYSVIEW_Globals.pfSendSysDesc();
+    }
+    SEGGER_SYSVIEW_RecordSystime();
+    SEGGER_SYSVIEW_SendTaskList();
+    SEGGER_SYSVIEW_SendNumModules();
+#endif
+#if (SEGGER_SYSVIEW_CAN_RESTART == 0)
+  }
+#endif
+}
+
+/*********************************************************************
+*
+*       SEGGER_SYSVIEW_Stop()
+*
+*  Function description
+*    Stop recording SystemView events.
+*
+*    This function is triggered by the SystemView Application on disconnect.
+*    For single-shot or post-mortem mode recording, it can be called
+*    by the application.
+*
+*  Additional information
+*    This function disables transmission of SystemView packets recorded
+*    by subsequent trace calls.  If transmission is enabled when
+*    this function is called, a single SystemView Stop event is recorded
+*    to the trace, send, and then trace transmission is halted.
+*/
+void SEGGER_SYSVIEW_Stop(void) {
+  U8* pPayloadStart;
+  RECORD_START(SEGGER_SYSVIEW_INFO_SIZE);
+  //
+  if (_SYSVIEW_Globals.EnableState) {
+    _SendPacket(pPayloadStart, pPayloadStart, SYSVIEW_EVTID_TRACE_STOP);
+    _SYSVIEW_Globals.EnableState = 0;
+  }
+  RECORD_END();
+}
+
+/*********************************************************************
+*
+*       SEGGER_SYSVIEW_GetChannelID()
+*
+*  Function description
+*    Returns the RTT <Up> / <Down> channel ID used by SystemView.
+*/
+int SEGGER_SYSVIEW_GetChannelID(void) {
+  return CHANNEL_ID_UP;
+}
+
+/*********************************************************************
+*
+*       SEGGER_SYSVIEW_GetSysDesc()
+*
+*  Function description
+*    Triggers a send of the system information and description.
+*
+*/
+void SEGGER_SYSVIEW_GetSysDesc(void) {
+  U8* pPayload;
+  U8* pPayloadStart;
+  RECORD_START(SEGGER_SYSVIEW_INFO_SIZE + 4 * SEGGER_SYSVIEW_QUANTA_U32);
+  //
+  pPayload = pPayloadStart;
+  ENCODE_U32(pPayload, _SYSVIEW_Globals.SysFreq);
+  ENCODE_U32(pPayload, _SYSVIEW_Globals.CPUFreq);
+  ENCODE_U32(pPayload, _SYSVIEW_Globals.RAMBaseAddress);
+  ENCODE_U32(pPayload, SEGGER_SYSVIEW_ID_SHIFT);
+  _SendPacket(pPayloadStart, pPayload, SYSVIEW_EVTID_INIT);
+  RECORD_END();
+  if (_SYSVIEW_Globals.pfSendSysDesc) {
+    _SYSVIEW_Globals.pfSendSysDesc();
+  }
+}
+
+/*********************************************************************
+*
+*       SEGGER_SYSVIEW_SendTaskInfo()
+*
+*  Function description
+*    Send a Task Info Packet, containing TaskId for identification,
+*    task priority and task name.
+*
+*  Parameters
+*    pInfo - Pointer to task information to send.
+*/
+void SEGGER_SYSVIEW_SendTaskInfo(const SEGGER_SYSVIEW_TASKINFO *pInfo) {
+  U8* pPayload;
+  U8* pPayloadStart;
+  RECORD_START(SEGGER_SYSVIEW_INFO_SIZE + SEGGER_SYSVIEW_QUANTA_U32 + 1 + 32);
+  //
+  pPayload = pPayloadStart;
+  ENCODE_U32(pPayload, SHRINK_ID(pInfo->TaskID));
+  ENCODE_U32(pPayload, pInfo->Prio);
+  pPayload = _EncodeStr(pPayload, pInfo->sName, 32);
+  _SendPacket(pPayloadStart, pPayload, SYSVIEW_EVTID_TASK_INFO);
+  //
+  pPayload = pPayloadStart;
+  ENCODE_U32(pPayload, SHRINK_ID(pInfo->TaskID));
+  ENCODE_U32(pPayload, pInfo->StackBase);
+  ENCODE_U32(pPayload, pInfo->StackSize);
+  ENCODE_U32(pPayload, 0); // Stack End, future use
+  _SendPacket(pPayloadStart, pPayload, SYSVIEW_EVTID_STACK_INFO);
+  RECORD_END();
+}
+
+/*********************************************************************
+*
+*       SEGGER_SYSVIEW_SendTaskList()
+*
+*  Function description
+*    Send all tasks descriptors to the host.
+*/
+void SEGGER_SYSVIEW_SendTaskList(void) {
+  if (_SYSVIEW_Globals.pOSAPI && _SYSVIEW_Globals.pOSAPI->pfSendTaskList) {
+    _SYSVIEW_Globals.pOSAPI->pfSendTaskList();
+  }
+}
+
+/*********************************************************************
+*
+*       SEGGER_SYSVIEW_SendSysDesc()
+*
+*  Function description
+*    Send the system description string to the host.
+*    The system description is used by the Systemview Application
+*    to identify the current application and handle events accordingly.
+*
+*    The system description is usually called by the system description
+*    callback, to ensure it is only sent when the SystemView Application
+*    is connected.
+*
+*  Parameters
+*    sSysDesc - Pointer to the 0-terminated system description string.
+*
+*  Additional information
+*    One system description string may not exceed SEGGER_SYSVIEW_MAX_STRING_LEN characters.
+*    Multiple description strings can be recorded.
+*
+*    The Following items can be described in a system description string.
+*    Each item is identified by its identifier, followed by '=' and the value.
+*    Items are separated by ','.
+*/
+void SEGGER_SYSVIEW_SendSysDesc(const char *sSysDesc) {
+  U8* pPayload;
+  U8* pPayloadStart;
+  RECORD_START(SEGGER_SYSVIEW_INFO_SIZE + 1 + SEGGER_SYSVIEW_MAX_STRING_LEN);
+  //
+  pPayload = _EncodeStr(pPayloadStart, sSysDesc, SEGGER_SYSVIEW_MAX_STRING_LEN);
+  _SendPacket(pPayloadStart, pPayload, SYSVIEW_EVTID_SYSDESC);
+  RECORD_END();
+}
+
+/*********************************************************************
+*
+*       SEGGER_SYSVIEW_RecordSystime()
+*
+*  Function description
+*    Formats and sends a SystemView Systime containing a single U64 or U32
+*    parameter payload.
+*/
+void SEGGER_SYSVIEW_RecordSystime(void) {
+  U64 Systime;
+
+  if (_SYSVIEW_Globals.pOSAPI && _SYSVIEW_Globals.pOSAPI->pfGetTime) {
+    Systime = _SYSVIEW_Globals.pOSAPI->pfGetTime();
+    SEGGER_SYSVIEW_RecordU32x2(SYSVIEW_EVTID_SYSTIME_US,
+                               (U32)(Systime),
+                               (U32)(Systime >> 32));
+  } else {
+    SEGGER_SYSVIEW_RecordU32(SYSVIEW_EVTID_SYSTIME_CYCLES, SEGGER_SYSVIEW_GET_TIMESTAMP());
+  }
+}
+
+/*********************************************************************
+*
+*       SEGGER_SYSVIEW_RecordEnterISR()
+*
+*  Function description
+*    Format and send an ISR entry event.
+*
+*  Additional information
+*    Example packets sent
+*      02 0F 50              // ISR(15) Enter. Timestamp is 80 (0x50)
+*/
+void SEGGER_SYSVIEW_RecordEnterISR(void) {
+  unsigned v;
+  U8* pPayload;
+  U8* pPayloadStart;
+  RECORD_START(SEGGER_SYSVIEW_INFO_SIZE + SEGGER_SYSVIEW_QUANTA_U32);
+  //
+  pPayload = pPayloadStart;
+  v = SEGGER_SYSVIEW_GET_INTERRUPT_ID();
+  ENCODE_U32(pPayload, v);
+  _SendPacket(pPayloadStart, pPayload, SYSVIEW_EVTID_ISR_ENTER);
+  RECORD_END();
+}
+
+/*********************************************************************
+*
+*       SEGGER_SYSVIEW_RecordExitISR()
+*
+*  Function description
+*    Format and send an ISR exit event.
+*
+*  Additional information
+*    Format as follows:
+*      03 <TimeStamp>        // Max. packet len is 6
+*
+*    Example packets sent
+*      03 20                // ISR Exit. Timestamp is 32 (0x20)
+*/
+void SEGGER_SYSVIEW_RecordExitISR(void) {
+  U8* pPayloadStart;
+  RECORD_START(SEGGER_SYSVIEW_INFO_SIZE);
+  //
+  _SendPacket(pPayloadStart, pPayloadStart, SYSVIEW_EVTID_ISR_EXIT);
+  RECORD_END();
+}
+
+/*********************************************************************
+*
+*       SEGGER_SYSVIEW_RecordExitISRToScheduler()
+*
+*  Function description
+*    Format and send an ISR exit into scheduler event.
+*
+*  Additional information
+*    Format as follows:
+*      18 <TimeStamp>        // Max. packet len is 6
+*
+*    Example packets sent
+*      18 20                // ISR Exit to Scheduler. Timestamp is 32 (0x20)
+*/
+void SEGGER_SYSVIEW_RecordExitISRToScheduler(void) {
+  U8* pPayloadStart;
+  RECORD_START(SEGGER_SYSVIEW_INFO_SIZE);
+  //
+  _SendPacket(pPayloadStart, pPayloadStart, SYSVIEW_EVTID_ISR_TO_SCHEDULER);
+  RECORD_END();
+}
+
+/*********************************************************************
+*
+*       SEGGER_SYSVIEW_RecordEnterTimer()
+*
+*  Function description
+*    Format and send a Timer entry event.
+*
+*  Parameters
+*    TimerId - Id of the timer which starts.
+*/
+void SEGGER_SYSVIEW_RecordEnterTimer(U32 TimerId) {
+  U8* pPayload;
+  U8* pPayloadStart;
+  RECORD_START(SEGGER_SYSVIEW_INFO_SIZE + SEGGER_SYSVIEW_QUANTA_U32);
+  //
+  pPayload = pPayloadStart;
+  ENCODE_U32(pPayload, SHRINK_ID(TimerId));
+  _SendPacket(pPayloadStart, pPayload, SYSVIEW_EVTID_TIMER_ENTER);
+  RECORD_END();
+}
+
+/*********************************************************************
+*
+*       SEGGER_SYSVIEW_RecordExitTimer()
+*
+*  Function description
+*    Format and send a Timer exit event.
+*/
+void SEGGER_SYSVIEW_RecordExitTimer(void) {
+  U8* pPayloadStart;
+  RECORD_START(SEGGER_SYSVIEW_INFO_SIZE);
+  //
+  _SendPacket(pPayloadStart, pPayloadStart, SYSVIEW_EVTID_TIMER_EXIT);
+  RECORD_END();
+}
+
+/*********************************************************************
+*
+*       SEGGER_SYSVIEW_RecordEndCall()
+*
+*  Function description
+*    Format and send an End API Call event without return value.
+*
+*  Parameters
+*    EventID - Id of API function which ends.
+*/
+void SEGGER_SYSVIEW_RecordEndCall(unsigned int EventID) {
+  U8* pPayload;
+  U8* pPayloadStart;
+  RECORD_START(SEGGER_SYSVIEW_INFO_SIZE + SEGGER_SYSVIEW_QUANTA_U32);
+  //
+  pPayload = pPayloadStart;
+  ENCODE_U32(pPayload, EventID);
+  _SendPacket(pPayloadStart, pPayload, SYSVIEW_EVTID_END_CALL);
+  RECORD_END();
+}
+
+/*********************************************************************
+*
+*       SEGGER_SYSVIEW_RecordEndCallU32()
+*
+*  Function description
+*    Format and send an End API Call event with return value.
+*
+*  Parameters
+*    EventID      - Id of API function which ends.
+*    Para0        - Return value which will be returned by the API function.
+*/
+void SEGGER_SYSVIEW_RecordEndCallU32(unsigned int EventID, U32 Para0) {
+  U8* pPayload;
+  U8* pPayloadStart;
+  RECORD_START(SEGGER_SYSVIEW_INFO_SIZE + 2 * SEGGER_SYSVIEW_QUANTA_U32);
+  //
+  pPayload = pPayloadStart;
+  ENCODE_U32(pPayload, EventID);
+  ENCODE_U32(pPayload, Para0);
+  _SendPacket(pPayloadStart, pPayload, SYSVIEW_EVTID_END_CALL);
+  RECORD_END();
+}
+
+/*********************************************************************
+*
+*       SEGGER_SYSVIEW_OnIdle()
+*
+*  Function description
+*    Record an Idle event.
+*/
+void SEGGER_SYSVIEW_OnIdle(void) {
+  U8* pPayloadStart;
+  RECORD_START(SEGGER_SYSVIEW_INFO_SIZE);
+  //
+  _SendPacket(pPayloadStart, pPayloadStart, SYSVIEW_EVTID_IDLE);
+  RECORD_END();
+}
+
+/*********************************************************************
+*
+*       SEGGER_SYSVIEW_OnTaskCreate()
+*
+*  Function description
+*    Record a Task Create event.  The Task Create event corresponds
+*    to creating a task in the OS.
+*
+*  Parameters
+*    TaskId        - Task ID of created task.
+*/
+void SEGGER_SYSVIEW_OnTaskCreate(U32 TaskId) {
+  U8* pPayload;
+  U8* pPayloadStart;
+  RECORD_START(SEGGER_SYSVIEW_INFO_SIZE + SEGGER_SYSVIEW_QUANTA_U32);
+  //
+  pPayload = pPayloadStart;
+  TaskId = SHRINK_ID(TaskId);
+  ENCODE_U32(pPayload, TaskId);
+  _SendPacket(pPayloadStart, pPayload, SYSVIEW_EVTID_TASK_CREATE);
+  RECORD_END();
+}
+
+/*********************************************************************
+*
+*       SEGGER_SYSVIEW_OnTaskTerminate()
+*
+*  Function description
+*    Record a Task termination event.
+*    The Task termination event corresponds to terminating a task in
+*    the OS. If the TaskId is the currently active task,
+*    SEGGER_SYSVIEW_OnTaskStopExec may be used, either.
+*
+*  Parameters
+*    TaskId        - Task ID of terminated task.
+*/
+void SEGGER_SYSVIEW_OnTaskTerminate(U32 TaskId) {
+  U8* pPayload;
+  U8* pPayloadStart;
+  RECORD_START(SEGGER_SYSVIEW_INFO_SIZE + SEGGER_SYSVIEW_QUANTA_U32);
+  //
+  pPayload = pPayloadStart;
+  TaskId = SHRINK_ID(TaskId);
+  ENCODE_U32(pPayload, TaskId);
+  _SendPacket(pPayloadStart, pPayload, SYSVIEW_EVTID_TASK_TERMINATE);
+  RECORD_END();
+}
+
+/*********************************************************************
+*
+*       SEGGER_SYSVIEW_OnTaskStartExec()
+*
+*  Function description
+*    Record a Task Start Execution event.  The Task Start event
+*    corresponds to when a task has started to execute rather than
+*    when it is ready to execute.
+*
+*  Parameters
+*    TaskId - Task ID of task that started to execute.
+*/
+void SEGGER_SYSVIEW_OnTaskStartExec(U32 TaskId) {
+  U8* pPayload;
+  U8* pPayloadStart;
+  RECORD_START(SEGGER_SYSVIEW_INFO_SIZE + SEGGER_SYSVIEW_QUANTA_U32);
+  //
+  pPayload = pPayloadStart;
+  TaskId = SHRINK_ID(TaskId);
+  ENCODE_U32(pPayload, TaskId);
+  _SendPacket(pPayloadStart, pPayload, SYSVIEW_EVTID_TASK_START_EXEC);
+  RECORD_END();
+}
+
+/*********************************************************************
+*
+*       SEGGER_SYSVIEW_OnTaskStopExec()
+*
+*  Function description
+*    Record a Task Stop Execution event.  The Task Stop event
+*    corresponds to when a task stops executing and terminates.
+*/
+void SEGGER_SYSVIEW_OnTaskStopExec(void) {
+  U8* pPayloadStart;
+  RECORD_START(SEGGER_SYSVIEW_INFO_SIZE);
+  //
+  _SendPacket(pPayloadStart, pPayloadStart, SYSVIEW_EVTID_TASK_STOP_EXEC);
+  RECORD_END();
+}
+
+/*********************************************************************
+*
+*       SEGGER_SYSVIEW_OnTaskStartReady()
+*
+*  Function description
+*    Record a Task Start Ready event.
+*
+*  Parameters
+*    TaskId - Task ID of task that started to execute.
+*/
+void SEGGER_SYSVIEW_OnTaskStartReady(U32 TaskId) {
+  U8* pPayload;
+  U8* pPayloadStart;
+  RECORD_START(SEGGER_SYSVIEW_INFO_SIZE + SEGGER_SYSVIEW_QUANTA_U32);
+  //
+  pPayload = pPayloadStart;
+  TaskId = SHRINK_ID(TaskId);
+  ENCODE_U32(pPayload, TaskId);
+  _SendPacket(pPayloadStart, pPayload, SYSVIEW_EVTID_TASK_START_READY);
+  RECORD_END();
+}
+
+/*********************************************************************
+*
+*       SEGGER_SYSVIEW_OnTaskStopReady()
+*
+*  Function description
+*    Record a Task Stop Ready event.
+*
+*  Parameters
+*    TaskId - Task ID of task that completed execution.
+*    Cause  - Reason for task to stop (i.e. Idle/Sleep)
+*/
+void SEGGER_SYSVIEW_OnTaskStopReady(U32 TaskId, unsigned int Cause) {
+  U8* pPayload;
+  U8* pPayloadStart;
+  RECORD_START(SEGGER_SYSVIEW_INFO_SIZE + 2 * SEGGER_SYSVIEW_QUANTA_U32);
+  //
+  pPayload = pPayloadStart;
+  TaskId = SHRINK_ID(TaskId);
+  ENCODE_U32(pPayload, TaskId);
+  ENCODE_U32(pPayload, Cause);
+  _SendPacket(pPayloadStart, pPayload, SYSVIEW_EVTID_TASK_STOP_READY);
+  RECORD_END();
+}
+
+/*********************************************************************
+*
+*       SEGGER_SYSVIEW_MarkStart()
+*
+*  Function description
+*    Record a Performance Marker Start event to start measuring runtime.
+*
+*  Parameters
+*    MarkerId  - User defined ID for the marker.
+*/
+void SEGGER_SYSVIEW_MarkStart(unsigned MarkerId) {
+  U8* pPayload;
+  U8* pPayloadStart;
+  RECORD_START(SEGGER_SYSVIEW_INFO_SIZE + SEGGER_SYSVIEW_QUANTA_U32);
+  //
+  pPayload = pPayloadStart;
+  ENCODE_U32(pPayload, MarkerId);
+  _SendPacket(pPayloadStart, pPayload, SYSVIEW_EVTID_MARK_START);
+  RECORD_END();
+}
+
+/*********************************************************************
+*
+*       SEGGER_SYSVIEW_MarkStop()
+*
+*  Function description
+*    Record a Performance Marker Stop event to stop measuring runtime.
+*
+*  Parameters
+*    MarkerId  - User defined ID for the marker.
+*/
+void SEGGER_SYSVIEW_MarkStop(unsigned MarkerId) {
+  U8 * pPayload;
+  U8 * pPayloadStart;
+  RECORD_START(SEGGER_SYSVIEW_INFO_SIZE + SEGGER_SYSVIEW_QUANTA_U32);
+  //
+  pPayload = pPayloadStart;
+  ENCODE_U32(pPayload, MarkerId);
+  _SendPacket(pPayloadStart, pPayload, SYSVIEW_EVTID_MARK_STOP);
+  RECORD_END();
+}
+
+/*********************************************************************
+*
+*       SEGGER_SYSVIEW_Mark()
+*
+*  Function description
+*    Record a Performance Marker intermediate event.
+*
+*  Parameters
+*    MarkerId  - User defined ID for the marker.
+*/
+void SEGGER_SYSVIEW_Mark(unsigned int MarkerId) {
+  U8* pPayload;
+  U8* pPayloadStart;
+  RECORD_START(SEGGER_SYSVIEW_INFO_SIZE + 2 * SEGGER_SYSVIEW_QUANTA_U32);
+  //
+  pPayload = pPayloadStart;
+  ENCODE_U32(pPayload, SYSVIEW_EVTID_EX_MARK);
+  ENCODE_U32(pPayload, MarkerId);
+  _SendPacket(pPayloadStart, pPayload, SYSVIEW_EVTID_EX);
+  RECORD_END();
+}
+
+/*********************************************************************
+*
+*       SEGGER_SYSVIEW_NameMarker()
+*
+*  Function description
+*    Send the name of a Performance Marker to be displayed in SystemView.
+*
+*    Marker names are usually set in the system description
+*    callback, to ensure it is only sent when the SystemView Application
+*    is connected.
+*
+*  Parameters
+*    MarkerId   - User defined ID for the marker.
+*    sName      - Pointer to the marker name. (Max. SEGGER_SYSVIEW_MAX_STRING_LEN Bytes)
+*/
+void SEGGER_SYSVIEW_NameMarker(unsigned int MarkerId, const char* sName) {
+  U8* pPayload;
+  U8* pPayloadStart;
+  RECORD_START(SEGGER_SYSVIEW_INFO_SIZE + 2 * SEGGER_SYSVIEW_QUANTA_U32 + 1 + SEGGER_SYSVIEW_MAX_STRING_LEN);
+  //
+  pPayload = pPayloadStart;
+  ENCODE_U32(pPayload, SYSVIEW_EVTID_EX_NAME_MARKER);
+  ENCODE_U32(pPayload, MarkerId);
+  pPayload = _EncodeStr(pPayload, sName, SEGGER_SYSVIEW_MAX_STRING_LEN);
+  _SendPacket(pPayloadStart, pPayload, SYSVIEW_EVTID_EX);
+  RECORD_END();
+}
+
+/*********************************************************************
+*
+*       SEGGER_SYSVIEW_NameResource()
+*
+*  Function description
+*    Send the name of a resource to be displayed in SystemView.
+*
+*    Marker names are usually set in the system description
+*    callback, to ensure it is only sent when the SystemView Application
+*    is connected.
+*
+*  Parameters
+*    ResourceId - Id of the resource to be named. i.e. its address.
+*    sName      - Pointer to the resource name. (Max. SEGGER_SYSVIEW_MAX_STRING_LEN Bytes)
+*/
+void SEGGER_SYSVIEW_NameResource(U32 ResourceId, const char* sName) {
+  U8* pPayload;
+  U8* pPayloadStart;
+  RECORD_START(SEGGER_SYSVIEW_INFO_SIZE + SEGGER_SYSVIEW_QUANTA_U32 + 1 + SEGGER_SYSVIEW_MAX_STRING_LEN);
+  //
+  pPayload = pPayloadStart;
+  ENCODE_U32(pPayload, SHRINK_ID(ResourceId));
+  pPayload = _EncodeStr(pPayload, sName, SEGGER_SYSVIEW_MAX_STRING_LEN);
+  _SendPacket(pPayloadStart, pPayload, SYSVIEW_EVTID_NAME_RESOURCE);
+  RECORD_END();
+}
+
+/*********************************************************************
+*
+*       SEGGER_SYSVIEW_SendPacket()
+*
+*  Function description
+*    Send an event packet.
+*
+*  Parameters
+*    pPacket      - Pointer to the start of the packet.
+*    pPayloadEnd  - Pointer to the end of the payload.
+*                   Make sure there are at least 5 bytes free after the payload.
+*    EventId      - Id of the event packet.
+*
+*  Return value
+*    !=0:  Success, Message sent.
+*    ==0:  Buffer full, Message *NOT* sent.
+*/
+int SEGGER_SYSVIEW_SendPacket(U8* pPacket, U8* pPayloadEnd, unsigned int EventId) {
+#if (SEGGER_SYSVIEW_USE_STATIC_BUFFER == 1)
+  SEGGER_SYSVIEW_LOCK();
+#endif
+  _SendPacket(pPacket + 4, pPayloadEnd, EventId);
+#if (SEGGER_SYSVIEW_USE_STATIC_BUFFER == 1)
+  SEGGER_SYSVIEW_UNLOCK();
+#endif
+  return 0;
+}
+
+/*********************************************************************
+*
+*       SEGGER_SYSVIEW_EncodeU32()
+*
+*  Function description
+*    Encode a U32 in variable-length format.
+*
+*  Parameters
+*    pPayload - Pointer to where U32 will be encoded.
+*    Value    - The 32-bit value to be encoded.
+*
+*  Return value
+*    Pointer to the byte following the value, i.e. the first free
+*    byte in the payload and the next position to store payload
+*    content.
+*/
+U8* SEGGER_SYSVIEW_EncodeU32(U8* pPayload, U32 Value) {
+  ENCODE_U32(pPayload, Value);
+  return pPayload;
+}
+
+/*********************************************************************
+*
+*       SEGGER_SYSVIEW_EncodeString()
+*
+*  Function description
+*    Encode a string in variable-length format.
+*
+*  Parameters
+*    pPayload - Pointer to where string will be encoded.
+*    s        - String to encode.
+*    MaxLen   - Maximum number of characters to encode from string.
+*
+*  Return value
+*    Pointer to the byte following the value, i.e. the first free
+*    byte in the payload and the next position to store payload
+*    content.
+*
+*  Additional information
+*    The string is encoded as a count byte followed by the contents
+*    of the string.
+*    No more than 1 + MaxLen bytes will be encoded to the payload.
+*/
+U8* SEGGER_SYSVIEW_EncodeString(U8* pPayload, const char* s, unsigned int MaxLen) {
+  return _EncodeStr(pPayload, s, MaxLen);
+}
+
+/*********************************************************************
+*
+*       SEGGER_SYSVIEW_EncodeData()
+*
+*  Function description
+*    Encode a byte buffer in variable-length format.
+*
+*  Parameters
+*    pPayload - Pointer to where string will be encoded.
+*    pSrc     - Pointer to data buffer to be encoded.
+*    NumBytes - Number of bytes in the buffer to be encoded.
+*
+*  Return value
+*    Pointer to the byte following the value, i.e. the first free
+*    byte in the payload and the next position to store payload
+*    content.
+*
+*  Additional information
+*    The data is encoded as a count byte followed by the contents
+*    of the data buffer.
+*    Make sure NumBytes + 1 bytes are free for the payload.
+*/
+U8* SEGGER_SYSVIEW_EncodeData(U8 *pPayload, const char* pSrc, unsigned int NumBytes) {
+  return _EncodeData(pPayload, pSrc, NumBytes);
+}
+
+/*********************************************************************
+*
+*       SEGGER_SYSVIEW_EncodeId()
+*
+*  Function description
+*    Encode a 32-bit Id in shrunken variable-length format.
+*
+*  Parameters
+*    pPayload - Pointer to where the Id will be encoded.
+*    Id       - The 32-bit value to be encoded.
+*
+*  Return value
+*    Pointer to the byte following the value, i.e. the first free
+*    byte in the payload and the next position to store payload
+*    content.
+*
+*  Additional information
+*    The parameters to shrink an Id can be configured in
+*    SEGGER_SYSVIEW_Conf.h and via SEGGER_SYSVIEW_SetRAMBase().
+*     SEGGER_SYSVIEW_ID_BASE: Lowest Id reported by the application.
+*       (i.e. 0x20000000 when all Ids are an address in this RAM)
+*     SEGGER_SYSVIEW_ID_SHIFT: Number of bits to shift the Id to
+*       save bandwidth. (i.e. 2 when Ids are 4 byte aligned)
+*/
+U8* SEGGER_SYSVIEW_EncodeId(U8* pPayload, U32 Id) {
+  Id = SHRINK_ID(Id);
+  ENCODE_U32(pPayload, Id);
+  return pPayload;
+}
+
+/*********************************************************************
+*
+*       SEGGER_SYSVIEW_ShrinkId()
+*
+*  Function description
+*    Get the shrunken value of an Id for further processing like in
+*    SEGGER_SYSVIEW_NameResource().
+*
+*  Parameters
+*    Id       - The 32-bit value to be shrunken.
+*
+*  Return value
+*    Shrunken Id.
+*
+*  Additional information
+*    The parameters to shrink an Id can be configured in
+*    SEGGER_SYSVIEW_Conf.h and via SEGGER_SYSVIEW_SetRAMBase().
+*     SEGGER_SYSVIEW_ID_BASE: Lowest Id reported by the application.
+*       (i.e. 0x20000000 when all Ids are an address in this RAM)
+*     SEGGER_SYSVIEW_ID_SHIFT: Number of bits to shift the Id to
+*       save bandwidth. (i.e. 2 when Ids are 4 byte aligned)
+*/
+U32 SEGGER_SYSVIEW_ShrinkId(U32 Id) {
+  return SHRINK_ID(Id);
+}
+
+/*********************************************************************
+*
+*       SEGGER_SYSVIEW_RegisterModule()
+*
+*  Function description
+*    Register a middleware module for recording its events.
+*
+*  Parameters
+*    pModule  - The middleware module information.
+*
+*  Additional information
+*    SEGGER_SYSVIEW_MODULE elements:
+*      sDescription      - Pointer to a string containing the module name and optionally the module event description.
+*      NumEvents         - Number of events the module wants to register.
+*      EventOffset       - Offset to be added to the event Ids. Out parameter, set by this function. Do not modify after calling this function.
+*      pfSendModuleDesc  - Callback function pointer to send more detailed module description to SystemView Application.
+*      pNext             - Pointer to next registered module. Out parameter, set by this function. Do not modify after calling this function.
+*/
+void SEGGER_SYSVIEW_RegisterModule(SEGGER_SYSVIEW_MODULE* pModule) {
+  SEGGER_SYSVIEW_LOCK();
+  if (_pFirstModule == 0) {
+    //
+    // No module registered, yet.
+    // Start list with new module.
+    // EventOffset is the base offset for modules
+    //
+    pModule->EventOffset = MODULE_EVENT_OFFSET;
+    pModule->pNext = 0;
+    _pFirstModule = pModule;
+    _NumModules = 1;
+  } else {
+    //
+    // Registreded module(s) present.
+    // Prepend new module in list.
+    // EventOffset set from number of events and offset of previous module.
+    //
+    pModule->EventOffset = _pFirstModule->EventOffset + _pFirstModule->NumEvents;
+    pModule->pNext = _pFirstModule;
+    _pFirstModule = pModule;
+    _NumModules++;
+  }
+  SEGGER_SYSVIEW_SendModule(0);
+  if (pModule->pfSendModuleDesc) {
+    pModule->pfSendModuleDesc();
+  }
+  SEGGER_SYSVIEW_UNLOCK();
+}
+
+/*********************************************************************
+*
+*       SEGGER_SYSVIEW_RecordModuleDescription()
+*
+*  Function description
+*    Sends detailed information of a registered module to the host.
+*
+*  Parameters
+*    pModule      - Pointer to the described module.
+*    sDescription - Pointer to a description string.
+*/
+void SEGGER_SYSVIEW_RecordModuleDescription(const SEGGER_SYSVIEW_MODULE* pModule, const char* sDescription) {
+  U8  ModuleId;
+  SEGGER_SYSVIEW_MODULE* p;
+
+  p = _pFirstModule;
+  ModuleId = 0;
+  do {
+    if (p == pModule) {
+      break;
+    }
+    ModuleId++;
+    p = p->pNext;
+  } while (p);
+  {
+    U8* pPayload;
+    U8* pPayloadStart;
+    RECORD_START(SEGGER_SYSVIEW_INFO_SIZE + 2 * SEGGER_SYSVIEW_QUANTA_U32 + 1 + SEGGER_SYSVIEW_MAX_STRING_LEN);
+    //
+    pPayload = pPayloadStart;
+    //
+    // Send module description
+    // Send event offset and number of events
+    //
+    ENCODE_U32(pPayload, ModuleId);
+    ENCODE_U32(pPayload, (pModule->EventOffset));
+    pPayload = _EncodeStr(pPayload, sDescription, SEGGER_SYSVIEW_MAX_STRING_LEN);
+    _SendPacket(pPayloadStart, pPayload, SYSVIEW_EVTID_MODULEDESC);
+    RECORD_END();
+  }
+}
+
+/*********************************************************************
+*
+*       SEGGER_SYSVIEW_SendModule()
+*
+*  Function description
+*    Sends the information of a registered module to the host.
+*
+*  Parameters
+*    ModuleId   - Id of the requested module.
+*/
+void SEGGER_SYSVIEW_SendModule(U8 ModuleId) {
+  SEGGER_SYSVIEW_MODULE* pModule;
+  U32 n;
+
+  if (_pFirstModule != 0) {
+    pModule = _pFirstModule;
+    for (n = 0; n < ModuleId; n++) {
+      pModule = pModule->pNext;
+      if (pModule == 0) {
+        break;
+      }
+    }
+    if (pModule != 0) {
+      U8* pPayload;
+      U8* pPayloadStart;
+      RECORD_START(SEGGER_SYSVIEW_INFO_SIZE + 2 * SEGGER_SYSVIEW_QUANTA_U32 + 1 + SEGGER_SYSVIEW_MAX_STRING_LEN);
+      //
+      pPayload = pPayloadStart;
+      //
+      // Send module description
+      // Send event offset and number of events
+      //
+      ENCODE_U32(pPayload, ModuleId);
+      ENCODE_U32(pPayload, (pModule->EventOffset));
+      pPayload = _EncodeStr(pPayload, pModule->sModule, SEGGER_SYSVIEW_MAX_STRING_LEN);
+      _SendPacket(pPayloadStart, pPayload, SYSVIEW_EVTID_MODULEDESC);
+      RECORD_END();
+    }
+  }
+}
+
+/*********************************************************************
+*
+*       SEGGER_SYSVIEW_SendModuleDescription()
+*
+*  Function description
+*    Triggers a send of the registered module descriptions.
+*
+*/
+void SEGGER_SYSVIEW_SendModuleDescription(void) {
+  SEGGER_SYSVIEW_MODULE* pModule;
+
+  if (_pFirstModule != 0) {
+    pModule = _pFirstModule;
+    do {
+      if (pModule->pfSendModuleDesc) {
+        pModule->pfSendModuleDesc();
+      }
+      pModule = pModule->pNext;
+    } while (pModule);
+  }
+}
+
+/*********************************************************************
+*
+*       SEGGER_SYSVIEW_SendNumModules()
+*
+*  Function description
+*    Send the number of registered modules to the host.
+*/
+void SEGGER_SYSVIEW_SendNumModules(void) {
+  U8* pPayload;
+  U8* pPayloadStart;
+  RECORD_START(SEGGER_SYSVIEW_INFO_SIZE + 2*SEGGER_SYSVIEW_QUANTA_U32);
+  pPayload = pPayloadStart;
+  ENCODE_U32(pPayload, _NumModules);
+  _SendPacket(pPayloadStart, pPayload, SYSVIEW_EVTID_NUMMODULES);
+  RECORD_END();
+}
+
+#ifndef SEGGER_SYSVIEW_EXCLUDE_PRINTF // Define in project to avoid warnings about variable parameter list
+
+/*********************************************************************
+*
+*       SEGGER_SYSVIEW_PrintfHostEx()
+*
+*  Function description
+*    Print a string which is formatted on the host by the SystemView Application
+*    with Additional information.
+*
+*  Parameters
+*    s        - String to be formatted.
+*    Options  - Options for the string. i.e. Log level.
+*
+*  Additional information
+*    All format arguments are treated as 32-bit scalar values.
+*/
+void SEGGER_SYSVIEW_PrintfHostEx(const char* s, U32 Options, ...) {
+  va_list ParamList;
+#if SEGGER_SYSVIEW_PRINTF_IMPLICIT_FORMAT
+  int r;
+
+  va_start(ParamList, Options);
+  r = _VPrintHost(s, Options, &ParamList);
+  va_end(ParamList);
+
+  if (r == -1) {
+    va_start(ParamList, Options);
+    _VPrintTarget(s, Options, &ParamList);
+    va_end(ParamList);
+  }
+#else
+  va_start(ParamList, Options);
+  _VPrintHost(s, Options, &ParamList);
+  va_end(ParamList);
+#endif
+}
+
+/*********************************************************************
+*
+*       SEGGER_SYSVIEW_PrintfHost()
+*
+*  Function description
+*    Print a string which is formatted on the host by the SystemView Application.
+*
+*  Parameters
+*    s        - String to be formatted.
+*
+*  Additional information
+*    All format arguments are treated as 32-bit scalar values.
+*/
+void SEGGER_SYSVIEW_PrintfHost(const char* s, ...) {
+  va_list ParamList;
+#if SEGGER_SYSVIEW_PRINTF_IMPLICIT_FORMAT
+  int r;
+
+  va_start(ParamList, s);
+  r = _VPrintHost(s, SEGGER_SYSVIEW_LOG, &ParamList);
+  va_end(ParamList);
+
+  if (r == -1) {
+    va_start(ParamList, s);
+    _VPrintTarget(s, SEGGER_SYSVIEW_LOG, &ParamList);
+    va_end(ParamList);
+  }
+#else
+  va_start(ParamList, s);
+  _VPrintHost(s, SEGGER_SYSVIEW_LOG, &ParamList);
+  va_end(ParamList);
+#endif
+}
+
+/*********************************************************************
+*
+*       SEGGER_SYSVIEW_WarnfHost()
+*
+*  Function description
+*    Print a warning string which is formatted on the host by
+*    the SystemView Application.
+*
+*  Parameters
+*    s        - String to be formatted.
+*
+*  Additional information
+*    All format arguments are treated as 32-bit scalar values.
+*/
+void SEGGER_SYSVIEW_WarnfHost(const char* s, ...) {
+  va_list ParamList;
+#if SEGGER_SYSVIEW_PRINTF_IMPLICIT_FORMAT
+  int r;
+
+  va_start(ParamList, s);
+  r = _VPrintHost(s, SEGGER_SYSVIEW_WARNING, &ParamList);
+  va_end(ParamList);
+
+  if (r == -1) {
+    va_start(ParamList, s);
+    _VPrintTarget(s, SEGGER_SYSVIEW_WARNING, &ParamList);
+    va_end(ParamList);
+  }
+#else
+  va_start(ParamList, s);
+  _VPrintHost(s, SEGGER_SYSVIEW_WARNING, &ParamList);
+  va_end(ParamList);
+#endif
+}
+
+/*********************************************************************
+*
+*       SEGGER_SYSVIEW_ErrorfHost()
+*
+*  Function description
+*    Print an error string which is formatted on the host by
+*    the SystemView Application.
+*
+*  Parameters
+*    s        - String to be formatted.
+*
+*  Additional information
+*    All format arguments are treated as 32-bit scalar values.
+*/
+void SEGGER_SYSVIEW_ErrorfHost(const char* s, ...) {
+  va_list ParamList;
+#if SEGGER_SYSVIEW_PRINTF_IMPLICIT_FORMAT
+  int r;
+
+  va_start(ParamList, s);
+  r = _VPrintHost(s, SEGGER_SYSVIEW_ERROR, &ParamList);
+  va_end(ParamList);
+
+  if (r == -1) {
+    va_start(ParamList, s);
+    _VPrintTarget(s, SEGGER_SYSVIEW_ERROR, &ParamList);
+    va_end(ParamList);
+  }
+#else
+  va_start(ParamList, s);
+  _VPrintHost(s, SEGGER_SYSVIEW_ERROR, &ParamList);
+  va_end(ParamList);
+#endif
+}
+
+/*********************************************************************
+*
+*       SEGGER_SYSVIEW_PrintfTargetEx()
+*
+*  Function description
+*    Print a string which is formatted on the target before sent to
+*    the host with Additional information.
+*
+*  Parameters
+*    s        - String to be formatted.
+*    Options  - Options for the string. i.e. Log level.
+*/
+void SEGGER_SYSVIEW_PrintfTargetEx(const char* s, U32 Options, ...) {
+  va_list ParamList;
+
+  va_start(ParamList, Options);
+  _VPrintTarget(s, Options, &ParamList);
+  va_end(ParamList);
+}
+
+/*********************************************************************
+*
+*       SEGGER_SYSVIEW_PrintfTarget()
+*
+*  Function description
+*    Print a string which is formatted on the target before sent to
+*    the host.
+*
+*  Parameters
+*    s        - String to be formatted.
+*/
+void SEGGER_SYSVIEW_PrintfTarget(const char* s, ...) {
+  va_list ParamList;
+
+  va_start(ParamList, s);
+  _VPrintTarget(s, SEGGER_SYSVIEW_LOG, &ParamList);
+  va_end(ParamList);
+}
+
+/*********************************************************************
+*
+*       SEGGER_SYSVIEW_WarnfTarget()
+*
+*  Function description
+*    Print a warning string which is formatted on the target before
+*    sent to the host.
+*
+*  Parameters
+*    s        - String to be formatted.
+*/
+void SEGGER_SYSVIEW_WarnfTarget(const char* s, ...) {
+  va_list ParamList;
+
+  va_start(ParamList, s);
+  _VPrintTarget(s, SEGGER_SYSVIEW_WARNING, &ParamList);
+  va_end(ParamList);
+}
+
+/*********************************************************************
+*
+*       SEGGER_SYSVIEW_ErrorfTarget()
+*
+*  Function description
+*    Print an error string which is formatted on the target before
+*    sent to the host.
+*
+*  Parameters
+*    s        - String to be formatted.
+*/
+void SEGGER_SYSVIEW_ErrorfTarget(const char* s, ...) {
+  va_list ParamList;
+
+  va_start(ParamList, s);
+  _VPrintTarget(s, SEGGER_SYSVIEW_ERROR, &ParamList);
+  va_end(ParamList);
+}
+#endif // SEGGER_SYSVIEW_EXCLUDE_PRINTF
+
+/*********************************************************************
+*
+*       SEGGER_SYSVIEW_Print()
+*
+*  Function description
+*    Print a string to the host.
+*
+*  Parameters
+*    s        - String to sent.
+*/
+void SEGGER_SYSVIEW_Print(const char* s) {
+  U8* pPayload;
+  U8* pPayloadStart;
+  RECORD_START(SEGGER_SYSVIEW_INFO_SIZE + 2 * SEGGER_SYSVIEW_QUANTA_U32 + SEGGER_SYSVIEW_MAX_STRING_LEN);
+  //
+  pPayload = _EncodeStr(pPayloadStart, s, SEGGER_SYSVIEW_MAX_STRING_LEN);
+  ENCODE_U32(pPayload, SEGGER_SYSVIEW_LOG);
+  ENCODE_U32(pPayload, 0);
+  _SendPacket(pPayloadStart, pPayload, SYSVIEW_EVTID_PRINT_FORMATTED);
+  RECORD_END();
+}
+
+/*********************************************************************
+*
+*       SEGGER_SYSVIEW_Warn()
+*
+*  Function description
+*    Print a warning string to the host.
+*
+*  Parameters
+*    s        - String to sent.
+*/
+void SEGGER_SYSVIEW_Warn(const char* s) {
+  U8* pPayload;
+  U8* pPayloadStart;
+  RECORD_START(SEGGER_SYSVIEW_INFO_SIZE + 2 * SEGGER_SYSVIEW_QUANTA_U32 + SEGGER_SYSVIEW_MAX_STRING_LEN);
+  //
+  pPayload = _EncodeStr(pPayloadStart, s, SEGGER_SYSVIEW_MAX_STRING_LEN);
+  ENCODE_U32(pPayload, SEGGER_SYSVIEW_WARNING);
+  ENCODE_U32(pPayload, 0);
+  _SendPacket(pPayloadStart, pPayload, SYSVIEW_EVTID_PRINT_FORMATTED);
+  RECORD_END();
+}
+
+/*********************************************************************
+*
+*       SEGGER_SYSVIEW_Error()
+*
+*  Function description
+*    Print an error string to the host.
+*
+*  Parameters
+*    s        - String to sent.
+*/
+void SEGGER_SYSVIEW_Error(const char* s) {
+  U8* pPayload;
+  U8* pPayloadStart;
+  RECORD_START(SEGGER_SYSVIEW_INFO_SIZE + 2 * SEGGER_SYSVIEW_QUANTA_U32 + SEGGER_SYSVIEW_MAX_STRING_LEN);
+  //
+  pPayload = _EncodeStr(pPayloadStart, s, SEGGER_SYSVIEW_MAX_STRING_LEN);
+  ENCODE_U32(pPayload, SEGGER_SYSVIEW_ERROR);
+  ENCODE_U32(pPayload, 0);
+  _SendPacket(pPayloadStart, pPayload, SYSVIEW_EVTID_PRINT_FORMATTED);
+  RECORD_END();
+}
+
+/*********************************************************************
+*
+*       SEGGER_SYSVIEW_EnableEvents()
+*
+*  Function description
+*    Enable standard SystemView events to be generated.
+*
+*  Parameters
+*    EnableMask   - Events to be enabled.
+*/
+void SEGGER_SYSVIEW_EnableEvents(U32 EnableMask) {
+  _SYSVIEW_Globals.DisabledEvents &= ~EnableMask;
+}
+
+/*********************************************************************
+*
+*       SEGGER_SYSVIEW_DisableEvents()
+*
+*  Function description
+*    Disable standard SystemView events to not be generated.
+*
+*  Parameters
+*    DisableMask  - Events to be disabled.
+*/
+void SEGGER_SYSVIEW_DisableEvents(U32 DisableMask) {
+  _SYSVIEW_Globals.DisabledEvents |= DisableMask;
+}
+
+/*********************************************************************
+*
+*       SEGGER_SYSVIEW_IsStarted()
+*
+*  Function description
+*    Handle incoming packets if any and check if recording is started.
+*
+*  Return value
+*      0: Recording not started.
+*    > 0: Recording started.
+*/
+int SEGGER_SYSVIEW_IsStarted(void) {
+#if (SEGGER_SYSVIEW_POST_MORTEM_MODE != 1)
+  //
+  // Check if host is sending data which needs to be processed.
+  //
+  if (SEGGER_RTT_HASDATA(CHANNEL_ID_DOWN)) {
+    if (_SYSVIEW_Globals.RecursionCnt == 0) {   // Avoid uncontrolled nesting. This way, this routine can call itself once, but no more often than that.
+      _SYSVIEW_Globals.RecursionCnt = 1;
+      _HandleIncomingPacket();
+      _SYSVIEW_Globals.RecursionCnt = 0;
+    }
+  }
+#endif
+  return _SYSVIEW_Globals.EnableState;
+}
+
+
+/*************************** End of file ****************************/

+ 370 - 0
code/debug/SEGGER/SEGGER_SYSVIEW.h

@@ -0,0 +1,370 @@
+/*********************************************************************
+*                    SEGGER Microcontroller GmbH                     *
+*                        The Embedded Experts                        *
+**********************************************************************
+*                                                                    *
+*            (c) 1995 - 2021 SEGGER Microcontroller GmbH             *
+*                                                                    *
+*       www.segger.com     Support: support@segger.com               *
+*                                                                    *
+**********************************************************************
+*                                                                    *
+*       SEGGER SystemView * Real-time application analysis           *
+*                                                                    *
+**********************************************************************
+*                                                                    *
+* All rights reserved.                                               *
+*                                                                    *
+* SEGGER strongly recommends to not make any changes                 *
+* to or modify the source code of this software in order to stay     *
+* compatible with the SystemView and RTT protocol, and J-Link.       *
+*                                                                    *
+* Redistribution and use in source and binary forms, with or         *
+* without modification, are permitted provided that the following    *
+* condition is met:                                                  *
+*                                                                    *
+* o Redistributions of source code must retain the above copyright   *
+*   notice, this condition and the following disclaimer.             *
+*                                                                    *
+* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND             *
+* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,        *
+* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF           *
+* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE           *
+* DISCLAIMED. IN NO EVENT SHALL SEGGER Microcontroller BE LIABLE FOR *
+* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR           *
+* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT  *
+* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;    *
+* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF      *
+* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT          *
+* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE  *
+* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH   *
+* DAMAGE.                                                            *
+*                                                                    *
+**********************************************************************
+*                                                                    *
+*       SystemView version: 3.32                                    *
+*                                                                    *
+**********************************************************************
+-------------------------- END-OF-HEADER -----------------------------
+File    : SEGGER_SYSVIEW.h
+Purpose : System visualization API.
+Revision: $Rev: 26226 $
+*/
+
+#ifndef SEGGER_SYSVIEW_H
+#define SEGGER_SYSVIEW_H
+
+/*********************************************************************
+*
+*       #include Section
+*
+**********************************************************************
+*/
+
+#include "SEGGER.h"
+#include "SEGGER_SYSVIEW_ConfDefaults.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+
+/*********************************************************************
+*
+*       Defines, fixed
+*
+**********************************************************************
+*/
+
+#define SEGGER_SYSVIEW_MAJOR          3
+#define SEGGER_SYSVIEW_MINOR          32
+#define SEGGER_SYSVIEW_REV            0
+#define SEGGER_SYSVIEW_VERSION        ((SEGGER_SYSVIEW_MAJOR * 10000) + (SEGGER_SYSVIEW_MINOR * 100) + SEGGER_SYSVIEW_REV)
+
+#define SEGGER_SYSVIEW_INFO_SIZE      9   // Minimum size, which has to be reserved for a packet. 1-2 byte of message type, 0-2  byte of payload length, 1-5 bytes of timestamp.
+#define SEGGER_SYSVIEW_QUANTA_U32     5   // Maximum number of bytes to encode a U32, should be reserved for each 32-bit value in a packet.
+
+#define SEGGER_SYSVIEW_LOG            (0u)
+#define SEGGER_SYSVIEW_WARNING        (1u)
+#define SEGGER_SYSVIEW_ERROR          (2u)
+#define SEGGER_SYSVIEW_FLAG_APPEND    (1u << 6)
+
+#define SEGGER_SYSVIEW_PREPARE_PACKET(p)  (p) + 4
+//
+// SystemView events. First 32 IDs from 0 .. 31 are reserved for these
+//
+#define   SYSVIEW_EVTID_NOP                0  // Dummy packet.
+#define   SYSVIEW_EVTID_OVERFLOW           1
+#define   SYSVIEW_EVTID_ISR_ENTER          2
+#define   SYSVIEW_EVTID_ISR_EXIT           3
+#define   SYSVIEW_EVTID_TASK_START_EXEC    4
+#define   SYSVIEW_EVTID_TASK_STOP_EXEC     5
+#define   SYSVIEW_EVTID_TASK_START_READY   6
+#define   SYSVIEW_EVTID_TASK_STOP_READY    7
+#define   SYSVIEW_EVTID_TASK_CREATE        8
+#define   SYSVIEW_EVTID_TASK_INFO          9
+#define   SYSVIEW_EVTID_TRACE_START       10
+#define   SYSVIEW_EVTID_TRACE_STOP        11
+#define   SYSVIEW_EVTID_SYSTIME_CYCLES    12
+#define   SYSVIEW_EVTID_SYSTIME_US        13
+#define   SYSVIEW_EVTID_SYSDESC           14
+#define   SYSVIEW_EVTID_MARK_START        15
+#define   SYSVIEW_EVTID_MARK_STOP         16
+#define   SYSVIEW_EVTID_IDLE              17
+#define   SYSVIEW_EVTID_ISR_TO_SCHEDULER  18
+#define   SYSVIEW_EVTID_TIMER_ENTER       19
+#define   SYSVIEW_EVTID_TIMER_EXIT        20
+#define   SYSVIEW_EVTID_STACK_INFO        21
+#define   SYSVIEW_EVTID_MODULEDESC        22
+
+#define   SYSVIEW_EVTID_INIT              24
+#define   SYSVIEW_EVTID_NAME_RESOURCE     25
+#define   SYSVIEW_EVTID_PRINT_FORMATTED   26
+#define   SYSVIEW_EVTID_NUMMODULES        27
+#define   SYSVIEW_EVTID_END_CALL          28
+#define   SYSVIEW_EVTID_TASK_TERMINATE    29
+
+#define   SYSVIEW_EVTID_EX                31
+//
+// SystemView extended events. Sent with ID 31.
+//
+#define   SYSVIEW_EVTID_EX_MARK            0
+#define   SYSVIEW_EVTID_EX_NAME_MARKER     1
+//
+// Event masks to disable/enable events
+//
+#define   SYSVIEW_EVTMASK_NOP               (1 << SYSVIEW_EVTID_NOP)
+#define   SYSVIEW_EVTMASK_OVERFLOW          (1 << SYSVIEW_EVTID_OVERFLOW)
+#define   SYSVIEW_EVTMASK_ISR_ENTER         (1 << SYSVIEW_EVTID_ISR_ENTER)
+#define   SYSVIEW_EVTMASK_ISR_EXIT          (1 << SYSVIEW_EVTID_ISR_EXIT)
+#define   SYSVIEW_EVTMASK_TASK_START_EXEC   (1 << SYSVIEW_EVTID_TASK_START_EXEC)
+#define   SYSVIEW_EVTMASK_TASK_STOP_EXEC    (1 << SYSVIEW_EVTID_TASK_STOP_EXEC)
+#define   SYSVIEW_EVTMASK_TASK_START_READY  (1 << SYSVIEW_EVTID_TASK_START_READY)
+#define   SYSVIEW_EVTMASK_TASK_STOP_READY   (1 << SYSVIEW_EVTID_TASK_STOP_READY)
+#define   SYSVIEW_EVTMASK_TASK_CREATE       (1 << SYSVIEW_EVTID_TASK_CREATE)
+#define   SYSVIEW_EVTMASK_TASK_INFO         (1 << SYSVIEW_EVTID_TASK_INFO)
+#define   SYSVIEW_EVTMASK_TRACE_START       (1 << SYSVIEW_EVTID_TRACE_START)
+#define   SYSVIEW_EVTMASK_TRACE_STOP        (1 << SYSVIEW_EVTID_TRACE_STOP)
+#define   SYSVIEW_EVTMASK_SYSTIME_CYCLES    (1 << SYSVIEW_EVTID_SYSTIME_CYCLES)
+#define   SYSVIEW_EVTMASK_SYSTIME_US        (1 << SYSVIEW_EVTID_SYSTIME_US)
+#define   SYSVIEW_EVTMASK_SYSDESC           (1 << SYSVIEW_EVTID_SYSDESC)
+#define   SYSVIEW_EVTMASK_USER_START        (1 << SYSVIEW_EVTID_USER_START)
+#define   SYSVIEW_EVTMASK_USER_STOP         (1 << SYSVIEW_EVTID_USER_STOP)
+#define   SYSVIEW_EVTMASK_IDLE              (1 << SYSVIEW_EVTID_IDLE)
+#define   SYSVIEW_EVTMASK_ISR_TO_SCHEDULER  (1 << SYSVIEW_EVTID_ISR_TO_SCHEDULER)
+#define   SYSVIEW_EVTMASK_TIMER_ENTER       (1 << SYSVIEW_EVTID_TIMER_ENTER)
+#define   SYSVIEW_EVTMASK_TIMER_EXIT        (1 << SYSVIEW_EVTID_TIMER_EXIT)
+#define   SYSVIEW_EVTMASK_STACK_INFO        (1 << SYSVIEW_EVTID_STACK_INFO)
+#define   SYSVIEW_EVTMASK_MODULEDESC        (1 << SYSVIEW_EVTID_MODULEDESC)
+
+#define   SYSVIEW_EVTMASK_INIT              (1 << SYSVIEW_EVTID_INIT)
+#define   SYSVIEW_EVTMASK_NAME_RESOURCE     (1 << SYSVIEW_EVTID_NAME_RESOURCE)
+#define   SYSVIEW_EVTMASK_PRINT_FORMATTED   (1 << SYSVIEW_EVTID_PRINT_FORMATTED)
+#define   SYSVIEW_EVTMASK_NUMMODULES        (1 << SYSVIEW_EVTID_NUMMODULES)
+#define   SYSVIEW_EVTMASK_END_CALL          (1 << SYSVIEW_EVTID_END_CALL)
+#define   SYSVIEW_EVTMASK_TASK_TERMINATE    (1 << SYSVIEW_EVTID_TASK_TERMINATE)
+
+#define   SYSVIEW_EVTMASK_EX                (1 << SYSVIEW_EVTID_EX)
+
+#define   SYSVIEW_EVTMASK_ALL_INTERRUPTS    ( SYSVIEW_EVTMASK_ISR_ENTER           \
+                                            | SYSVIEW_EVTMASK_ISR_EXIT            \
+                                            | SYSVIEW_EVTMASK_ISR_TO_SCHEDULER)
+#define   SYSVIEW_EVTMASK_ALL_TASKS         ( SYSVIEW_EVTMASK_TASK_START_EXEC     \
+                                            | SYSVIEW_EVTMASK_TASK_STOP_EXEC      \
+                                            | SYSVIEW_EVTMASK_TASK_START_READY    \
+                                            | SYSVIEW_EVTMASK_TASK_STOP_READY     \
+                                            | SYSVIEW_EVTMASK_TASK_CREATE         \
+                                            | SYSVIEW_EVTMASK_TASK_INFO           \
+                                            | SYSVIEW_EVTMASK_STACK_INFO          \
+                                            | SYSVIEW_EVTMASK_TASK_TERMINATE)
+
+/*********************************************************************
+*
+*       Structures
+*
+**********************************************************************
+*/
+
+typedef struct {
+  U32          TaskID;
+  const char*  sName;
+  U32          Prio;
+  U32          StackBase;
+  U32          StackSize;
+} SEGGER_SYSVIEW_TASKINFO;
+
+typedef struct SEGGER_SYSVIEW_MODULE_STRUCT SEGGER_SYSVIEW_MODULE;
+
+struct SEGGER_SYSVIEW_MODULE_STRUCT {
+  const char*                   sModule;
+        U32                     NumEvents;
+        U32                     EventOffset;
+        void                    (*pfSendModuleDesc)(void);
+        SEGGER_SYSVIEW_MODULE*  pNext;
+};
+
+typedef void (SEGGER_SYSVIEW_SEND_SYS_DESC_FUNC)(void);
+
+
+/*********************************************************************
+*
+*       Global data
+*
+**********************************************************************
+*/
+
+#ifdef   EXTERN
+  #undef EXTERN
+#endif
+
+#ifndef SEGGER_SYSVIEW_C       // Defined in SEGGER_SYSVIEW.c which includes this header beside other C-files
+  #define EXTERN extern
+#else
+  #define EXTERN
+#endif
+
+EXTERN unsigned int SEGGER_SYSVIEW_TickCnt;
+EXTERN unsigned int SEGGER_SYSVIEW_InterruptId;
+
+#undef EXTERN
+
+/*********************************************************************
+*
+*       API functions
+*
+**********************************************************************
+*/
+
+typedef struct {
+  U64  (*pfGetTime)      (void);
+  void (*pfSendTaskList) (void);
+} SEGGER_SYSVIEW_OS_API;
+
+/*********************************************************************
+*
+*       Control and initialization functions
+*/
+void SEGGER_SYSVIEW_Init                          (U32 SysFreq, U32 CPUFreq, const SEGGER_SYSVIEW_OS_API *pOSAPI, SEGGER_SYSVIEW_SEND_SYS_DESC_FUNC pfSendSysDesc);
+void SEGGER_SYSVIEW_SetRAMBase                    (U32 RAMBaseAddress);
+void SEGGER_SYSVIEW_Start                         (void);
+void SEGGER_SYSVIEW_Stop                          (void);
+void SEGGER_SYSVIEW_GetSysDesc                    (void);
+void SEGGER_SYSVIEW_SendTaskList                  (void);
+void SEGGER_SYSVIEW_SendTaskInfo                  (const SEGGER_SYSVIEW_TASKINFO* pInfo);
+void SEGGER_SYSVIEW_SendSysDesc                   (const char* sSysDesc);
+int  SEGGER_SYSVIEW_IsStarted                     (void);
+int  SEGGER_SYSVIEW_GetChannelID                  (void);
+
+/*********************************************************************
+*
+*       Event recording functions
+*/
+void SEGGER_SYSVIEW_RecordVoid                    (unsigned int EventId);
+void SEGGER_SYSVIEW_RecordU32                     (unsigned int EventId, U32 Para0);
+void SEGGER_SYSVIEW_RecordU32x2                   (unsigned int EventId, U32 Para0, U32 Para1);
+void SEGGER_SYSVIEW_RecordU32x3                   (unsigned int EventId, U32 Para0, U32 Para1, U32 Para2);
+void SEGGER_SYSVIEW_RecordU32x4                   (unsigned int EventId, U32 Para0, U32 Para1, U32 Para2, U32 Para3);
+void SEGGER_SYSVIEW_RecordU32x5                   (unsigned int EventId, U32 Para0, U32 Para1, U32 Para2, U32 Para3, U32 Para4);
+void SEGGER_SYSVIEW_RecordU32x6                   (unsigned int EventId, U32 Para0, U32 Para1, U32 Para2, U32 Para3, U32 Para4, U32 Para5);
+void SEGGER_SYSVIEW_RecordU32x7                   (unsigned int EventId, U32 Para0, U32 Para1, U32 Para2, U32 Para3, U32 Para4, U32 Para5, U32 Para6);
+void SEGGER_SYSVIEW_RecordU32x8                   (unsigned int EventId, U32 Para0, U32 Para1, U32 Para2, U32 Para3, U32 Para4, U32 Para5, U32 Para6, U32 Para7);
+void SEGGER_SYSVIEW_RecordU32x9                   (unsigned int EventId, U32 Para0, U32 Para1, U32 Para2, U32 Para3, U32 Para4, U32 Para5, U32 Para6, U32 Para7, U32 Para8);
+void SEGGER_SYSVIEW_RecordU32x10                  (unsigned int EventId, U32 Para0, U32 Para1, U32 Para2, U32 Para3, U32 Para4, U32 Para5, U32 Para6, U32 Para7, U32 Para8, U32 Para9);
+void SEGGER_SYSVIEW_RecordString                  (unsigned int EventId, const char* pString);
+void SEGGER_SYSVIEW_RecordSystime                 (void);
+void SEGGER_SYSVIEW_RecordEnterISR                (void);
+void SEGGER_SYSVIEW_RecordExitISR                 (void);
+void SEGGER_SYSVIEW_RecordExitISRToScheduler      (void);
+void SEGGER_SYSVIEW_RecordEnterTimer              (U32 TimerId);
+void SEGGER_SYSVIEW_RecordExitTimer               (void);
+void SEGGER_SYSVIEW_RecordEndCall                 (unsigned int EventID);
+void SEGGER_SYSVIEW_RecordEndCallU32              (unsigned int EventID, U32 Para0);
+
+void SEGGER_SYSVIEW_OnIdle                        (void);
+void SEGGER_SYSVIEW_OnTaskCreate                  (U32 TaskId);
+void SEGGER_SYSVIEW_OnTaskTerminate               (U32 TaskId);
+void SEGGER_SYSVIEW_OnTaskStartExec               (U32 TaskId);
+void SEGGER_SYSVIEW_OnTaskStopExec                (void);
+void SEGGER_SYSVIEW_OnTaskStartReady              (U32 TaskId);
+void SEGGER_SYSVIEW_OnTaskStopReady               (U32 TaskId, unsigned int Cause);
+void SEGGER_SYSVIEW_MarkStart                     (unsigned int MarkerId);
+void SEGGER_SYSVIEW_MarkStop                      (unsigned int MarkerId);
+void SEGGER_SYSVIEW_Mark                          (unsigned int MarkerId);
+void SEGGER_SYSVIEW_NameMarker                    (unsigned int MarkerId, const char* sName);
+
+void SEGGER_SYSVIEW_NameResource                  (U32 ResourceId, const char* sName);
+
+int  SEGGER_SYSVIEW_SendPacket                    (U8* pPacket, U8* pPayloadEnd, unsigned int EventId);
+
+/*********************************************************************
+*
+*       Event parameter encoding functions
+*/
+U8*  SEGGER_SYSVIEW_EncodeU32                     (U8* pPayload, U32 Value);
+U8*  SEGGER_SYSVIEW_EncodeData                    (U8* pPayload, const char* pSrc, unsigned int Len);
+U8*  SEGGER_SYSVIEW_EncodeString                  (U8* pPayload, const char* s, unsigned int MaxLen);
+U8*  SEGGER_SYSVIEW_EncodeId                      (U8* pPayload, U32 Id);
+U32  SEGGER_SYSVIEW_ShrinkId                      (U32 Id);
+
+
+/*********************************************************************
+*
+*       Middleware module registration
+*/
+void SEGGER_SYSVIEW_RegisterModule                (SEGGER_SYSVIEW_MODULE* pModule);
+void SEGGER_SYSVIEW_RecordModuleDescription       (const SEGGER_SYSVIEW_MODULE* pModule, const char* sDescription);
+void SEGGER_SYSVIEW_SendModule                    (U8 ModuleId);
+void SEGGER_SYSVIEW_SendModuleDescription         (void);
+void SEGGER_SYSVIEW_SendNumModules                (void);
+
+/*********************************************************************
+*
+*       printf-Style functions
+*/
+#ifndef SEGGER_SYSVIEW_EXCLUDE_PRINTF // Define in project to avoid warnings about variable parameter list
+void SEGGER_SYSVIEW_PrintfHostEx                  (const char* s, U32 Options, ...);
+void SEGGER_SYSVIEW_PrintfTargetEx                (const char* s, U32 Options, ...);
+void SEGGER_SYSVIEW_PrintfHost                    (const char* s, ...);
+void SEGGER_SYSVIEW_PrintfTarget                  (const char* s, ...);
+void SEGGER_SYSVIEW_WarnfHost                     (const char* s, ...);
+void SEGGER_SYSVIEW_WarnfTarget                   (const char* s, ...);
+void SEGGER_SYSVIEW_ErrorfHost                    (const char* s, ...);
+void SEGGER_SYSVIEW_ErrorfTarget                  (const char* s, ...);
+#endif
+
+void SEGGER_SYSVIEW_Print                         (const char* s);
+void SEGGER_SYSVIEW_Warn                          (const char* s);
+void SEGGER_SYSVIEW_Error                         (const char* s);
+
+/*********************************************************************
+*
+*       Run-time configuration functions
+*/
+void SEGGER_SYSVIEW_EnableEvents                  (U32 EnableMask);
+void SEGGER_SYSVIEW_DisableEvents                 (U32 DisableMask);
+
+/*********************************************************************
+*
+*       Application-provided functions
+*/
+void SEGGER_SYSVIEW_Conf                          (void);
+U32  SEGGER_SYSVIEW_X_GetTimestamp                (void);
+U32  SEGGER_SYSVIEW_X_GetInterruptId              (void);
+
+void SEGGER_SYSVIEW_X_StartComm                   (void);
+void SEGGER_SYSVIEW_X_OnEventRecorded             (unsigned NumBytes);
+
+#ifdef __cplusplus
+}
+#endif
+
+/*********************************************************************
+*
+*       Compatibility API defines
+*/
+#define SEGGER_SYSVIEW_OnUserStart      SEGGER_SYSVIEW_MarkStart
+#define SEGGER_SYSVIEW_OnUserStop       SEGGER_SYSVIEW_MarkStop
+
+#endif
+
+/*************************** End of file ****************************/

+ 85 - 0
code/debug/SEGGER/SEGGER_SYSVIEW_Conf.h

@@ -0,0 +1,85 @@
+/*********************************************************************
+*                    SEGGER Microcontroller GmbH                     *
+*                        The Embedded Experts                        *
+**********************************************************************
+*                                                                    *
+*            (c) 1995 - 2021 SEGGER Microcontroller GmbH             *
+*                                                                    *
+*       www.segger.com     Support: support@segger.com               *
+*                                                                    *
+**********************************************************************
+*                                                                    *
+*       SEGGER SystemView * Real-time application analysis           *
+*                                                                    *
+**********************************************************************
+*                                                                    *
+* All rights reserved.                                               *
+*                                                                    *
+* SEGGER strongly recommends to not make any changes                 *
+* to or modify the source code of this software in order to stay     *
+* compatible with the SystemView and RTT protocol, and J-Link.       *
+*                                                                    *
+* Redistribution and use in source and binary forms, with or         *
+* without modification, are permitted provided that the following    *
+* condition is met:                                                  *
+*                                                                    *
+* o Redistributions of source code must retain the above copyright   *
+*   notice, this condition and the following disclaimer.             *
+*                                                                    *
+* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND             *
+* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,        *
+* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF           *
+* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE           *
+* DISCLAIMED. IN NO EVENT SHALL SEGGER Microcontroller BE LIABLE FOR *
+* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR           *
+* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT  *
+* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;    *
+* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF      *
+* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT          *
+* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE  *
+* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH   *
+* DAMAGE.                                                            *
+*                                                                    *
+**********************************************************************
+*                                                                    *
+*       SystemView version: 3.32                                    *
+*                                                                    *
+**********************************************************************
+-------------------------- END-OF-HEADER -----------------------------
+
+File    : SEGGER_SYSVIEW_Conf.h
+Purpose : SEGGER SystemView configuration file.
+          Set defines which deviate from the defaults (see SEGGER_SYSVIEW_ConfDefaults.h) here.          
+Revision: $Rev: 21292 $
+
+Additional information:
+  Required defines which must be set are:
+    SEGGER_SYSVIEW_GET_TIMESTAMP
+    SEGGER_SYSVIEW_GET_INTERRUPT_ID
+  For known compilers and cores, these might be set to good defaults
+  in SEGGER_SYSVIEW_ConfDefaults.h.
+  
+  SystemView needs a (nestable) locking mechanism.
+  If not defined, the RTT locking mechanism is used,
+  which then needs to be properly configured.
+*/
+
+#ifndef SEGGER_SYSVIEW_CONF_H
+#define SEGGER_SYSVIEW_CONF_H
+
+/*********************************************************************
+*
+*       Defines, configurable
+*
+**********************************************************************
+*/
+
+/*********************************************************************
+* TODO: Add your defines here.                                       *
+**********************************************************************
+*/
+
+
+#endif  // SEGGER_SYSVIEW_CONF_H
+
+/*************************** End of file ****************************/

+ 579 - 0
code/debug/SEGGER/SEGGER_SYSVIEW_ConfDefaults.h

@@ -0,0 +1,579 @@
+/*********************************************************************
+*                    SEGGER Microcontroller GmbH                     *
+*                        The Embedded Experts                        *
+**********************************************************************
+*                                                                    *
+*            (c) 1995 - 2021 SEGGER Microcontroller GmbH             *
+*                                                                    *
+*       www.segger.com     Support: support@segger.com               *
+*                                                                    *
+**********************************************************************
+*                                                                    *
+*       SEGGER SystemView * Real-time application analysis           *
+*                                                                    *
+**********************************************************************
+*                                                                    *
+* All rights reserved.                                               *
+*                                                                    *
+* SEGGER strongly recommends to not make any changes                 *
+* to or modify the source code of this software in order to stay     *
+* compatible with the SystemView and RTT protocol, and J-Link.       *
+*                                                                    *
+* Redistribution and use in source and binary forms, with or         *
+* without modification, are permitted provided that the following    *
+* condition is met:                                                  *
+*                                                                    *
+* o Redistributions of source code must retain the above copyright   *
+*   notice, this condition and the following disclaimer.             *
+*                                                                    *
+* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND             *
+* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,        *
+* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF           *
+* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE           *
+* DISCLAIMED. IN NO EVENT SHALL SEGGER Microcontroller BE LIABLE FOR *
+* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR           *
+* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT  *
+* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;    *
+* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF      *
+* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT          *
+* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE  *
+* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH   *
+* DAMAGE.                                                            *
+*                                                                    *
+**********************************************************************
+*                                                                    *
+*       SystemView version: 3.32                                    *
+*                                                                    *
+**********************************************************************
+-------------------------- END-OF-HEADER -----------------------------
+File    : SEGGER_SYSVIEW_ConfDefaults.h
+Purpose : Defines defaults for configurable defines used in
+          SEGGER SystemView.
+Revision: $Rev: 26230 $
+*/
+
+#ifndef SEGGER_SYSVIEW_CONFDEFAULTS_H
+#define SEGGER_SYSVIEW_CONFDEFAULTS_H
+
+/*********************************************************************
+*
+*       #include Section
+*
+**********************************************************************
+*/
+
+#include "SEGGER_SYSVIEW_Conf.h"
+#include "SEGGER_RTT_Conf.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/*********************************************************************
+*
+*       Defines, fixed
+*
+**********************************************************************
+*/
+//
+// Use auto-detection for SEGGER_SYSVIEW_CORE define
+// based on compiler-/toolchain-specific defines
+// to define SEGGER_SYSVIEW_GET_INTERRUPT_ID and SEGGER_SYSVIEW_GET_TIMESTAMP
+//
+#define SEGGER_SYSVIEW_CORE_OTHER   0
+#define SEGGER_SYSVIEW_CORE_CM0     1 // Cortex-M0/M0+/M1
+#define SEGGER_SYSVIEW_CORE_CM3     2 // Cortex-M3/M4/M7
+#define SEGGER_SYSVIEW_CORE_RX      3 // Renesas RX
+#ifndef SEGGER_SYSVIEW_CORE
+  #if (defined __SES_ARM) || (defined __CROSSWORKS_ARM) || (defined __SEGGER_CC__) || (defined __GNUC__) || (defined __clang__)
+    #if (defined __ARM_ARCH_6M__) || (defined __ARM_ARCH_8M_BASE__)
+      #define SEGGER_SYSVIEW_CORE SEGGER_SYSVIEW_CORE_CM0
+    #elif (defined(__ARM_ARCH_7M__) || defined(__ARM_ARCH_7EM__) || defined(__ARM_ARCH_8M_MAIN__))
+      #define SEGGER_SYSVIEW_CORE SEGGER_SYSVIEW_CORE_CM3
+    #endif
+  #elif defined(__ICCARM__)
+    #if (defined (__ARM6M__)          && (__CORE__ == __ARM6M__))          \
+     || (defined (__ARM8M_BASELINE__) && (__CORE__ == __ARM8M_BASELINE__))
+      #define SEGGER_SYSVIEW_CORE SEGGER_SYSVIEW_CORE_CM0
+    #elif (defined (__ARM7EM__)         && (__CORE__ == __ARM7EM__))         \
+       || (defined (__ARM7M__)          && (__CORE__ == __ARM7M__))          \
+       || (defined (__ARM8M_MAINLINE__) && (__CORE__ == __ARM8M_MAINLINE__)) \
+       || (defined (__ARM8M_MAINLINE__) && (__CORE__ == __ARM8M_MAINLINE__))
+      #define SEGGER_SYSVIEW_CORE SEGGER_SYSVIEW_CORE_CM3
+    #endif
+  #elif defined(__CC_ARM)
+    #if (defined(__TARGET_ARCH_6S_M))
+      #define SEGGER_SYSVIEW_CORE SEGGER_SYSVIEW_CORE_CM0
+    #elif (defined(__TARGET_ARCH_7_M) || defined(__TARGET_ARCH_7E_M))
+      #define SEGGER_SYSVIEW_CORE SEGGER_SYSVIEW_CORE_CM3
+    #endif
+  #elif defined(__TI_ARM__)
+    #ifdef __TI_ARM_V6M0__
+      #define SEGGER_SYSVIEW_CORE SEGGER_SYSVIEW_CORE_CM0
+    #elif (defined(__TI_ARM_V7M3__) || defined(__TI_ARM_V7M4__))
+      #define SEGGER_SYSVIEW_CORE SEGGER_SYSVIEW_CORE_CM3
+    #endif
+  #elif defined(__ICCRX__)
+    #define SEGGER_SYSVIEW_CORE SEGGER_SYSVIEW_CORE_RX
+  #elif defined(__RX)
+    #define SEGGER_SYSVIEW_CORE SEGGER_SYSVIEW_CORE_RX
+  #endif
+
+  #ifndef   SEGGER_SYSVIEW_CORE
+    #define SEGGER_SYSVIEW_CORE SEGGER_SYSVIEW_CORE_OTHER
+  #endif
+#endif
+
+
+/*********************************************************************
+*
+*       Defines, defaults
+*
+**********************************************************************
+*/
+/*********************************************************************
+*
+*       Define: SEGGER_SYSVIEW_APP_NAME
+*
+*  Description
+*    The application name to be displayed in SystemView.
+*  Default
+*    "SystemView-enabled Application"
+*  Notes
+*    Convenience define to be used for SEGGER_SYSVIEW_SendSysDesc().
+*/
+#ifndef   SEGGER_SYSVIEW_APP_NAME
+  #define SEGGER_SYSVIEW_APP_NAME                 "SystemView-enabled Application"
+#endif
+
+/*********************************************************************
+*
+*       Define: SEGGER_SYSVIEW_DEVICE_NAME
+*
+*  Description
+*    The target device name to be displayed in SystemView.
+*  Default
+*    "undefined device"
+*  Notes
+*    Convenience define to be used for SEGGER_SYSVIEW_SendSysDesc().
+*/
+#ifndef   SEGGER_SYSVIEW_DEVICE_NAME
+  #define SEGGER_SYSVIEW_DEVICE_NAME              "undefined device"
+#endif
+
+/*********************************************************************
+*
+*       Define: SEGGER_SYSVIEW_GET_INTERRUPT_ID()
+*
+*  Description
+*    Function macro to retrieve the Id of the currently active
+*    interrupt.
+*  Default
+*    Call user-supplied function SEGGER_SYSVIEW_X_GetInterruptId().
+*  Notes
+*    For some known compilers and cores, a ready-to-use, core-specific
+*    default is set.
+*    ARMv7M: Read ICSR[8:0] (active vector)
+*    ARMv6M: Read ICSR[5:0] (active vector)
+*/
+#ifndef SEGGER_SYSVIEW_GET_INTERRUPT_ID
+  #if SEGGER_SYSVIEW_CORE == SEGGER_SYSVIEW_CORE_CM3
+    #define SEGGER_SYSVIEW_GET_INTERRUPT_ID()     ((*(U32*)(0xE000ED04)) & 0x1FF)         // Get the currently active interrupt Id. (i.e. read Cortex-M ICSR[8:0] = active vector)
+  #elif SEGGER_SYSVIEW_CORE == SEGGER_SYSVIEW_CORE_CM0
+    #if defined(__ICCARM__)
+      #if (__VER__ > 6010000)
+        #define SEGGER_SYSVIEW_GET_INTERRUPT_ID() (__get_IPSR())                          // Workaround for IAR, which might do a byte-access to 0xE000ED04. Read IPSR instead.
+      #else
+        #define SEGGER_SYSVIEW_GET_INTERRUPT_ID() ((*(U32*)(0xE000ED04)) & 0x3F)          // Older versions of IAR do not include __get_IPSR, but might also not optimize to byte-access.
+      #endif
+    #else
+      #define SEGGER_SYSVIEW_GET_INTERRUPT_ID()   ((*(U32*)(0xE000ED04)) & 0x3F)          // Get the currently active interrupt Id. (i.e. read Cortex-M ICSR[5:0] = active vector)
+    #endif
+  #else
+    #define SEGGER_SYSVIEW_GET_INTERRUPT_ID()     SEGGER_SYSVIEW_X_GetInterruptId()       // Get the currently active interrupt Id from the user-provided function.
+  #endif
+#endif
+
+/*********************************************************************
+*
+*       Define: SEGGER_SYSVIEW_GET_TIMESTAMP()
+*
+*  Description
+*    Function macro to retrieve a system timestamp for SYSVIEW events.
+*  Default
+*    Call user-supplied function SEGGER_SYSVIEW_X_GetTimestamp().
+*  Notes
+*    For some known compilers and cores, a ready-to-use, core-specific
+*    default is set.
+*    ARMv7M: Read Cortex-M Cycle Count register.
+*
+*    The system timestamp clock frequency has to be passed in
+*    SEGGER_SYSVIEW_Init().
+*/
+#ifndef SEGGER_SYSVIEW_GET_TIMESTAMP
+  #if defined (SEGGER_SYSVIEW_CORE) && (SEGGER_SYSVIEW_CORE == SEGGER_SYSVIEW_CORE_CM3)
+    #define SEGGER_SYSVIEW_GET_TIMESTAMP()        (*(U32 *)(0xE0001004))                  // Retrieve a system timestamp. Cortex-M cycle counter.
+  #else
+    #define SEGGER_SYSVIEW_GET_TIMESTAMP()        SEGGER_SYSVIEW_X_GetTimestamp()         // Retrieve a system timestamp via user-defined function
+  #endif
+#endif
+
+/*********************************************************************
+*
+*       Define: SEGGER_SYSVIEW_TIMESTAMP_BITS
+*
+*  Description
+*    Number of valid (low-order) bits delivered in system timestamp.
+*  Default
+*    32
+*  Notes
+*    Value has to match system timestamp clock source.
+*/
+// Define number of valid bits low-order delivered by clock source.
+#ifndef   SEGGER_SYSVIEW_TIMESTAMP_BITS
+  #define SEGGER_SYSVIEW_TIMESTAMP_BITS           32
+#endif
+
+/*********************************************************************
+*
+*       Define: SEGGER_SYSVIEW_RTT_CHANNEL
+*
+*  Description
+*    The RTT channel that SystemView will use.
+*  Default
+*    0: Auto selection.
+*  Notes
+*    Value has to be lower than SEGGER_RTT_MAX_NUM_UP_BUFFERS.
+*/
+#ifndef   SEGGER_SYSVIEW_RTT_CHANNEL
+  #define SEGGER_SYSVIEW_RTT_CHANNEL              0
+#endif
+// Sanity check of RTT channel
+#if (SEGGER_SYSVIEW_RTT_CHANNEL == 0) && (SEGGER_RTT_MAX_NUM_UP_BUFFERS < 2)
+  #error "SEGGER_RTT_MAX_NUM_UP_BUFFERS in SEGGER_RTT_Conf.h has to be > 1!"
+#elif (SEGGER_SYSVIEW_RTT_CHANNEL >= SEGGER_RTT_MAX_NUM_UP_BUFFERS)
+  #error "SEGGER_RTT_MAX_NUM_UP_BUFFERS  in SEGGER_RTT_Conf.h has to be > SEGGER_SYSVIEW_RTT_CHANNEL!"
+#endif
+
+/*********************************************************************
+*
+*       Define: SEGGER_SYSVIEW_RTT_BUFFER_SIZE
+*
+*  Description
+*    Number of bytes that SystemView uses for the RTT buffer.
+*  Default
+*    1024
+*/
+#ifndef   SEGGER_SYSVIEW_RTT_BUFFER_SIZE
+  #define SEGGER_SYSVIEW_RTT_BUFFER_SIZE          1024
+#endif
+
+/*********************************************************************
+*
+*       Define: SEGGER_SYSVIEW_SECTION
+*
+*  Description
+*    Section to place the SystemView RTT Buffer into.
+*  Default
+*    undefined: Do not place into a specific section.
+*  Notes
+*    If SEGGER_RTT_SECTION is defined, the default changes to use
+*    this section for the SystemView RTT Buffer, too.
+*/
+#if !(defined SEGGER_SYSVIEW_SECTION) && (defined SEGGER_RTT_SECTION)
+  #define SEGGER_SYSVIEW_SECTION                  SEGGER_RTT_SECTION
+#endif
+
+/*********************************************************************
+*
+*       Define: SEGGER_SYSVIEW_CPU_CACHE_LINE_SIZE
+*
+*  Description
+*    Largest cache line size (in bytes) in the target system.
+*  Default
+*    0
+*  Notes
+*    Required in systems with caches to make sure that the SystemView
+*    RTT buffer can be aligned accordingly.
+*/
+#ifndef SEGGER_SYSVIEW_CPU_CACHE_LINE_SIZE
+  #define SEGGER_SYSVIEW_CPU_CACHE_LINE_SIZE      0
+#endif
+
+/*********************************************************************
+*
+*       Define: SEGGER_SYSVIEW_ID_BASE
+*
+*  Description
+*    Lowest Id reported by the application.
+*  Default
+*    0
+*  Notes
+*    Value is usually subtracted from mailboxes, semaphores, tasks,
+*    .... addresses, to compress event parameters.
+*    Should be the lowest RAM address of the system.
+*/
+#ifndef   SEGGER_SYSVIEW_ID_BASE
+  #define SEGGER_SYSVIEW_ID_BASE                  0
+#endif
+
+/*********************************************************************
+*
+*       Define: SEGGER_SYSVIEW_ID_SHIFT
+*
+*  Description
+*    Number of bits to shift Ids.
+*  Default
+*    0
+*  Notes
+*    Ids are shifted to compress event parameters.
+*    Should match the alignment of Ids (addresses),
+*    e.g. 2 when Ids are 4 byte aligned.
+*/
+#ifndef   SEGGER_SYSVIEW_ID_SHIFT
+  #define SEGGER_SYSVIEW_ID_SHIFT                 0
+#endif
+
+/*********************************************************************
+*
+*       Define: SEGGER_SYSVIEW_MAX_ARGUMENTS
+*
+*  Description
+*    Maximum number of arguments which are handled with SystemView
+*    print routines or may be encoded in one recording function.
+*    routines.
+*  Default
+*    16
+*/
+#ifndef   SEGGER_SYSVIEW_MAX_ARGUMENTS
+  #define SEGGER_SYSVIEW_MAX_ARGUMENTS            16
+#endif
+
+/*********************************************************************
+*
+*       Define: SEGGER_SYSVIEW_MAX_STRING_LEN
+*
+*  Description
+*    Maximum string length which can be used in SystemView print and
+*    system description routines.
+*  Default
+*    128
+*/
+#ifndef   SEGGER_SYSVIEW_MAX_STRING_LEN
+  #define SEGGER_SYSVIEW_MAX_STRING_LEN           128
+#endif
+
+/*********************************************************************
+*
+*       Define: SEGGER_SYSVIEW_SUPPORT_LONG_ID
+*
+*  Description
+*    It set, support enconding Evend Ids longer than 14 bit.
+*  Default
+*    1
+*/
+#ifndef   SEGGER_SYSVIEW_SUPPORT_LONG_ID
+  #define SEGGER_SYSVIEW_SUPPORT_LONG_ID          1
+#endif
+
+/*********************************************************************
+*
+*       Define: SEGGER_SYSVIEW_SUPPORT_LONG_DATA
+*
+*  Description
+*    It set, support enconding event data longer than 14 bit.
+*  Default
+*    0
+*/
+#ifndef   SEGGER_SYSVIEW_SUPPORT_LONG_DATA
+  #define SEGGER_SYSVIEW_SUPPORT_LONG_DATA        0
+#endif
+
+/*********************************************************************
+*
+*       Define: SEGGER_SYSVIEW_PRINTF_IMPLICIT_FORMAT
+*
+*  Description
+*    If enabled, on SEGGER_SYSVIEW_PrintHost, check the format string
+*    and if it includes unsupported formatters, use formatting on the
+*    target instead.
+*  Default
+*    0: Disabled.
+*/
+#ifndef   SEGGER_SYSVIEW_PRINTF_IMPLICIT_FORMAT
+  #define SEGGER_SYSVIEW_PRINTF_IMPLICIT_FORMAT   0
+#endif
+
+/*********************************************************************
+*
+*       Define: SEGGER_SYSVIEW_USE_INTERNAL_RECORDER
+*
+*  Description
+*    If set, an internal recorder, such as UART or IP is used.
+*  Default
+*    0: Disabled.
+*  Notes
+*    Convenience define to be used by SEGGER_SYSVIEW_Conf(),
+*    such as in embOS configuration to enable Cortex-M cycle counter.
+*/
+#ifndef   SEGGER_SYSVIEW_USE_INTERNAL_RECORDER
+  #define SEGGER_SYSVIEW_USE_INTERNAL_RECORDER    0
+#endif
+
+/*********************************************************************
+*
+*       Define: SEGGER_SYSVIEW_CAN_RESTART
+*
+*  Description
+*    If enabled, send the SystemView start sequence on every start
+*    command, not just on the first one.
+*    Enables restart when SystemView disconnected unexpectedly.
+*  Default
+*    1: Enabled
+*/
+#ifndef   SEGGER_SYSVIEW_CAN_RESTART
+  #define SEGGER_SYSVIEW_CAN_RESTART              1
+#endif
+
+/*********************************************************************
+*
+*       Define: SEGGER_SYSVIEW_START_ON_INIT
+*
+*  Description
+*    Enable calling SEGGER_SYSVIEW_Start() after initialization.
+*  Default
+*    0: Disabled.
+*  Notes
+*    Convenience define to be used by SEGGER_SYSVIEW_Conf(),
+*    such as in embOS configuration.
+*/
+#ifndef   SEGGER_SYSVIEW_START_ON_INIT
+  #define SEGGER_SYSVIEW_START_ON_INIT            0
+#endif
+
+/*********************************************************************
+*
+*       Define: SEGGER_SYSVIEW_USE_STATIC_BUFFER
+*
+*  Description
+*    If enabled, use a static buffer instead of a buffer on the stack
+*    for SystemView event packets.
+*  Default
+*    1: Enabled.
+*  Notes
+*    If enabled, the static memory use by SystemView is increased by
+*    the maximum packet size. SystemView is locked on entry of a
+*    recording function.
+*    If disabled, the stack usage by SystemView recording functions
+*    might be increased by up to the maximum packet size. SystemView
+*    is locked when writing the packet to the RTT buffer.
+*/
+#ifndef   SEGGER_SYSVIEW_USE_STATIC_BUFFER
+  #define SEGGER_SYSVIEW_USE_STATIC_BUFFER        1
+#endif
+
+/*********************************************************************
+*
+*       Define: SEGGER_SYSVIEW_MAX_PACKET_SIZE
+*
+*  Description
+*    Maximum packet size for a SystemView event.
+*  Default
+*    Automatically calculated.
+*  Notes
+*    The maximum packet size is mainly defined by the maximum string
+*    length and the maximum number of arguments.
+*/
+#ifndef   SEGGER_SYSVIEW_MAX_PACKET_SIZE
+  #define SEGGER_SYSVIEW_MAX_PACKET_SIZE          (SEGGER_SYSVIEW_INFO_SIZE + SEGGER_SYSVIEW_MAX_STRING_LEN + 2 * SEGGER_SYSVIEW_QUANTA_U32 + SEGGER_SYSVIEW_MAX_ARGUMENTS * SEGGER_SYSVIEW_QUANTA_U32)
+#endif
+
+/*********************************************************************
+*
+*       Define: SEGGER_SYSVIEW_POST_MORTEM_MODE
+*
+*  Description
+*    If enabled, SystemView records for post-mortem analysis instead
+*    of real-time analysis.
+*  Default
+*    0: Disabled.
+*  Notes
+*    For more information refer to
+*    https://www.segger.com/products/development-tools/systemview/technology/post-mortem-mode
+*/
+#ifndef   SEGGER_SYSVIEW_POST_MORTEM_MODE
+  #define SEGGER_SYSVIEW_POST_MORTEM_MODE         0
+#endif
+
+/*********************************************************************
+*
+*       Define: SEGGER_SYSVIEW_SYNC_PERIOD_SHIFT
+*
+*  Description
+*    Configure how frequently syncronization is sent in post-mortem
+*    mode.
+*  Default
+*    8: (1 << 8) = Every 256 Events.
+*  Notes
+*    In post-mortem mode, at least one sync has to be in the RTT buffer.
+*    Recommended sync frequency: Buffer Size / 16
+*    For more information refer to
+*    https://www.segger.com/products/development-tools/systemview/technology/post-mortem-mode
+*/
+#ifndef   SEGGER_SYSVIEW_SYNC_PERIOD_SHIFT
+  #define SEGGER_SYSVIEW_SYNC_PERIOD_SHIFT        8
+#endif
+
+/*********************************************************************
+*
+*       Define: SEGGER_SYSVIEW_ON_EVENT_RECORDED()
+*
+*  Description
+*    Function macro to notify recorder about a new event in buffer.
+*  Default
+*    undefined: Do not notify recorder.
+*  Notes
+*    Used for non-J-Link recorder,
+*    such as to enable transmission via UART or notify IP task.
+*/
+#ifndef   SEGGER_SYSVIEW_ON_EVENT_RECORDED
+  #define SEGGER_SYSVIEW_ON_EVENT_RECORDED(NumBytes)
+#endif
+
+/*********************************************************************
+*
+*       Define: SEGGER_SYSVIEW_LOCK()
+*
+*  Description
+*    Function macro to (nestable) lock SystemView recording.
+*  Default
+*    Use RTT Locking mechanism (defined by SEGGER_RTT_LOCK()).
+*  Notes
+*    If SystemView recording is not locked, recording events from
+*    interrupts and tasks may lead to unpredictable, undefined, event
+*    data.
+*/
+#ifndef   SEGGER_SYSVIEW_LOCK
+  #define SEGGER_SYSVIEW_LOCK()                   SEGGER_RTT_LOCK()
+#endif
+
+/*********************************************************************
+*
+*       Define: SEGGER_SYSVIEW_UNLOCK
+*
+*  Description
+*    Function macro to unlock SystemView recording.
+*  Default
+*    Use RTT Unlocking mechanism (defined by SEGGER_RTT_UNLOCK()).
+*/
+#ifndef   SEGGER_SYSVIEW_UNLOCK
+  #define SEGGER_SYSVIEW_UNLOCK()                 SEGGER_RTT_UNLOCK()
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
+
+/*************************** End of file ****************************/

+ 104 - 0
code/debug/SEGGER/SEGGER_SYSVIEW_Config_FreeRTOS.c

@@ -0,0 +1,104 @@
+/*********************************************************************
+*                    SEGGER Microcontroller GmbH                     *
+*                        The Embedded Experts                        *
+**********************************************************************
+*                                                                    *
+*            (c) 1995 - 2021 SEGGER Microcontroller GmbH             *
+*                                                                    *
+*       www.segger.com     Support: support@segger.com               *
+*                                                                    *
+**********************************************************************
+*                                                                    *
+*       SEGGER SystemView * Real-time application analysis           *
+*                                                                    *
+**********************************************************************
+*                                                                    *
+* All rights reserved.                                               *
+*                                                                    *
+* SEGGER strongly recommends to not make any changes                 *
+* to or modify the source code of this software in order to stay     *
+* compatible with the SystemView and RTT protocol, and J-Link.       *
+*                                                                    *
+* Redistribution and use in source and binary forms, with or         *
+* without modification, are permitted provided that the following    *
+* condition is met:                                                  *
+*                                                                    *
+* o Redistributions of source code must retain the above copyright   *
+*   notice, this condition and the following disclaimer.             *
+*                                                                    *
+* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND             *
+* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,        *
+* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF           *
+* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE           *
+* DISCLAIMED. IN NO EVENT SHALL SEGGER Microcontroller BE LIABLE FOR *
+* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR           *
+* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT  *
+* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;    *
+* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF      *
+* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT          *
+* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE  *
+* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH   *
+* DAMAGE.                                                            *
+*                                                                    *
+**********************************************************************
+*                                                                    *
+*       SystemView version: 3.32                                    *
+*                                                                    *
+**********************************************************************
+-------------------------- END-OF-HEADER -----------------------------
+
+File    : SEGGER_SYSVIEW_Config_FreeRTOS.c
+Purpose : Sample setup configuration of SystemView with FreeRTOS.
+Revision: $Rev: 7745 $
+*/
+#include "FreeRTOS.h"
+#include "SEGGER_SYSVIEW.h"
+
+extern const SEGGER_SYSVIEW_OS_API SYSVIEW_X_OS_TraceAPI;
+
+/*********************************************************************
+*
+*       Defines, configurable
+*
+**********************************************************************
+*/
+// The application name to be displayed in SystemViewer
+#define SYSVIEW_APP_NAME        "FreeRTOS Demo Application"
+
+// The target device name
+#define SYSVIEW_DEVICE_NAME     "Cortex-M4"
+
+// Frequency of the timestamp. Must match SEGGER_SYSVIEW_GET_TIMESTAMP in SEGGER_SYSVIEW_Conf.h
+#define SYSVIEW_TIMESTAMP_FREQ  (configCPU_CLOCK_HZ)
+
+// System Frequency. SystemcoreClock is used in most CMSIS compatible projects.
+#define SYSVIEW_CPU_FREQ        configCPU_CLOCK_HZ
+
+// The lowest RAM address used for IDs (pointers)
+#define SYSVIEW_RAM_BASE        (0x10000000)
+
+/********************************************************************* 
+*
+*       _cbSendSystemDesc()
+*
+*  Function description
+*    Sends SystemView description strings.
+*/
+static void _cbSendSystemDesc(void) {
+  SEGGER_SYSVIEW_SendSysDesc("N="SYSVIEW_APP_NAME",D="SYSVIEW_DEVICE_NAME",O=FreeRTOS");
+  SEGGER_SYSVIEW_SendSysDesc("I#15=SysTick");
+}
+
+/*********************************************************************
+*
+*       Global functions
+*
+**********************************************************************
+*/
+void SEGGER_SYSVIEW_Conf(void) {
+  SEGGER_SYSVIEW_Init(SYSVIEW_TIMESTAMP_FREQ, SYSVIEW_CPU_FREQ, 
+                      &SYSVIEW_X_OS_TraceAPI, _cbSendSystemDesc);
+  SEGGER_SYSVIEW_SetRAMBase(SYSVIEW_RAM_BASE);
+}
+
+/*************************** End of file ****************************/

+ 252 - 0
code/debug/SEGGER/SEGGER_SYSVIEW_FreeRTOS.c

@@ -0,0 +1,252 @@
+/*********************************************************************
+*                    SEGGER Microcontroller GmbH                     *
+*                        The Embedded Experts                        *
+**********************************************************************
+*                                                                    *
+*            (c) 1995 - 2021 SEGGER Microcontroller GmbH             *
+*                                                                    *
+*       www.segger.com     Support: support@segger.com               *
+*                                                                    *
+**********************************************************************
+*                                                                    *
+*       SEGGER SystemView * Real-time application analysis           *
+*                                                                    *
+**********************************************************************
+*                                                                    *
+* All rights reserved.                                               *
+*                                                                    *
+* SEGGER strongly recommends to not make any changes                 *
+* to or modify the source code of this software in order to stay     *
+* compatible with the SystemView and RTT protocol, and J-Link.       *
+*                                                                    *
+* Redistribution and use in source and binary forms, with or         *
+* without modification, are permitted provided that the following    *
+* condition is met:                                                  *
+*                                                                    *
+* o Redistributions of source code must retain the above copyright   *
+*   notice, this condition and the following disclaimer.             *
+*                                                                    *
+* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND             *
+* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,        *
+* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF           *
+* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE           *
+* DISCLAIMED. IN NO EVENT SHALL SEGGER Microcontroller BE LIABLE FOR *
+* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR           *
+* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT  *
+* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;    *
+* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF      *
+* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT          *
+* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE  *
+* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH   *
+* DAMAGE.                                                            *
+*                                                                    *
+**********************************************************************
+*                                                                    *
+*       SystemView version: 3.32                                    *
+*                                                                    *
+**********************************************************************
+-------------------------- END-OF-HEADER -----------------------------
+
+File    : SEGGER_SYSVIEW_FreeRTOS.c
+Purpose : Interface between FreeRTOS and SystemView.
+Revision: $Rev: 7947 $
+*/
+#include "FreeRTOS.h"
+#include "task.h"
+#include "SEGGER_SYSVIEW.h"
+#include "SEGGER_SYSVIEW_FreeRTOS.h"
+#include "string.h" // Required for memset
+
+
+
+typedef struct SYSVIEW_FREERTOS_TASK_STATUS SYSVIEW_FREERTOS_TASK_STATUS;
+
+struct SYSVIEW_FREERTOS_TASK_STATUS {
+  U32         xHandle;
+  const char* pcTaskName;
+  unsigned    uxCurrentPriority;
+  U32         pxStack;
+  unsigned    uStackHighWaterMark;
+};
+
+static SYSVIEW_FREERTOS_TASK_STATUS _aTasks[SYSVIEW_FREERTOS_MAX_NOF_TASKS];
+static unsigned _NumTasks;
+
+/*********************************************************************
+*
+*       _cbSendTaskList()
+*
+*  Function description
+*    This function is part of the link between FreeRTOS and SYSVIEW.
+*    Called from SystemView when asked by the host, it uses SYSVIEW
+*    functions to send the entire task list to the host.
+*/
+static void _cbSendTaskList(void) {
+  unsigned n;
+
+  for (n = 0; n < _NumTasks; n++) {
+#if INCLUDE_uxTaskGetStackHighWaterMark // Report Task Stack High Watermark
+    _aTasks[n].uStackHighWaterMark = uxTaskGetStackHighWaterMark((TaskHandle_t)_aTasks[n].xHandle);
+#endif
+    SYSVIEW_SendTaskInfo((U32)_aTasks[n].xHandle, _aTasks[n].pcTaskName, (unsigned)_aTasks[n].uxCurrentPriority, (U32)_aTasks[n].pxStack, (unsigned)_aTasks[n].uStackHighWaterMark);
+  }
+}
+
+/*********************************************************************
+*
+*       _cbGetTime()
+*
+*  Function description
+*    This function is part of the link between FreeRTOS and SYSVIEW.
+*    Called from SystemView when asked by the host, returns the
+*    current system time in micro seconds.
+*/
+static U64 _cbGetTime(void) {
+  U64 Time;
+
+  Time = xTaskGetTickCountFromISR();
+  Time *= portTICK_PERIOD_MS;
+  Time *= 1000;
+  return Time;
+}
+
+/*********************************************************************
+*
+*       Global functions
+*
+**********************************************************************
+*/
+/*********************************************************************
+*
+*       SYSVIEW_AddTask()
+*
+*  Function description
+*    Add a task to the internal list and record its information.
+*/
+void SYSVIEW_AddTask(U32 xHandle, const char* pcTaskName, unsigned uxCurrentPriority, U32  pxStack, unsigned uStackHighWaterMark) {
+  
+  if (memcmp(pcTaskName, "IDLE", 5) == 0) {
+    return;
+  }
+  
+  if (_NumTasks >= SYSVIEW_FREERTOS_MAX_NOF_TASKS) {
+    SEGGER_SYSVIEW_Warn("SYSTEMVIEW: Could not record task information. Maximum number of tasks reached.");
+    return;
+  }
+
+  _aTasks[_NumTasks].xHandle = xHandle;
+  _aTasks[_NumTasks].pcTaskName = pcTaskName;
+  _aTasks[_NumTasks].uxCurrentPriority = uxCurrentPriority;
+  _aTasks[_NumTasks].pxStack = pxStack;
+  _aTasks[_NumTasks].uStackHighWaterMark = uStackHighWaterMark;
+
+  _NumTasks++;
+
+  SYSVIEW_SendTaskInfo(xHandle, pcTaskName,uxCurrentPriority, pxStack, uStackHighWaterMark);
+
+}
+
+/*********************************************************************
+*
+*       SYSVIEW_UpdateTask()
+*
+*  Function description
+*    Update a task in the internal list and record its information.
+*/
+void SYSVIEW_UpdateTask(U32 xHandle, const char* pcTaskName, unsigned uxCurrentPriority, U32 pxStack, unsigned uStackHighWaterMark) {
+  unsigned n;
+  
+  if (memcmp(pcTaskName, "IDLE", 5) == 0) {
+    return;
+  }
+
+  for (n = 0; n < _NumTasks; n++) {
+    if (_aTasks[n].xHandle == xHandle) {
+      break;
+    }
+  }
+  if (n < _NumTasks) {
+    _aTasks[n].pcTaskName = pcTaskName;
+    _aTasks[n].uxCurrentPriority = uxCurrentPriority;
+    _aTasks[n].pxStack = pxStack;
+    _aTasks[n].uStackHighWaterMark = uStackHighWaterMark;
+
+    SYSVIEW_SendTaskInfo(xHandle, pcTaskName, uxCurrentPriority, pxStack, uStackHighWaterMark);
+  } else {
+    SYSVIEW_AddTask(xHandle, pcTaskName, uxCurrentPriority, pxStack, uStackHighWaterMark);
+  }
+}
+
+/*********************************************************************
+*
+*       SYSVIEW_DeleteTask()
+*
+*  Function description
+*    Delete a task from the internal list.
+*/
+void SYSVIEW_DeleteTask(U32 xHandle) {
+  unsigned n;
+  
+  if (_NumTasks == 0) {
+    return; // Early out
+  }  
+  for (n = 0; n < _NumTasks; n++) {
+    if (_aTasks[n].xHandle == xHandle) {
+      break;
+    }
+  }
+  if (n == (_NumTasks - 1)) {  
+    //
+    // Task is last item in list.
+    // Simply zero the item and decrement number of tasks.
+    //
+    memset(&_aTasks[n], 0, sizeof(_aTasks[n]));
+    _NumTasks--;
+  } else if (n < _NumTasks) {
+    //
+    // Task is in the middle of the list.
+    // Move last item to current position and decrement number of tasks.
+    // Order of tasks does not really matter, so no need to move all following items.
+    //
+    _aTasks[n].xHandle             = _aTasks[_NumTasks - 1].xHandle;
+    _aTasks[n].pcTaskName          = _aTasks[_NumTasks - 1].pcTaskName;
+    _aTasks[n].uxCurrentPriority   = _aTasks[_NumTasks - 1].uxCurrentPriority;
+    _aTasks[n].pxStack             = _aTasks[_NumTasks - 1].pxStack;
+    _aTasks[n].uStackHighWaterMark = _aTasks[_NumTasks - 1].uStackHighWaterMark;
+    memset(&_aTasks[_NumTasks - 1], 0, sizeof(_aTasks[_NumTasks - 1]));
+    _NumTasks--;
+  }
+}
+
+/*********************************************************************
+*
+*       SYSVIEW_SendTaskInfo()
+*
+*  Function description
+*    Record task information.
+*/
+void SYSVIEW_SendTaskInfo(U32 TaskID, const char* sName, unsigned Prio, U32 StackBase, unsigned StackSize) {
+  SEGGER_SYSVIEW_TASKINFO TaskInfo;
+
+  memset(&TaskInfo, 0, sizeof(TaskInfo)); // Fill all elements with 0 to allow extending the structure in future version without breaking the code
+  TaskInfo.TaskID     = TaskID;
+  TaskInfo.sName      = sName;
+  TaskInfo.Prio       = Prio;
+  TaskInfo.StackBase  = StackBase;
+  TaskInfo.StackSize  = StackSize;
+  SEGGER_SYSVIEW_SendTaskInfo(&TaskInfo);
+}
+
+/*********************************************************************
+*
+*       Public API structures
+*
+**********************************************************************
+*/
+// Callbacks provided to SYSTEMVIEW by FreeRTOS
+const SEGGER_SYSVIEW_OS_API SYSVIEW_X_OS_TraceAPI = {
+  _cbGetTime,
+  _cbSendTaskList,
+};
+
+/*************************** End of file ****************************/

+ 334 - 0
code/debug/SEGGER/SEGGER_SYSVIEW_FreeRTOS.h

@@ -0,0 +1,334 @@
+/*********************************************************************
+*                    SEGGER Microcontroller GmbH                     *
+*                        The Embedded Experts                        *
+**********************************************************************
+*                                                                    *
+*            (c) 1995 - 2021 SEGGER Microcontroller GmbH             *
+*                                                                    *
+*       www.segger.com     Support: support@segger.com               *
+*                                                                    *
+**********************************************************************
+*                                                                    *
+*       SEGGER SystemView * Real-time application analysis           *
+*                                                                    *
+**********************************************************************
+*                                                                    *
+* All rights reserved.                                               *
+*                                                                    *
+* SEGGER strongly recommends to not make any changes                 *
+* to or modify the source code of this software in order to stay     *
+* compatible with the SystemView and RTT protocol, and J-Link.       *
+*                                                                    *
+* Redistribution and use in source and binary forms, with or         *
+* without modification, are permitted provided that the following    *
+* condition is met:                                                  *
+*                                                                    *
+* o Redistributions of source code must retain the above copyright   *
+*   notice, this condition and the following disclaimer.             *
+*                                                                    *
+* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND             *
+* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,        *
+* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF           *
+* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE           *
+* DISCLAIMED. IN NO EVENT SHALL SEGGER Microcontroller BE LIABLE FOR *
+* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR           *
+* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT  *
+* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;    *
+* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF      *
+* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT          *
+* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE  *
+* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH   *
+* DAMAGE.                                                            *
+*                                                                    *
+**********************************************************************
+*                                                                    *
+*       SystemView version: 3.32                                    *
+*                                                                    *
+**********************************************************************
+-------------------------- END-OF-HEADER -----------------------------
+
+File    : SEGGER_SYSVIEW_FreeRTOS.h
+Purpose : Interface between FreeRTOS and SystemView.
+          Tested with FreeRTOS V10.4.3
+Revision: $Rev: 7745 $
+
+Notes:
+  (1) Include this file at the end of FreeRTOSConfig.h
+*/
+
+#ifndef SYSVIEW_FREERTOS_H
+#define SYSVIEW_FREERTOS_H
+
+#include "SEGGER_SYSVIEW.h"
+
+/*********************************************************************
+*
+*       Defines, configurable
+*
+**********************************************************************
+*/
+#ifndef portSTACK_GROWTH
+  #define portSTACK_GROWTH              ( -1 )
+#endif
+
+#define SYSVIEW_FREERTOS_MAX_NOF_TASKS  8
+
+/*********************************************************************
+*
+*       Defines, fixed
+*
+**********************************************************************
+*/
+#define apiID_OFFSET                              (32u)
+
+#define apiID_VTASKALLOCATEMPUREGIONS             (1u)
+#define apiID_VTASKDELETE                         (2u)
+#define apiID_VTASKDELAY                          (3u)
+#define apiID_VTASKDELAYUNTIL                     (4u)
+#define apiID_UXTASKPRIORITYGET                   (5u)
+#define apiID_UXTASKPRIORITYGETFROMISR            (6u)
+#define apiID_ETASKGETSTATE                       (7u)
+#define apiID_VTASKPRIORITYSET                    (8u)
+#define apiID_VTASKSUSPEND                        (9u)
+#define apiID_VTASKRESUME                         (10u)
+#define apiID_XTASKRESUMEFROMISR                  (11u)
+#define apiID_VTASKSTARTSCHEDULER                 (12u)
+#define apiID_VTASKENDSCHEDULER                   (13u)
+#define apiID_VTASKSUSPENDALL                     (14u)
+#define apiID_XTASKRESUMEALL                      (15u)
+#define apiID_XTASKGETTICKCOUNT                   (16u)
+#define apiID_XTASKGETTICKCOUNTFROMISR            (17u)
+#define apiID_UXTASKGETNUMBEROFTASKS              (18u)
+#define apiID_PCTASKGETTASKNAME                   (19u)
+#define apiID_UXTASKGETSTACKHIGHWATERMARK         (20u)
+#define apiID_VTASKSETAPPLICATIONTASKTAG          (21u)
+#define apiID_XTASKGETAPPLICATIONTASKTAG          (22u)
+#define apiID_VTASKSETTHREADLOCALSTORAGEPOINTER   (23u)
+#define apiID_PVTASKGETTHREADLOCALSTORAGEPOINTER  (24u)
+#define apiID_XTASKCALLAPPLICATIONTASKHOOK        (25u)
+#define apiID_XTASKGETIDLETASKHANDLE              (26u)
+#define apiID_UXTASKGETSYSTEMSTATE                (27u)
+#define apiID_VTASKLIST                           (28u)
+#define apiID_VTASKGETRUNTIMESTATS                (29u)
+#define apiID_XTASKGENERICNOTIFY                  (30u)
+#define apiID_XTASKGENERICNOTIFYFROMISR           (31u)
+#define apiID_XTASKNOTIFYWAIT                     (32u)
+#define apiID_VTASKNOTIFYGIVEFROMISR              (33u)
+#define apiID_ULTASKNOTIFYTAKE                    (34u)
+#define apiID_XTASKNOTIFYSTATECLEAR               (35u)
+#define apiID_XTASKGETCURRENTTASKHANDLE           (36u)
+#define apiID_VTASKSETTIMEOUTSTATE                (37u)
+#define apiID_XTASKCHECKFORTIMEOUT                (38u)
+#define apiID_VTASKMISSEDYIELD                    (39u)
+#define apiID_XTASKGETSCHEDULERSTATE              (40u)
+#define apiID_VTASKPRIORITYINHERIT                (41u)
+#define apiID_XTASKPRIORITYDISINHERIT             (42u)
+#define apiID_XTASKGENERICCREATE                  (43u)
+#define apiID_UXTASKGETTASKNUMBER                 (44u)
+#define apiID_VTASKSETTASKNUMBER                  (45u)
+#define apiID_VTASKSTEPTICK                       (46u)
+#define apiID_ETASKCONFIRMSLEEPMODESTATUS         (47u)
+#define apiID_XTIMERCREATE                        (48u)
+#define apiID_PVTIMERGETTIMERID                   (49u)
+#define apiID_VTIMERSETTIMERID                    (50u)
+#define apiID_XTIMERISTIMERACTIVE                 (51u)
+#define apiID_XTIMERGETTIMERDAEMONTASKHANDLE      (52u)
+#define apiID_XTIMERPENDFUNCTIONCALLFROMISR       (53u)
+#define apiID_XTIMERPENDFUNCTIONCALL              (54u)
+#define apiID_PCTIMERGETTIMERNAME                 (55u)
+#define apiID_XTIMERCREATETIMERTASK               (56u)
+#define apiID_XTIMERGENERICCOMMAND                (57u)
+#define apiID_XQUEUEGENERICSEND                   (58u)
+#define apiID_XQUEUEPEEKFROMISR                   (59u)
+#define apiID_XQUEUEGENERICRECEIVE                (60u)
+#define apiID_UXQUEUEMESSAGESWAITING              (61u)
+#define apiID_UXQUEUESPACESAVAILABLE              (62u)
+#define apiID_VQUEUEDELETE                        (63u)
+#define apiID_XQUEUEGENERICSENDFROMISR            (64u)
+#define apiID_XQUEUEGIVEFROMISR                   (65u)
+#define apiID_XQUEUERECEIVEFROMISR                (66u)
+#define apiID_XQUEUEISQUEUEEMPTYFROMISR           (67u)
+#define apiID_XQUEUEISQUEUEFULLFROMISR            (68u)
+#define apiID_UXQUEUEMESSAGESWAITINGFROMISR       (69u)
+#define apiID_XQUEUEALTGENERICSEND                (70u)
+#define apiID_XQUEUEALTGENERICRECEIVE             (71u)
+#define apiID_XQUEUECRSENDFROMISR                 (72u)
+#define apiID_XQUEUECRRECEIVEFROMISR              (73u)
+#define apiID_XQUEUECRSEND                        (74u)
+#define apiID_XQUEUECRRECEIVE                     (75u)
+#define apiID_XQUEUECREATEMUTEX                   (76u)
+#define apiID_XQUEUECREATECOUNTINGSEMAPHORE       (77u)
+#define apiID_XQUEUEGETMUTEXHOLDER                (78u)
+#define apiID_XQUEUETAKEMUTEXRECURSIVE            (79u)
+#define apiID_XQUEUEGIVEMUTEXRECURSIVE            (80u)
+#define apiID_VQUEUEADDTOREGISTRY                 (81u)
+#define apiID_VQUEUEUNREGISTERQUEUE               (82u)
+#define apiID_XQUEUEGENERICCREATE                 (83u)
+#define apiID_XQUEUECREATESET                     (84u)
+#define apiID_XQUEUEADDTOSET                      (85u)
+#define apiID_XQUEUEREMOVEFROMSET                 (86u)
+#define apiID_XQUEUESELECTFROMSET                 (87u)
+#define apiID_XQUEUESELECTFROMSETFROMISR          (88u)
+#define apiID_XQUEUEGENERICRESET                  (89u)
+#define apiID_VLISTINITIALISE                     (90u)
+#define apiID_VLISTINITIALISEITEM                 (91u)
+#define apiID_VLISTINSERT                         (92u)
+#define apiID_VLISTINSERTEND                      (93u)
+#define apiID_UXLISTREMOVE                        (94u)
+#define apiID_XEVENTGROUPCREATE                   (95u)
+#define apiID_XEVENTGROUPWAITBITS                 (96u)
+#define apiID_XEVENTGROUPCLEARBITS                (97u)
+#define apiID_XEVENTGROUPCLEARBITSFROMISR         (98u)
+#define apiID_XEVENTGROUPSETBITS                  (99u)
+#define apiID_XEVENTGROUPSETBITSFROMISR           (100u)
+#define apiID_XEVENTGROUPSYNC                     (101u)
+#define apiID_XEVENTGROUPGETBITSFROMISR           (102u)
+#define apiID_VEVENTGROUPDELETE                   (103u)
+#define apiID_UXEVENTGROUPGETNUMBER               (104u)
+#define apiID_XSTREAMBUFFERCREATE                 (105u)
+#define apiID_VSTREAMBUFFERDELETE                 (106u)
+#define apiID_XSTREAMBUFFERRESET                  (107u)
+#define apiID_XSTREAMBUFFERSEND                   (108u)
+#define apiID_XSTREAMBUFFERSENDFROMISR            (109u)
+#define apiID_XSTREAMBUFFERRECEIVE                (110u)
+#define apiID_XSTREAMBUFFERRECEIVEFROMISR         (111u)
+
+#define traceSTART()                                                            SEGGER_SYSVIEW_Conf()
+
+#define traceTASK_NOTIFY_TAKE(uxIndexToWait)                                    SEGGER_SYSVIEW_RecordU32x2(apiID_OFFSET + apiID_ULTASKNOTIFYTAKE, xClearCountOnExit, xTicksToWait)
+#define traceTASK_DELAY()                                                       SEGGER_SYSVIEW_RecordU32  (apiID_OFFSET + apiID_VTASKDELAY, xTicksToDelay)
+#define traceTASK_DELAY_UNTIL(xTimeToWake)                                      SEGGER_SYSVIEW_RecordVoid (apiID_OFFSET + apiID_VTASKDELAYUNTIL)
+#define traceTASK_NOTIFY_GIVE_FROM_ISR(uxIndexToNotify)                         SEGGER_SYSVIEW_RecordU32x2(apiID_OFFSET + apiID_VTASKNOTIFYGIVEFROMISR, SEGGER_SYSVIEW_ShrinkId((U32)pxTCB), (U32)pxHigherPriorityTaskWoken)
+
+#define traceTASK_PRIORITY_INHERIT( pxTCB, uxPriority )                         SEGGER_SYSVIEW_RecordU32  (apiID_OFFSET + apiID_VTASKPRIORITYINHERIT, (U32)pxMutexHolder)
+#define traceTASK_RESUME( pxTCB )                                               SEGGER_SYSVIEW_RecordU32  (apiID_OFFSET + apiID_VTASKRESUME, SEGGER_SYSVIEW_ShrinkId((U32)pxTCB))
+#define traceINCREASE_TICK_COUNT( xTicksToJump )                                SEGGER_SYSVIEW_RecordU32  (apiID_OFFSET + apiID_VTASKSTEPTICK, xTicksToJump)
+#define traceTASK_SUSPEND( pxTCB )                                              SEGGER_SYSVIEW_RecordU32  (apiID_OFFSET + apiID_VTASKSUSPEND, SEGGER_SYSVIEW_ShrinkId((U32)pxTCB))
+#define traceTASK_PRIORITY_DISINHERIT( pxTCB, uxBasePriority )                  SEGGER_SYSVIEW_RecordU32  (apiID_OFFSET + apiID_XTASKPRIORITYDISINHERIT, (U32)pxMutexHolder)
+#define traceTASK_RESUME_FROM_ISR( pxTCB )                                      SEGGER_SYSVIEW_RecordU32  (apiID_OFFSET + apiID_XTASKRESUMEFROMISR, SEGGER_SYSVIEW_ShrinkId((U32)pxTCB))
+#define traceTASK_NOTIFY(uxIndexToNotify)                                       SEGGER_SYSVIEW_RecordU32x4(apiID_OFFSET + apiID_XTASKGENERICNOTIFY, SEGGER_SYSVIEW_ShrinkId((U32)pxTCB), ulValue, eAction, (U32)pulPreviousNotificationValue)
+#define traceTASK_NOTIFY_FROM_ISR(uxIndexToWait)                                SEGGER_SYSVIEW_RecordU32x5(apiID_OFFSET + apiID_XTASKGENERICNOTIFYFROMISR, SEGGER_SYSVIEW_ShrinkId((U32)pxTCB), ulValue, eAction, (U32)pulPreviousNotificationValue, (U32)pxHigherPriorityTaskWoken)
+#define traceTASK_NOTIFY_WAIT(uxIndexToWait)                                    SEGGER_SYSVIEW_RecordU32x4(apiID_OFFSET + apiID_XTASKNOTIFYWAIT, ulBitsToClearOnEntry, ulBitsToClearOnExit, (U32)pulNotificationValue, xTicksToWait)
+
+#define traceQUEUE_CREATE( pxNewQueue )                                         SEGGER_SYSVIEW_RecordU32x3(apiID_OFFSET + apiID_XQUEUEGENERICCREATE, uxQueueLength, uxItemSize, ucQueueType)
+#define traceQUEUE_DELETE( pxQueue )                                            SEGGER_SYSVIEW_RecordU32  (apiID_OFFSET + apiID_VQUEUEDELETE, SEGGER_SYSVIEW_ShrinkId((U32)pxQueue))
+#define traceQUEUE_PEEK( pxQueue )                                              SEGGER_SYSVIEW_RecordU32x4(apiID_OFFSET + apiID_XQUEUEGENERICRECEIVE, SEGGER_SYSVIEW_ShrinkId((U32)pxQueue), SEGGER_SYSVIEW_ShrinkId((U32)pvBuffer), xTicksToWait, 1)
+#define traceQUEUE_PEEK_FROM_ISR( pxQueue )                                     SEGGER_SYSVIEW_RecordU32x2(apiID_OFFSET + apiID_XQUEUEPEEKFROMISR, SEGGER_SYSVIEW_ShrinkId((U32)pxQueue), SEGGER_SYSVIEW_ShrinkId((U32)pvBuffer))
+#define traceQUEUE_PEEK_FROM_ISR_FAILED( pxQueue )                              SEGGER_SYSVIEW_RecordU32x2(apiID_OFFSET + apiID_XQUEUEPEEKFROMISR, SEGGER_SYSVIEW_ShrinkId((U32)pxQueue), SEGGER_SYSVIEW_ShrinkId((U32)pvBuffer))
+#define traceQUEUE_RECEIVE( pxQueue )                                           SEGGER_SYSVIEW_RecordU32x4(apiID_OFFSET + apiID_XQUEUEGENERICRECEIVE, SEGGER_SYSVIEW_ShrinkId((U32)pxQueue), SEGGER_SYSVIEW_ShrinkId((U32)0), xTicksToWait, 1)
+#define traceQUEUE_RECEIVE_FAILED( pxQueue )                                    SEGGER_SYSVIEW_RecordU32x4(apiID_OFFSET + apiID_XQUEUEGENERICRECEIVE, SEGGER_SYSVIEW_ShrinkId((U32)pxQueue), SEGGER_SYSVIEW_ShrinkId((U32)0), xTicksToWait, 1)
+#define traceQUEUE_SEMAPHORE_RECEIVE( pxQueue )                                 SEGGER_SYSVIEW_RecordU32x4(apiID_OFFSET + apiID_XQUEUEGENERICRECEIVE, SEGGER_SYSVIEW_ShrinkId((U32)pxQueue), SEGGER_SYSVIEW_ShrinkId((U32)0), xTicksToWait, 0)
+#define traceQUEUE_RECEIVE_FROM_ISR( pxQueue )                                  SEGGER_SYSVIEW_RecordU32x3(apiID_OFFSET + apiID_XQUEUERECEIVEFROMISR, SEGGER_SYSVIEW_ShrinkId((U32)pxQueue), SEGGER_SYSVIEW_ShrinkId((U32)pvBuffer), (U32)pxHigherPriorityTaskWoken)
+#define traceQUEUE_RECEIVE_FROM_ISR_FAILED( pxQueue )                           SEGGER_SYSVIEW_RecordU32x3(apiID_OFFSET + apiID_XQUEUERECEIVEFROMISR, SEGGER_SYSVIEW_ShrinkId((U32)pxQueue), SEGGER_SYSVIEW_ShrinkId((U32)pvBuffer), (U32)pxHigherPriorityTaskWoken)
+#define traceQUEUE_REGISTRY_ADD( xQueue, pcQueueName )                          SEGGER_SYSVIEW_RecordU32x2(apiID_OFFSET + apiID_VQUEUEADDTOREGISTRY, SEGGER_SYSVIEW_ShrinkId((U32)xQueue), (U32)pcQueueName)
+#if ( configUSE_QUEUE_SETS != 1 )
+  #define traceQUEUE_SEND( pxQueue )                                            SEGGER_SYSVIEW_RecordU32x4(apiID_OFFSET + apiID_XQUEUEGENERICSEND, SEGGER_SYSVIEW_ShrinkId((U32)pxQueue), (U32)pvItemToQueue, xTicksToWait, xCopyPosition)
+#else
+  #define traceQUEUE_SEND( pxQueue )                                            SEGGER_SYSVIEW_RecordU32x4(apiID_OFFSET + apiID_XQUEUEGENERICSEND, SEGGER_SYSVIEW_ShrinkId((U32)pxQueue), 0u, 0u, xCopyPosition)
+#endif
+#define traceQUEUE_SEND_FAILED( pxQueue )                                       SEGGER_SYSVIEW_RecordU32x4(apiID_OFFSET + apiID_XQUEUEGENERICSEND, SEGGER_SYSVIEW_ShrinkId((U32)pxQueue), (U32)pvItemToQueue, xTicksToWait, xCopyPosition)
+#define traceQUEUE_SEND_FROM_ISR( pxQueue )                                     SEGGER_SYSVIEW_RecordU32x2(apiID_OFFSET + apiID_XQUEUEGENERICSENDFROMISR, SEGGER_SYSVIEW_ShrinkId((U32)pxQueue), (U32)pxHigherPriorityTaskWoken)
+#define traceQUEUE_SEND_FROM_ISR_FAILED( pxQueue )                              SEGGER_SYSVIEW_RecordU32x2(apiID_OFFSET + apiID_XQUEUEGENERICSENDFROMISR, SEGGER_SYSVIEW_ShrinkId((U32)pxQueue), (U32)pxHigherPriorityTaskWoken)
+#define traceSTREAM_BUFFER_CREATE( pxStreamBuffer, xIsMessageBuffer )           SEGGER_SYSVIEW_RecordU32x2(apiID_OFFSET + apiID_XSTREAMBUFFERCREATE, (U32)xIsMessageBuffer, (U32)pxStreamBuffer)
+#define traceSTREAM_BUFFER_CREATE_FAILED( xIsMessageBuffer )                    SEGGER_SYSVIEW_RecordU32x2(apiID_OFFSET + apiID_XSTREAMBUFFERCREATE, (U32)xIsMessageBuffer, 0u)
+#define traceSTREAM_BUFFER_DELETE( xStreamBuffer )                              SEGGER_SYSVIEW_RecordU32  (apiID_OFFSET + apiID_VSTREAMBUFFERDELETE, (U32)xStreamBuffer)
+#define traceSTREAM_BUFFER_RESET( xStreamBuffer )                               SEGGER_SYSVIEW_RecordU32  (apiID_OFFSET + apiID_XSTREAMBUFFERRESET, (U32)xStreamBuffer)
+#define traceSTREAM_BUFFER_SEND( xStreamBuffer, xBytesSent )                    SEGGER_SYSVIEW_RecordU32x2(apiID_OFFSET + apiID_XSTREAMBUFFERSEND, (U32)xStreamBuffer, (U32)xBytesSent)
+#define traceSTREAM_BUFFER_SEND_FAILED( xStreamBuffer )                         SEGGER_SYSVIEW_RecordU32x2(apiID_OFFSET + apiID_XSTREAMBUFFERSEND, (U32)xStreamBuffer, 0u)
+#define traceSTREAM_BUFFER_SEND_FROM_ISR( xStreamBuffer, xBytesSent )           SEGGER_SYSVIEW_RecordU32x2(apiID_OFFSET + apiID_XSTREAMBUFFERSENDFROMISR, (U32)xStreamBuffer, (U32)xBytesSent)
+#define traceSTREAM_BUFFER_RECEIVE( xStreamBuffer, xReceivedLength )            SEGGER_SYSVIEW_RecordU32x2(apiID_OFFSET + apiID_XSTREAMBUFFERRECEIVE, (U32)xStreamBuffer, (U32)xReceivedLength)
+#define traceSTREAM_BUFFER_RECEIVE_FAILED( xStreamBuffer )                      SEGGER_SYSVIEW_RecordU32x2(apiID_OFFSET + apiID_XSTREAMBUFFERRECEIVE, (U32)xStreamBuffer, 0u)
+#define traceSTREAM_BUFFER_RECEIVE_FROM_ISR( xStreamBuffer, xReceivedLength )   SEGGER_SYSVIEW_RecordU32x2(apiID_OFFSET + apiID_XSTREAMBUFFERRECEIVEFROMISR, (U32)xStreamBuffer, (U32)xReceivedLength)
+
+
+#define traceTASK_DELETE( pxTCB )                   {                                                                                                   \
+                                                      SEGGER_SYSVIEW_RecordU32(apiID_OFFSET + apiID_VTASKDELETE, SEGGER_SYSVIEW_ShrinkId((U32)pxTCB));  \
+                                                      SYSVIEW_DeleteTask((U32)pxTCB);                                                                   \
+                                                    }
+
+
+#if( portSTACK_GROWTH < 0 )
+#define traceTASK_CREATE(pxNewTCB)                  if (pxNewTCB != NULL) {                                             \
+                                                      SEGGER_SYSVIEW_OnTaskCreate((U32)pxNewTCB);                       \
+                                                      SYSVIEW_AddTask((U32)pxNewTCB,                                    \
+                                                                      &(pxNewTCB->pcTaskName[0]),                       \
+                                                                      pxNewTCB->uxPriority,                             \
+                                                                      (U32)pxNewTCB->pxStack,                           \
+                                                                      ((U32)pxNewTCB->pxTopOfStack - (U32)pxNewTCB->pxStack) \
+                                                                      );                                                \
+                                                    }
+#else
+#define traceTASK_CREATE(pxNewTCB)                  if (pxNewTCB != NULL) {                                             \
+                                                      SEGGER_SYSVIEW_OnTaskCreate((U32)pxNewTCB);                       \
+                                                      SYSVIEW_AddTask((U32)pxNewTCB,                                    \
+                                                                      &(pxNewTCB->pcTaskName[0]),                       \
+                                                                      pxNewTCB->uxPriority,                             \
+                                                                      (U32)pxNewTCB->pxStack,                           \
+                                                                      (U32)(pxNewTCB->pxStack-pxNewTCB->pxTopOfStack)   \
+                                                                      );                                                \
+                                                    }
+#endif
+#define traceTASK_PRIORITY_SET(pxTask, uxNewPriority) {                                                                 \
+                                                        SEGGER_SYSVIEW_RecordU32x2(apiID_OFFSET+apiID_VTASKPRIORITYSET, \
+                                                                                   SEGGER_SYSVIEW_ShrinkId((U32)pxTCB), \
+                                                                                   uxNewPriority                        \
+                                                                                  );                                    \
+                                                        SYSVIEW_UpdateTask((U32)pxTask,                                 \
+                                                                           &(pxTask->pcTaskName[0]),                    \
+                                                                           uxNewPriority,                               \
+                                                                           (U32)pxTask->pxStack,                        \
+                                                                           0                                            \
+                                                                          );                                            \
+                                                      }
+//
+// Define INCLUDE_xTaskGetIdleTaskHandle as 1 in FreeRTOSConfig.h to allow identification of Idle state.
+//
+#if ( INCLUDE_xTaskGetIdleTaskHandle == 1 )
+  #define traceTASK_SWITCHED_IN()                   if(prvGetTCBFromHandle(NULL) == xIdleTaskHandle) {                  \
+                                                      SEGGER_SYSVIEW_OnIdle();                                          \
+                                                    } else {                                                            \
+                                                      SEGGER_SYSVIEW_OnTaskStartExec((U32)pxCurrentTCB);                \
+                                                    }
+#else
+  #define traceTASK_SWITCHED_IN()                   {                                                                   \
+                                                      if (memcmp(pxCurrentTCB->pcTaskName, "IDLE", 5) != 0) {           \
+                                                        SEGGER_SYSVIEW_OnTaskStartExec((U32)pxCurrentTCB);              \
+                                                      } else {                                                          \
+                                                        SEGGER_SYSVIEW_OnIdle();                                        \
+                                                      }                                                                 \
+                                                    }
+#endif
+
+#define traceMOVED_TASK_TO_READY_STATE(pxTCB)       SEGGER_SYSVIEW_OnTaskStartReady((U32)pxTCB)
+#define traceREADDED_TASK_TO_READY_STATE(pxTCB)
+
+#define traceMOVED_TASK_TO_DELAYED_LIST()           SEGGER_SYSVIEW_OnTaskStopReady((U32)pxCurrentTCB,  (1u << 2))
+#define traceMOVED_TASK_TO_OVERFLOW_DELAYED_LIST()  SEGGER_SYSVIEW_OnTaskStopReady((U32)pxCurrentTCB,  (1u << 2))
+#define traceMOVED_TASK_TO_SUSPENDED_LIST(pxTCB)    SEGGER_SYSVIEW_OnTaskStopReady((U32)pxTCB,         ((3u << 3) | 3))
+
+
+#define traceISR_EXIT_TO_SCHEDULER()                SEGGER_SYSVIEW_RecordExitISRToScheduler()
+#define traceISR_EXIT()                             SEGGER_SYSVIEW_RecordExitISR()
+#define traceISR_ENTER()                            SEGGER_SYSVIEW_RecordEnterISR()
+
+/*********************************************************************
+*
+*       API functions
+*
+**********************************************************************
+*/
+#ifdef __cplusplus
+extern "C" {
+#endif
+void SYSVIEW_AddTask      (U32 xHandle, const char* pcTaskName, unsigned uxCurrentPriority, U32  pxStack, unsigned uStackHighWaterMark);
+void SYSVIEW_UpdateTask   (U32 xHandle, const char* pcTaskName, unsigned uxCurrentPriority, U32 pxStack, unsigned uStackHighWaterMark);
+void SYSVIEW_DeleteTask   (U32 xHandle);
+void SYSVIEW_SendTaskInfo (U32 TaskID, const char* sName, unsigned Prio, U32 StackBase, unsigned StackSize);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
+
+/*************************** End of file ****************************/

+ 99 - 0
code/debug/SEGGER/SEGGER_SYSVIEW_Int.h

@@ -0,0 +1,99 @@
+/*********************************************************************
+*                    SEGGER Microcontroller GmbH                     *
+*                        The Embedded Experts                        *
+**********************************************************************
+*                                                                    *
+*            (c) 1995 - 2021 SEGGER Microcontroller GmbH             *
+*                                                                    *
+*       www.segger.com     Support: support@segger.com               *
+*                                                                    *
+**********************************************************************
+*                                                                    *
+*       SEGGER SystemView * Real-time application analysis           *
+*                                                                    *
+**********************************************************************
+*                                                                    *
+* All rights reserved.                                               *
+*                                                                    *
+* SEGGER strongly recommends to not make any changes                 *
+* to or modify the source code of this software in order to stay     *
+* compatible with the SystemView and RTT protocol, and J-Link.       *
+*                                                                    *
+* Redistribution and use in source and binary forms, with or         *
+* without modification, are permitted provided that the following    *
+* condition is met:                                                  *
+*                                                                    *
+* o Redistributions of source code must retain the above copyright   *
+*   notice, this condition and the following disclaimer.             *
+*                                                                    *
+* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND             *
+* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,        *
+* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF           *
+* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE           *
+* DISCLAIMED. IN NO EVENT SHALL SEGGER Microcontroller BE LIABLE FOR *
+* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR           *
+* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT  *
+* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;    *
+* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF      *
+* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT          *
+* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE  *
+* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH   *
+* DAMAGE.                                                            *
+*                                                                    *
+**********************************************************************
+*                                                                    *
+*       SystemView version: 3.32                                    *
+*                                                                    *
+**********************************************************************
+-------------------------- END-OF-HEADER -----------------------------
+File    : SEGGER_SYSVIEW_Int.h
+Purpose : SEGGER SystemView internal header.
+Revision: $Rev: 21281 $
+*/
+
+#ifndef SEGGER_SYSVIEW_INT_H
+#define SEGGER_SYSVIEW_INT_H
+
+/*********************************************************************
+*
+*       #include Section
+*
+**********************************************************************
+*/
+
+#include "SEGGER_SYSVIEW.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+
+/*********************************************************************
+*
+*       Private data types
+*
+**********************************************************************
+*/
+//
+// Commands that Host can send to target
+//
+typedef enum {
+  SEGGER_SYSVIEW_COMMAND_ID_START = 1,
+  SEGGER_SYSVIEW_COMMAND_ID_STOP,
+  SEGGER_SYSVIEW_COMMAND_ID_GET_SYSTIME,
+  SEGGER_SYSVIEW_COMMAND_ID_GET_TASKLIST,
+  SEGGER_SYSVIEW_COMMAND_ID_GET_SYSDESC,
+  SEGGER_SYSVIEW_COMMAND_ID_GET_NUMMODULES,
+  SEGGER_SYSVIEW_COMMAND_ID_GET_MODULEDESC,
+  SEGGER_SYSVIEW_COMMAND_ID_HEARTBEAT = 127,
+  // Extended commands: Commands >= 128 have a second parameter
+  SEGGER_SYSVIEW_COMMAND_ID_GET_MODULE = 128
+} SEGGER_SYSVIEW_COMMAND_ID;
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
+
+/*************************** End of file ****************************/

+ 8 - 0
code/debug/cm_backtrace/Languages/README.md

@@ -0,0 +1,8 @@
+# CmBacktrace: ARM Cortex-M 系列 MCU 错误追踪库
+
+## 多语言支持
+
+| Language             | Location (or type)         | Language tag |
+|----------------------|----------------------------|--------------|
+| English              | United States              | en-US        |
+| Chinese (Simplified) | People's Republic of China | zh-CN        |

+ 71 - 0
code/debug/cm_backtrace/Languages/en-US/cmb_en_US.h

@@ -0,0 +1,71 @@
+/*
+ * This file is part of the CmBacktrace Library.
+ *
+ * Copyright (c) 2020, Armink, <armink.ztl@gmail.com>
+ *                     Chenxuan, <chenxuan.zhao@icloud.com>
+ *
+ * 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.
+ *
+ * NOTE: DO NOT include this file on the header file.
+ * Encoding: UTF-8
+ * Created on: 2020-09-06
+ */
+
+[PRINT_MAIN_STACK_CFG_ERROR]  = "ERROR: Unable to get the main stack information, please check the configuration of the main stack",
+[PRINT_FIRMWARE_INFO]         = "Firmware name: %s, hardware version: %s, software version: %s",
+[PRINT_ASSERT_ON_THREAD]      = "Assert on thread %s",
+[PRINT_ASSERT_ON_HANDLER]     = "Assert on interrupt or bare metal(no OS) environment",
+[PRINT_THREAD_STACK_INFO]     = "===== Thread stack information =====",
+[PRINT_MAIN_STACK_INFO]       = "====== Main stack information ======",
+[PRINT_THREAD_STACK_OVERFLOW] = "Error: Thread stack(%08x) was overflow",
+[PRINT_MAIN_STACK_OVERFLOW]   = "Error: Main stack(%08x) was overflow",
+[PRINT_CALL_STACK_INFO]       = "Show more call stack info by run: addr2line -e %s%s -a -f %s",
+[PRINT_CALL_STACK_ERR]        = "Dump call stack has an error",
+[PRINT_FAULT_ON_THREAD]       = "Fault on thread %s",
+[PRINT_FAULT_ON_HANDLER]      = "Fault on interrupt or bare metal(no OS) environment",
+[PRINT_REGS_TITLE]            = "=================== Registers information ====================",
+[PRINT_HFSR_VECTBL]           = "Hard fault is caused by failed vector fetch",
+[PRINT_MFSR_IACCVIOL]         = "Memory management fault is caused by instruction access violation",
+[PRINT_MFSR_DACCVIOL]         = "Memory management fault is caused by data access violation",
+[PRINT_MFSR_MUNSTKERR]        = "Memory management fault is caused by unstacking error",
+[PRINT_MFSR_MSTKERR]          = "Memory management fault is caused by stacking error",
+[PRINT_MFSR_MLSPERR]          = "Memory management fault is caused by floating-point lazy state preservation",
+[PRINT_BFSR_IBUSERR]          = "Bus fault is caused by instruction access violation",
+[PRINT_BFSR_PRECISERR]        = "Bus fault is caused by precise data access violation",
+[PRINT_BFSR_IMPREISERR]       = "Bus fault is caused by imprecise data access violation",
+[PRINT_BFSR_UNSTKERR]         = "Bus fault is caused by unstacking error",
+[PRINT_BFSR_STKERR]           = "Bus fault is caused by stacking error",
+[PRINT_BFSR_LSPERR]           = "Bus fault is caused by floating-point lazy state preservation",
+[PRINT_UFSR_UNDEFINSTR]       = "Usage fault is caused by attempts to execute an undefined instruction",
+[PRINT_UFSR_INVSTATE]         = "Usage fault is caused by attempts to switch to an invalid state (e.g., ARM)",
+[PRINT_UFSR_INVPC]            = "Usage fault is caused by attempts to do an exception with a bad value in the EXC_RETURN number",
+[PRINT_UFSR_NOCP]             = "Usage fault is caused by attempts to execute a coprocessor instruction",
+#if (CMB_CPU_PLATFORM_TYPE == CMB_CPU_ARM_CORTEX_M33)
+    [PRINT_UFSR_STKOF]        = "Usage fault is caused by indicates that a stack overflow (hardware check) has taken place",
+#endif
+[PRINT_UFSR_UNALIGNED]        = "Usage fault is caused by indicates that an unaligned access fault has taken place",
+[PRINT_UFSR_DIVBYZERO0]       = "Usage fault is caused by Indicates a divide by zero has taken place (can be set only if DIV_0_TRP is set)",
+[PRINT_DFSR_HALTED]           = "Debug fault is caused by halt requested in NVIC",
+[PRINT_DFSR_BKPT]             = "Debug fault is caused by BKPT instruction executed",
+[PRINT_DFSR_DWTTRAP]          = "Debug fault is caused by DWT match occurred",
+[PRINT_DFSR_VCATCH]           = "Debug fault is caused by Vector fetch occurred",
+[PRINT_DFSR_EXTERNAL]         = "Debug fault is caused by EDBGRQ signal asserted",
+[PRINT_MMAR]                  = "The memory management fault occurred address is %08x",
+[PRINT_BFAR]                  = "The bus fault occurred address is %08x",

+ 71 - 0
code/debug/cm_backtrace/Languages/zh-CN/cmb_zh_CN.h

@@ -0,0 +1,71 @@
+/*
+ * This file is part of the CmBacktrace Library.
+ *
+ * Copyright (c) 2020, Armink, <armink.ztl@gmail.com>
+ *                     Chenxuan, <chenxuan.zhao@icloud.com>
+ *
+ * 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.
+ *
+ * NOTE: DO NOT include this file on the header file.
+ * Encoding: GB18030
+ * Created on: 2020-09-06
+ */
+
+[PRINT_MAIN_STACK_CFG_ERROR]  = "错误:无法获取主栈信息,请检查主栈的相关配置",
+[PRINT_FIRMWARE_INFO]         = "固件名称:%s,硬件版本号:%s,软件版本号:%s",
+[PRINT_ASSERT_ON_THREAD]      = "在线程(%s)中发生断言",
+[PRINT_ASSERT_ON_HANDLER]     = "在中断或裸机环境下发生断言",
+[PRINT_THREAD_STACK_INFO]     = "=========== 线程堆栈信息 ===========",
+[PRINT_MAIN_STACK_INFO]       = "============ 主堆栈信息 ============",
+[PRINT_THREAD_STACK_OVERFLOW] = "错误:线程栈(%08x)发生溢出",
+[PRINT_MAIN_STACK_OVERFLOW]   = "错误:主栈(%08x)发生溢出",
+[PRINT_CALL_STACK_INFO]       = "查看更多函数调用栈信息,请运行:addr2line -e %s%s -a -f %s",
+[PRINT_CALL_STACK_ERR]        = "获取函数调用栈失败",
+[PRINT_FAULT_ON_THREAD]       =  "在线程(%s)中发生错误异常",
+[PRINT_FAULT_ON_HANDLER]      = "在中断或裸机环境下发生错误异常",
+[PRINT_REGS_TITLE]            = "========================= 寄存器信息 =========================",
+[PRINT_HFSR_VECTBL]           = "发生硬错误,原因:取中断向量时出错",
+[PRINT_MFSR_IACCVIOL]         = "发生存储器管理错误,原因:企图从不允许访问的区域取指令",
+[PRINT_MFSR_DACCVIOL]         = "发生存储器管理错误,原因:企图从不允许访问的区域读、写数据",
+[PRINT_MFSR_MUNSTKERR]        = "发生存储器管理错误,原因:出栈时企图访问不被允许的区域",
+[PRINT_MFSR_MSTKERR]          = "发生存储器管理错误,原因:入栈时企图访问不被允许的区域",
+[PRINT_MFSR_MLSPERR]          = "发生存储器管理错误,原因:惰性保存浮点状态时发生错误",
+[PRINT_BFSR_IBUSERR]          = "发生总线错误,原因:指令总线错误",
+[PRINT_BFSR_PRECISERR]        = "发生总线错误,原因:精确的数据总线错误",
+[PRINT_BFSR_IMPREISERR]       = "发生总线错误,原因:不精确的数据总线错误",
+[PRINT_BFSR_UNSTKERR]         = "发生总线错误,原因:出栈时发生错误",
+[PRINT_BFSR_STKERR]           = "发生总线错误,原因:入栈时发生错误",
+[PRINT_BFSR_LSPERR]           = "发生总线错误,原因:惰性保存浮点状态时发生错误",
+[PRINT_UFSR_UNDEFINSTR]       = "发生用法错误,原因:企图执行未定义指令",
+[PRINT_UFSR_INVSTATE]         = "发生用法错误,原因:试图切换到 ARM 状态",
+[PRINT_UFSR_INVPC]            = "发生用法错误,原因:无效的异常返回码",
+[PRINT_UFSR_NOCP]             = "发生用法错误,原因:企图执行协处理器指令",
+#if (CMB_CPU_PLATFORM_TYPE == CMB_CPU_ARM_CORTEX_M33)
+    [PRINT_UFSR_STKOF]        = "发生用法错误,原因:硬件检测到栈溢出",
+#endif
+[PRINT_UFSR_UNALIGNED]        = "发生用法错误,原因:企图执行非对齐访问",
+[PRINT_UFSR_DIVBYZERO0]       = "发生用法错误,原因:企图执行除 0 操作",
+[PRINT_DFSR_HALTED]           = "发生调试错误,原因:NVIC 停机请求",
+[PRINT_DFSR_BKPT]             = "发生调试错误,原因:执行 BKPT 指令",
+[PRINT_DFSR_DWTTRAP]          = "发生调试错误,原因:数据监测点匹配",
+[PRINT_DFSR_VCATCH]           = "发生调试错误,原因:发生向量捕获",
+[PRINT_DFSR_EXTERNAL]         = "发生调试错误,原因:外部调试请求",
+[PRINT_MMAR]                  = "发生存储器管理错误的地址:%08x",
+[PRINT_BFAR]                  = "发生总线错误的地址:%08x",

+ 71 - 0
code/debug/cm_backtrace/Languages/zh-CN/cmb_zh_CN_UTF8.h

@@ -0,0 +1,71 @@
+/*
+ * This file is part of the CmBacktrace Library.
+ *
+ * Copyright (c) 2020, Armink, <armink.ztl@gmail.com>
+ *                     Chenxuan, <chenxuan.zhao@icloud.com>
+ *
+ * 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.
+ *
+ * NOTE: DO NOT include this file on the header file.
+ * Encoding: UTF-8
+ * Created on: 2020-09-06
+ */
+
+[PRINT_MAIN_STACK_CFG_ERROR]  = "错误:无法获取主栈信息,请检查主栈的相关配置",
+[PRINT_FIRMWARE_INFO]         = "固件名称:%s,硬件版本号:%s,软件版本号:%s",
+[PRINT_ASSERT_ON_THREAD]      = "在线程(%s)中发生断言",
+[PRINT_ASSERT_ON_HANDLER]     = "在中断或裸机环境下发生断言",
+[PRINT_THREAD_STACK_INFO]     = "=========== 线程堆栈信息 ===========",
+[PRINT_MAIN_STACK_INFO]       = "============ 主堆栈信息 ============",
+[PRINT_THREAD_STACK_OVERFLOW] = "错误:线程栈(%08x)发生溢出",
+[PRINT_MAIN_STACK_OVERFLOW]   = "错误:主栈(%08x)发生溢出",
+[PRINT_CALL_STACK_INFO]       = "查看更多函数调用栈信息,请运行:addr2line -e %s%s -a -f %s",
+[PRINT_CALL_STACK_ERR]        = "获取函数调用栈失败",
+[PRINT_FAULT_ON_THREAD]       =  "在线程(%s)中发生错误异常",
+[PRINT_FAULT_ON_HANDLER]      = "在中断或裸机环境下发生错误异常",
+[PRINT_REGS_TITLE]            = "========================= 寄存器信息 =========================",
+[PRINT_HFSR_VECTBL]           = "发生硬错误,原因:取中断向量时出错",
+[PRINT_MFSR_IACCVIOL]         = "发生存储器管理错误,原因:企图从不允许访问的区域取指令",
+[PRINT_MFSR_DACCVIOL]         = "发生存储器管理错误,原因:企图从不允许访问的区域读、写数据",
+[PRINT_MFSR_MUNSTKERR]        = "发生存储器管理错误,原因:出栈时企图访问不被允许的区域",
+[PRINT_MFSR_MSTKERR]          = "发生存储器管理错误,原因:入栈时企图访问不被允许的区域",
+[PRINT_MFSR_MLSPERR]          = "发生存储器管理错误,原因:惰性保存浮点状态时发生错误",
+[PRINT_BFSR_IBUSERR]          = "发生总线错误,原因:指令总线错误",
+[PRINT_BFSR_PRECISERR]        = "发生总线错误,原因:精确的数据总线错误",
+[PRINT_BFSR_IMPREISERR]       = "发生总线错误,原因:不精确的数据总线错误",
+[PRINT_BFSR_UNSTKERR]         = "发生总线错误,原因:出栈时发生错误",
+[PRINT_BFSR_STKERR]           = "发生总线错误,原因:入栈时发生错误",
+[PRINT_BFSR_LSPERR]           = "发生总线错误,原因:惰性保存浮点状态时发生错误",
+[PRINT_UFSR_UNDEFINSTR]       = "发生用法错误,原因:企图执行未定义指令",
+[PRINT_UFSR_INVSTATE]         = "发生用法错误,原因:试图切换到 ARM 状态",
+[PRINT_UFSR_INVPC]            = "发生用法错误,原因:无效的异常返回码",
+[PRINT_UFSR_NOCP]             = "发生用法错误,原因:企图执行协处理器指令",
+#if (CMB_CPU_PLATFORM_TYPE == CMB_CPU_ARM_CORTEX_M33)
+    [PRINT_UFSR_STKOF]        = "发生用法错误,原因:硬件检测到栈溢出",
+#endif
+[PRINT_UFSR_UNALIGNED]        = "发生用法错误,原因:企图执行非对齐访问",
+[PRINT_UFSR_DIVBYZERO0]       = "发生用法错误,原因:企图执行除 0 操作",
+[PRINT_DFSR_HALTED]           = "发生调试错误,原因:NVIC 停机请求",
+[PRINT_DFSR_BKPT]             = "发生调试错误,原因:执行 BKPT 指令",
+[PRINT_DFSR_DWTTRAP]          = "发生调试错误,原因:数据监测点匹配",
+[PRINT_DFSR_VCATCH]           = "发生调试错误,原因:发生向量捕获",
+[PRINT_DFSR_EXTERNAL]         = "发生调试错误,原因:外部调试请求",
+[PRINT_MMAR]                  = "发生存储器管理错误的地址:%08x",
+[PRINT_BFAR]                  = "发生总线错误的地址:%08x",

+ 666 - 0
code/debug/cm_backtrace/cm_backtrace.c

@@ -0,0 +1,666 @@
+/*
+ * This file is part of the CmBacktrace Library.
+ *
+ * Copyright (c) 2016-2019, Armink, <armink.ztl@gmail.com>
+ *
+ * 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.
+ *
+ * Function: Initialize function and other general function.
+ * Created on: 2016-12-15
+ */
+
+#include <cm_backtrace.h>
+#include <stdbool.h>
+#include <string.h>
+#include <stdio.h>
+
+#if __STDC_VERSION__ < 199901L
+    #error "must be C99 or higher. try to add '-std=c99' to compile parameters"
+#endif
+
+#if defined(__ARMCC_VERSION)
+    #define SECTION_START(_name_)                _name_##$$Base
+    #define SECTION_END(_name_)                  _name_##$$Limit
+    #define IMAGE_SECTION_START(_name_)          Image$$##_name_##$$Base
+    #define IMAGE_SECTION_END(_name_)            Image$$##_name_##$$Limit
+    #define CSTACK_BLOCK_START(_name_)           SECTION_START(_name_)
+    #define CSTACK_BLOCK_END(_name_)             SECTION_END(_name_)
+    #define CODE_SECTION_START(_name_)           IMAGE_SECTION_START(_name_)
+    #define CODE_SECTION_END(_name_)             IMAGE_SECTION_END(_name_)
+
+    extern const int CSTACK_BLOCK_START(CMB_CSTACK_BLOCK_NAME);
+    extern const int CSTACK_BLOCK_END(CMB_CSTACK_BLOCK_NAME);
+    extern const int CODE_SECTION_START(CMB_CODE_SECTION_NAME);
+    extern const int CODE_SECTION_END(CMB_CODE_SECTION_NAME);
+#elif defined(__ICCARM__)
+    #pragma section=CMB_CSTACK_BLOCK_NAME
+    #pragma section=CMB_CODE_SECTION_NAME
+#elif defined(__GNUC__)
+    extern const int CMB_CSTACK_BLOCK_START;
+    extern const int CMB_CSTACK_BLOCK_END;
+    extern const int CMB_CODE_SECTION_START;
+    extern const int CMB_CODE_SECTION_END;
+#else
+    #error "not supported compiler"
+#endif
+
+enum {
+    PRINT_MAIN_STACK_CFG_ERROR,
+    PRINT_FIRMWARE_INFO,
+    PRINT_ASSERT_ON_THREAD,
+    PRINT_ASSERT_ON_HANDLER,
+    PRINT_THREAD_STACK_INFO,
+    PRINT_MAIN_STACK_INFO,
+    PRINT_THREAD_STACK_OVERFLOW,
+    PRINT_MAIN_STACK_OVERFLOW,
+    PRINT_CALL_STACK_INFO,
+    PRINT_CALL_STACK_ERR,
+    PRINT_FAULT_ON_THREAD,
+    PRINT_FAULT_ON_HANDLER,
+    PRINT_REGS_TITLE,
+    PRINT_HFSR_VECTBL,
+    PRINT_MFSR_IACCVIOL,
+    PRINT_MFSR_DACCVIOL,
+    PRINT_MFSR_MUNSTKERR,
+    PRINT_MFSR_MSTKERR,
+    PRINT_MFSR_MLSPERR,
+    PRINT_BFSR_IBUSERR,
+    PRINT_BFSR_PRECISERR,
+    PRINT_BFSR_IMPREISERR,
+    PRINT_BFSR_UNSTKERR,
+    PRINT_BFSR_STKERR,
+    PRINT_BFSR_LSPERR,
+    PRINT_UFSR_UNDEFINSTR,
+    PRINT_UFSR_INVSTATE,
+    PRINT_UFSR_INVPC,
+    PRINT_UFSR_NOCP,
+#if (CMB_CPU_PLATFORM_TYPE == CMB_CPU_ARM_CORTEX_M33)
+    PRINT_UFSR_STKOF,
+#endif
+    PRINT_UFSR_UNALIGNED,
+    PRINT_UFSR_DIVBYZERO0,
+    PRINT_DFSR_HALTED,
+    PRINT_DFSR_BKPT,
+    PRINT_DFSR_DWTTRAP,
+    PRINT_DFSR_VCATCH,
+    PRINT_DFSR_EXTERNAL,
+    PRINT_MMAR,
+    PRINT_BFAR,
+};
+
+static const char * const print_info[] = {
+#if (CMB_PRINT_LANGUAGE == CMB_PRINT_LANGUAGE_ENGLISH)
+    #include "Languages/en-US/cmb_en_US.h"
+#elif (CMB_PRINT_LANGUAGE == CMB_PRINT_LANGUAGE_CHINESE)
+    #include "Languages/zh-CN/cmb_zh_CN.h"
+#elif (CMB_PRINT_LANGUAGE == CMB_PRINT_LANGUAGE_CHINESE_UTF8)
+    #include "Languages/zh-CN/cmb_zh_CN_UTF8.h"
+#else
+    #error "CMB_PRINT_LANGUAGE defined error in 'cmb_cfg.h'"
+#endif
+};
+
+static char fw_name[CMB_NAME_MAX] = {0};
+static char hw_ver[CMB_NAME_MAX] = {0};
+static char sw_ver[CMB_NAME_MAX] = {0};
+static uint32_t main_stack_start_addr = 0;
+static size_t main_stack_size = 0;
+static uint32_t code_start_addr = 0;
+static size_t code_size = 0;
+static bool init_ok = false;
+static char call_stack_info[CMB_CALL_STACK_MAX_DEPTH * (8 + 1)] = { 0 };
+static bool on_fault = false;
+static bool stack_is_overflow = false;
+static struct cmb_hard_fault_regs regs;
+
+#if (CMB_CPU_PLATFORM_TYPE == CMB_CPU_ARM_CORTEX_M4) || (CMB_CPU_PLATFORM_TYPE == CMB_CPU_ARM_CORTEX_M7) || \
+    (CMB_CPU_PLATFORM_TYPE == CMB_CPU_ARM_CORTEX_M33)
+static bool statck_has_fpu_regs = false;
+#endif
+
+static bool on_thread_before_fault = false;
+
+/**
+ * library initialize
+ */
+void cm_backtrace_init(const char *firmware_name, const char *hardware_ver, const char *software_ver) {
+    strncpy(fw_name, firmware_name, CMB_NAME_MAX);
+    strncpy(hw_ver, hardware_ver, CMB_NAME_MAX);
+    strncpy(sw_ver, software_ver, CMB_NAME_MAX);
+
+#if defined(__ARMCC_VERSION)
+    main_stack_start_addr = (uint32_t)&CSTACK_BLOCK_START(CMB_CSTACK_BLOCK_NAME);
+    main_stack_size = (uint32_t)&CSTACK_BLOCK_END(CMB_CSTACK_BLOCK_NAME) - main_stack_start_addr;
+    code_start_addr = (uint32_t)&CODE_SECTION_START(CMB_CODE_SECTION_NAME);
+    code_size = (uint32_t)&CODE_SECTION_END(CMB_CODE_SECTION_NAME) - code_start_addr;
+#elif defined(__ICCARM__)
+    main_stack_start_addr = (uint32_t)__section_begin(CMB_CSTACK_BLOCK_NAME);
+    main_stack_size = (uint32_t)__section_end(CMB_CSTACK_BLOCK_NAME) - main_stack_start_addr;
+    code_start_addr = (uint32_t)__section_begin(CMB_CODE_SECTION_NAME);
+    code_size = (uint32_t)__section_end(CMB_CODE_SECTION_NAME) - code_start_addr;
+#elif defined(__GNUC__)
+    main_stack_start_addr = (uint32_t)(&CMB_CSTACK_BLOCK_START);
+    main_stack_size = (uint32_t)(&CMB_CSTACK_BLOCK_END) - main_stack_start_addr;
+    code_start_addr = (uint32_t)(&CMB_CODE_SECTION_START);
+    code_size = (uint32_t)(&CMB_CODE_SECTION_END) - code_start_addr;
+#else
+    #error "not supported compiler"
+#endif
+
+    if (main_stack_size == 0) {
+        cmb_println(print_info[PRINT_MAIN_STACK_CFG_ERROR]);
+        return;
+    }
+
+    init_ok = true;
+}
+/**
+ * print firmware information, such as: firmware name, hardware version, software version
+ */
+void cm_backtrace_firmware_info(void) {
+    cmb_println(print_info[PRINT_FIRMWARE_INFO], fw_name, hw_ver, sw_ver);
+}
+
+#ifdef CMB_USING_OS_PLATFORM
+/**
+ * Get current thread stack information
+ *
+ * @param sp stack current pointer
+ * @param start_addr stack start address
+ * @param size stack size
+ */
+static void get_cur_thread_stack_info(uint32_t sp, uint32_t *start_addr, size_t *size) {
+    CMB_ASSERT(start_addr);
+    CMB_ASSERT(size);
+
+#if (CMB_OS_PLATFORM_TYPE == CMB_OS_PLATFORM_RTT)
+    *start_addr = (uint32_t) rt_thread_self()->stack_addr;
+    *size = rt_thread_self()->stack_size;
+#elif (CMB_OS_PLATFORM_TYPE == CMB_OS_PLATFORM_UCOSII)
+    extern OS_TCB *OSTCBCur;
+
+    *start_addr = (uint32_t) OSTCBCur->OSTCBStkBottom;
+    *size = OSTCBCur->OSTCBStkSize * sizeof(OS_STK);
+#elif (CMB_OS_PLATFORM_TYPE == CMB_OS_PLATFORM_UCOSIII)
+    extern OS_TCB *OSTCBCurPtr; 
+    
+    *start_addr = (uint32_t) OSTCBCurPtr->StkBasePtr;
+    *size = OSTCBCurPtr->StkSize * sizeof(CPU_STK_SIZE);
+#elif (CMB_OS_PLATFORM_TYPE == CMB_OS_PLATFORM_FREERTOS)   
+    *start_addr = (uint32_t)vTaskStackAddr();
+    *size = vTaskStackSize() * sizeof( StackType_t );
+#elif (CMB_OS_PLATFORM_TYPE == CMB_OS_PLATFORM_RTX5)
+    osRtxThread_t *thread = osRtxInfo.thread.run.curr;
+    *start_addr = (uint32_t)thread->stack_mem;
+    *size = thread->stack_size;
+#endif
+}
+
+/**
+ * Get current thread name
+ */
+static const char *get_cur_thread_name(void) {
+#if (CMB_OS_PLATFORM_TYPE == CMB_OS_PLATFORM_RTT)
+    return rt_thread_self()->name;
+#elif (CMB_OS_PLATFORM_TYPE == CMB_OS_PLATFORM_UCOSII)
+    extern OS_TCB *OSTCBCur;
+
+#if OS_TASK_NAME_SIZE > 0 || OS_TASK_NAME_EN > 0
+        return (const char *)OSTCBCur->OSTCBTaskName;
+#else
+        return NULL;
+#endif /* OS_TASK_NAME_SIZE > 0 || OS_TASK_NAME_EN > 0 */
+
+#elif (CMB_OS_PLATFORM_TYPE == CMB_OS_PLATFORM_UCOSIII)
+    extern OS_TCB *OSTCBCurPtr; 
+    
+    return (const char *)OSTCBCurPtr->NamePtr;
+#elif (CMB_OS_PLATFORM_TYPE == CMB_OS_PLATFORM_FREERTOS)
+    return vTaskName();
+#elif (CMB_OS_PLATFORM_TYPE == CMB_OS_PLATFORM_RTX5)
+    osThreadId_t id = osThreadGetId();
+    return osThreadGetName(id);
+#endif
+}
+
+#endif /* CMB_USING_OS_PLATFORM */
+
+#ifdef CMB_USING_DUMP_STACK_INFO
+/**
+ * dump current stack information
+ */
+static void dump_stack(uint32_t stack_start_addr, size_t stack_size, uint32_t *stack_pointer) {
+    if (stack_is_overflow) {
+        if (on_thread_before_fault) {
+            cmb_println(print_info[PRINT_THREAD_STACK_OVERFLOW], stack_pointer);
+        } else {
+            cmb_println(print_info[PRINT_MAIN_STACK_OVERFLOW], stack_pointer);
+        }
+        if ((uint32_t) stack_pointer < stack_start_addr) {
+            stack_pointer = (uint32_t *) stack_start_addr;
+        } else if ((uint32_t) stack_pointer > stack_start_addr + stack_size) {
+            stack_pointer = (uint32_t *) (stack_start_addr + stack_size);
+        }
+    }
+    cmb_println(print_info[PRINT_THREAD_STACK_INFO]);
+    for (; (uint32_t) stack_pointer < stack_start_addr + stack_size; stack_pointer++) {
+        cmb_println("  addr: %08x    data: %08x", stack_pointer, *stack_pointer);
+    }
+    cmb_println("====================================");
+}
+#endif /* CMB_USING_DUMP_STACK_INFO */
+
+/* check the disassembly instruction is 'BL' or 'BLX' */
+static bool disassembly_ins_is_bl_blx(uint32_t addr) {
+    uint16_t ins1 = *((uint16_t *)addr);
+    uint16_t ins2 = *((uint16_t *)(addr + 2));
+
+#define BL_INS_MASK         0xF800
+#define BL_INS_HIGH         0xF800
+#define BL_INS_LOW          0xF000
+#define BLX_INX_MASK        0xFF00
+#define BLX_INX             0x4700
+
+    if ((ins2 & BL_INS_MASK) == BL_INS_HIGH && (ins1 & BL_INS_MASK) == BL_INS_LOW) {
+        return true;
+    } else if ((ins2 & BLX_INX_MASK) == BLX_INX) {
+        return true;
+    } else {
+        return false;
+    }
+}
+
+/**
+ * backtrace function call stack
+ *
+ * @param buffer call stack buffer
+ * @param size buffer size
+ * @param sp stack pointer
+ *
+ * @return depth
+ */
+size_t cm_backtrace_call_stack(uint32_t *buffer, size_t size, uint32_t sp) {
+    uint32_t stack_start_addr = main_stack_start_addr, pc;
+    size_t depth = 0, stack_size = main_stack_size;
+    bool regs_saved_lr_is_valid = false;
+
+    if (on_fault) {
+        if (!stack_is_overflow) {
+            /* first depth is PC */
+            buffer[depth++] = regs.saved.pc;
+            /* fix the LR address in thumb mode */
+            pc = regs.saved.lr - 1;
+            if ((pc >= code_start_addr) && (pc <= code_start_addr + code_size) && (depth < CMB_CALL_STACK_MAX_DEPTH)
+                    && (depth < size)) {
+                buffer[depth++] = pc;
+                regs_saved_lr_is_valid = true;
+            }
+        }
+
+#ifdef CMB_USING_OS_PLATFORM
+        /* program is running on thread before fault */
+        if (on_thread_before_fault) {
+            get_cur_thread_stack_info(sp, &stack_start_addr, &stack_size);
+        }
+    } else {
+        /* OS environment */
+        if (cmb_get_sp() == cmb_get_psp()) {
+            get_cur_thread_stack_info(sp, &stack_start_addr, &stack_size);
+        }
+#endif /* CMB_USING_OS_PLATFORM */
+
+    }
+
+    if (stack_is_overflow) {
+        if (sp < stack_start_addr) {
+            sp = stack_start_addr;
+        } else if (sp > stack_start_addr + stack_size) {
+            sp = stack_start_addr + stack_size;
+        }
+    }
+
+    /* copy called function address */
+    for (; sp < stack_start_addr + stack_size; sp += sizeof(size_t)) {
+        /* the *sp value may be LR, so need decrease a word to PC */
+        pc = *((uint32_t *) sp) - sizeof(size_t);
+        /* the Cortex-M using thumb instruction, so the pc must be an odd number */
+        if (pc % 2 == 0) {
+            continue;
+        }
+        /* fix the PC address in thumb mode */
+        pc = *((uint32_t *) sp) - 1;
+        if ((pc >= code_start_addr + sizeof(size_t)) && (pc <= code_start_addr + code_size) && (depth < CMB_CALL_STACK_MAX_DEPTH)
+                /* check the the instruction before PC address is 'BL' or 'BLX' */
+                && disassembly_ins_is_bl_blx(pc - sizeof(size_t)) && (depth < size)) {
+            /* the second depth function may be already saved, so need ignore repeat */
+            if ((depth == 2) && regs_saved_lr_is_valid && (pc == buffer[1])) {
+                continue;
+            }
+            buffer[depth++] = pc;
+        }
+    }
+
+    return depth;
+}
+
+/**
+ * dump function call stack
+ *
+ * @param sp stack pointer
+ */
+static void print_call_stack(uint32_t sp) {
+    size_t i, cur_depth = 0;
+    uint32_t call_stack_buf[CMB_CALL_STACK_MAX_DEPTH] = {0};
+
+    cur_depth = cm_backtrace_call_stack(call_stack_buf, CMB_CALL_STACK_MAX_DEPTH, sp);
+
+    for (i = 0; i < cur_depth; i++) {
+        sprintf(call_stack_info + i * (8 + 1), "%08lx", (unsigned long)call_stack_buf[i]);
+        call_stack_info[i * (8 + 1) + 8] = ' ';
+    }
+
+    if (cur_depth) {
+        call_stack_info[cur_depth * (8 + 1) - 1] = '\0';
+        cmb_println(print_info[PRINT_CALL_STACK_INFO], fw_name, CMB_ELF_FILE_EXTENSION_NAME, call_stack_info);
+    } else {
+        cmb_println(print_info[PRINT_CALL_STACK_ERR]);
+    }
+}
+
+/**
+ * backtrace for assert
+ *
+ * @param sp the stack pointer when on assert occurred
+ */
+void cm_backtrace_assert(uint32_t sp) {
+    CMB_ASSERT(init_ok);
+
+#ifdef CMB_USING_OS_PLATFORM
+    uint32_t cur_stack_pointer = cmb_get_sp();
+#endif
+
+    cmb_println("");
+    cm_backtrace_firmware_info();
+
+#ifdef CMB_USING_OS_PLATFORM
+    /* OS environment */
+    if (cur_stack_pointer == cmb_get_msp()) {
+        cmb_println(print_info[PRINT_ASSERT_ON_HANDLER]);
+
+#ifdef CMB_USING_DUMP_STACK_INFO
+        dump_stack(main_stack_start_addr, main_stack_size, (uint32_t *) sp);
+#endif /* CMB_USING_DUMP_STACK_INFO */
+
+    } else if (cur_stack_pointer == cmb_get_psp()) {
+        cmb_println(print_info[PRINT_ASSERT_ON_THREAD], get_cur_thread_name());
+
+#ifdef CMB_USING_DUMP_STACK_INFO
+        uint32_t stack_start_addr;
+        size_t stack_size;
+        get_cur_thread_stack_info(sp, &stack_start_addr, &stack_size);
+        dump_stack(stack_start_addr, stack_size, (uint32_t *) sp);
+#endif /* CMB_USING_DUMP_STACK_INFO */
+
+    }
+
+#else
+
+    /* bare metal(no OS) environment */
+#ifdef CMB_USING_DUMP_STACK_INFO
+    dump_stack(main_stack_start_addr, main_stack_size, (uint32_t *) sp);
+#endif /* CMB_USING_DUMP_STACK_INFO */
+
+#endif /* CMB_USING_OS_PLATFORM */
+
+    print_call_stack(sp);
+}
+
+#if (CMB_CPU_PLATFORM_TYPE != CMB_CPU_ARM_CORTEX_M0)
+/**
+ * fault diagnosis then print cause of fault
+ */
+static void fault_diagnosis(void) {
+    if (regs.hfsr.bits.VECTBL) {
+        cmb_println(print_info[PRINT_HFSR_VECTBL]);
+    }
+    if (regs.hfsr.bits.FORCED) {
+        /* Memory Management Fault */
+        if (regs.mfsr.value) {
+            if (regs.mfsr.bits.IACCVIOL) {
+                cmb_println(print_info[PRINT_MFSR_IACCVIOL]);
+            }
+            if (regs.mfsr.bits.DACCVIOL) {
+                cmb_println(print_info[PRINT_MFSR_DACCVIOL]);
+            }
+            if (regs.mfsr.bits.MUNSTKERR) {
+                cmb_println(print_info[PRINT_MFSR_MUNSTKERR]);
+            }
+            if (regs.mfsr.bits.MSTKERR) {
+                cmb_println(print_info[PRINT_MFSR_MSTKERR]);
+            }
+
+#if (CMB_CPU_PLATFORM_TYPE == CMB_CPU_ARM_CORTEX_M4) || (CMB_CPU_PLATFORM_TYPE == CMB_CPU_ARM_CORTEX_M7) || \
+    (CMB_CPU_PLATFORM_TYPE == CMB_CPU_ARM_CORTEX_M33)
+            if (regs.mfsr.bits.MLSPERR) {
+                cmb_println(print_info[PRINT_MFSR_MLSPERR]);
+            }
+#endif
+
+            if (regs.mfsr.bits.MMARVALID) {
+                if (regs.mfsr.bits.IACCVIOL || regs.mfsr.bits.DACCVIOL) {
+                    cmb_println(print_info[PRINT_MMAR], regs.mmar);
+                }
+            }
+        }
+        /* Bus Fault */
+        if (regs.bfsr.value) {
+            if (regs.bfsr.bits.IBUSERR) {
+                cmb_println(print_info[PRINT_BFSR_IBUSERR]);
+            }
+            if (regs.bfsr.bits.PRECISERR) {
+                cmb_println(print_info[PRINT_BFSR_PRECISERR]);
+            }
+            if (regs.bfsr.bits.IMPREISERR) {
+                cmb_println(print_info[PRINT_BFSR_IMPREISERR]);
+            }
+            if (regs.bfsr.bits.UNSTKERR) {
+                cmb_println(print_info[PRINT_BFSR_UNSTKERR]);
+            }
+            if (regs.bfsr.bits.STKERR) {
+                cmb_println(print_info[PRINT_BFSR_STKERR]);
+            }
+
+#if (CMB_CPU_PLATFORM_TYPE == CMB_CPU_ARM_CORTEX_M4) || (CMB_CPU_PLATFORM_TYPE == CMB_CPU_ARM_CORTEX_M7) || \
+    (CMB_CPU_PLATFORM_TYPE == CMB_CPU_ARM_CORTEX_M33)
+            if (regs.bfsr.bits.LSPERR) {
+                cmb_println(print_info[PRINT_BFSR_LSPERR]);
+            }
+#endif
+
+            if (regs.bfsr.bits.BFARVALID) {
+                if (regs.bfsr.bits.PRECISERR) {
+                    cmb_println(print_info[PRINT_BFAR], regs.bfar);
+                }
+            }
+
+        }
+        /* Usage Fault */
+        if (regs.ufsr.value) {
+            if (regs.ufsr.bits.UNDEFINSTR) {
+                cmb_println(print_info[PRINT_UFSR_UNDEFINSTR]);
+            }
+            if (regs.ufsr.bits.INVSTATE) {
+                cmb_println(print_info[PRINT_UFSR_INVSTATE]);
+            }
+            if (regs.ufsr.bits.INVPC) {
+                cmb_println(print_info[PRINT_UFSR_INVPC]);
+            }
+            if (regs.ufsr.bits.NOCP) {
+                cmb_println(print_info[PRINT_UFSR_NOCP]);
+            }
+#if (CMB_CPU_PLATFORM_TYPE == CMB_CPU_ARM_CORTEX_M33)
+            if (regs.ufsr.bits.STKOF) {
+                cmb_println(print_info[PRINT_UFSR_STKOF]);
+            }
+#endif
+            if (regs.ufsr.bits.UNALIGNED) {
+                cmb_println(print_info[PRINT_UFSR_UNALIGNED]);
+            }
+            if (regs.ufsr.bits.DIVBYZERO0) {
+                cmb_println(print_info[PRINT_UFSR_DIVBYZERO0]);
+            }
+        }
+    }
+    /* Debug Fault */
+    if (regs.hfsr.bits.DEBUGEVT) {
+        if (regs.dfsr.value) {
+            if (regs.dfsr.bits.HALTED) {
+                cmb_println(print_info[PRINT_DFSR_HALTED]);
+            }
+            if (regs.dfsr.bits.BKPT) {
+                cmb_println(print_info[PRINT_DFSR_BKPT]);
+            }
+            if (regs.dfsr.bits.DWTTRAP) {
+                cmb_println(print_info[PRINT_DFSR_DWTTRAP]);
+            }
+            if (regs.dfsr.bits.VCATCH) {
+                cmb_println(print_info[PRINT_DFSR_VCATCH]);
+            }
+            if (regs.dfsr.bits.EXTERNAL) {
+                cmb_println(print_info[PRINT_DFSR_EXTERNAL]);
+            }
+        }
+    }
+}
+#endif /* (CMB_CPU_PLATFORM_TYPE != CMB_CPU_ARM_CORTEX_M0) */
+
+#if (CMB_CPU_PLATFORM_TYPE == CMB_CPU_ARM_CORTEX_M4) || (CMB_CPU_PLATFORM_TYPE == CMB_CPU_ARM_CORTEX_M7) || \
+    (CMB_CPU_PLATFORM_TYPE == CMB_CPU_ARM_CORTEX_M33)
+static uint32_t statck_del_fpu_regs(uint32_t fault_handler_lr, uint32_t sp) {
+    statck_has_fpu_regs = (fault_handler_lr & (1UL << 4)) == 0 ? true : false;
+
+    /* the stack has S0~S15 and FPSCR registers when statck_has_fpu_regs is true, double word align */
+    return statck_has_fpu_regs == true ? sp + sizeof(size_t) * 18 : sp;
+}
+#endif
+
+/**
+ * backtrace for fault
+ * @note only call once
+ *
+ * @param fault_handler_lr the LR register value on fault handler
+ * @param fault_handler_sp the stack pointer on fault handler
+ */
+void cm_backtrace_fault(uint32_t fault_handler_lr, uint32_t fault_handler_sp) {
+    uint32_t stack_pointer = fault_handler_sp, saved_regs_addr = stack_pointer;
+    const char *regs_name[] = { "R0 ", "R1 ", "R2 ", "R3 ", "R12", "LR ", "PC ", "PSR" };
+
+#ifdef CMB_USING_DUMP_STACK_INFO
+    uint32_t stack_start_addr = main_stack_start_addr;
+    size_t stack_size = main_stack_size;
+#endif
+
+    CMB_ASSERT(init_ok);
+    /* only call once */
+    CMB_ASSERT(!on_fault);
+
+    on_fault = true;
+
+    cmb_println("");
+    cm_backtrace_firmware_info();
+
+#ifdef CMB_USING_OS_PLATFORM
+    on_thread_before_fault = fault_handler_lr & (1UL << 2);
+    /* check which stack was used before (MSP or PSP) */
+    if (on_thread_before_fault) {
+        cmb_println(print_info[PRINT_FAULT_ON_THREAD], get_cur_thread_name() != NULL ? get_cur_thread_name() : "NO_NAME");
+        saved_regs_addr = stack_pointer = cmb_get_psp();
+
+#ifdef CMB_USING_DUMP_STACK_INFO
+        get_cur_thread_stack_info(stack_pointer, &stack_start_addr, &stack_size);
+#endif /* CMB_USING_DUMP_STACK_INFO */
+
+    } else {
+        cmb_println(print_info[PRINT_FAULT_ON_HANDLER]);
+    }
+#else
+    /* bare metal(no OS) environment */
+    cmb_println(print_info[PRINT_FAULT_ON_HANDLER]);
+#endif /* CMB_USING_OS_PLATFORM */
+
+    /* delete saved R0~R3, R12, LR,PC,xPSR registers space */
+    stack_pointer += sizeof(size_t) * 8;
+
+#if (CMB_CPU_PLATFORM_TYPE == CMB_CPU_ARM_CORTEX_M4) || (CMB_CPU_PLATFORM_TYPE == CMB_CPU_ARM_CORTEX_M7) || \
+    (CMB_CPU_PLATFORM_TYPE == CMB_CPU_ARM_CORTEX_M33)
+    stack_pointer = statck_del_fpu_regs(fault_handler_lr, stack_pointer);
+#endif /* (CMB_CPU_PLATFORM_TYPE == CMB_CPU_ARM_CORTEX_M4) || (CMB_CPU_PLATFORM_TYPE == CMB_CPU_ARM_CORTEX_M7) */
+
+#ifdef CMB_USING_DUMP_STACK_INFO
+    /* check stack overflow */
+    if (stack_pointer < stack_start_addr || stack_pointer > stack_start_addr + stack_size) {
+        stack_is_overflow = true;
+    }
+    /* dump stack information */
+    dump_stack(stack_start_addr, stack_size, (uint32_t *) stack_pointer);
+#endif /* CMB_USING_DUMP_STACK_INFO */
+
+    /* the stack frame may be get failed when it is overflow  */
+    if (!stack_is_overflow) {
+        /* dump register */
+        cmb_println(print_info[PRINT_REGS_TITLE]);
+
+        regs.saved.r0        = ((uint32_t *)saved_regs_addr)[0];  // Register R0
+        regs.saved.r1        = ((uint32_t *)saved_regs_addr)[1];  // Register R1
+        regs.saved.r2        = ((uint32_t *)saved_regs_addr)[2];  // Register R2
+        regs.saved.r3        = ((uint32_t *)saved_regs_addr)[3];  // Register R3
+        regs.saved.r12       = ((uint32_t *)saved_regs_addr)[4];  // Register R12
+        regs.saved.lr        = ((uint32_t *)saved_regs_addr)[5];  // Link register LR
+        regs.saved.pc        = ((uint32_t *)saved_regs_addr)[6];  // Program counter PC
+        regs.saved.psr.value = ((uint32_t *)saved_regs_addr)[7];  // Program status word PSR
+
+        cmb_println("  %s: %08x  %s: %08x  %s: %08x  %s: %08x", regs_name[0], regs.saved.r0,
+                                                                regs_name[1], regs.saved.r1,
+                                                                regs_name[2], regs.saved.r2,
+                                                                regs_name[3], regs.saved.r3);
+        cmb_println("  %s: %08x  %s: %08x  %s: %08x  %s: %08x", regs_name[4], regs.saved.r12,
+                                                                regs_name[5], regs.saved.lr,
+                                                                regs_name[6], regs.saved.pc,
+                                                                regs_name[7], regs.saved.psr.value);
+        cmb_println("==============================================================");
+    }
+
+    /* the Cortex-M0 is not support fault diagnosis */
+#if (CMB_CPU_PLATFORM_TYPE != CMB_CPU_ARM_CORTEX_M0)
+    regs.syshndctrl.value = CMB_SYSHND_CTRL;  // System Handler Control and State Register
+    regs.mfsr.value       = CMB_NVIC_MFSR;    // Memory Fault Status Register
+    regs.mmar             = CMB_NVIC_MMAR;    // Memory Management Fault Address Register
+    regs.bfsr.value       = CMB_NVIC_BFSR;    // Bus Fault Status Register
+    regs.bfar             = CMB_NVIC_BFAR;    // Bus Fault Manage Address Register
+    regs.ufsr.value       = CMB_NVIC_UFSR;    // Usage Fault Status Register
+    regs.hfsr.value       = CMB_NVIC_HFSR;    // Hard Fault Status Register
+    regs.dfsr.value       = CMB_NVIC_DFSR;    // Debug Fault Status Register
+    regs.afsr             = CMB_NVIC_AFSR;    // Auxiliary Fault Status Register
+
+    fault_diagnosis();
+#endif
+
+    print_call_stack(stack_pointer);
+}

+ 48 - 0
code/debug/cm_backtrace/cm_backtrace.h

@@ -0,0 +1,48 @@
+/*
+ * This file is part of the CmBacktrace Library.
+ *
+ * Copyright (c) 2016, Armink, <armink.ztl@gmail.com>
+ *
+ * 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.
+ *
+ * Function: It is an head file for this library. You can see all be called functions.
+ * Created on: 2016-12-15
+ */
+
+#ifndef _CORTEXM_BACKTRACE_H_
+#define _CORTEXM_BACKTRACE_H_
+
+#include "cmb_def.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+void cm_backtrace_init(const char *firmware_name, const char *hardware_ver, const char *software_ver);
+void cm_backtrace_firmware_info(void);
+size_t cm_backtrace_call_stack(uint32_t *buffer, size_t size, uint32_t sp);
+void cm_backtrace_assert(uint32_t sp);
+void cm_backtrace_fault(uint32_t fault_handler_lr, uint32_t fault_handler_sp);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* _CORTEXM_BACKTRACE_H_ */

+ 46 - 0
code/debug/cm_backtrace/cmb_cfg.h

@@ -0,0 +1,46 @@
+/*
+ * This file is part of the CmBacktrace Library.
+ *
+ * Copyright (c) 2016, Armink, <armink.ztl@gmail.com>
+ *
+ * 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.
+ *
+ * Function: It is the configure head file for this library.
+ * Created on: 2016-12-15
+ */
+
+#ifndef _CMB_CFG_H_
+#define _CMB_CFG_H_
+#include "SEGGER_RTT.h"
+/* print line, must config by user */
+#define cmb_println(...)       SEGGER_RTT_printf(__VA_ARGS__);SEGGER_RTT_printf("\r\n");        /* e.g., printf(__VA_ARGS__);printf("\r\n")  or  SEGGER_RTT_printf(0, __VA_ARGS__);SEGGER_RTT_WriteString(0, "\r\n")  */
+/* enable bare metal(no OS) platform */
+/* #define CMB_USING_BARE_METAL_PLATFORM */
+/* enable OS platform */
+#define CMB_USING_OS_PLATFORM
+/* OS platform type, must config when CMB_USING_OS_PLATFORM is enable */
+#define CMB_OS_PLATFORM_TYPE   CMB_OS_PLATFORM_FREERTOS        /*CMB_OS_PLATFORM_RTT or CMB_OS_PLATFORM_UCOSII or CMB_OS_PLATFORM_UCOSIII or CMB_OS_PLATFORM_FREERTOS or CMB_OS_PLATFORM_RTX5 */
+/* cpu platform type, must config by user */
+#define CMB_CPU_PLATFORM_TYPE  CMB_CPU_ARM_CORTEX_M4     /* CMB_CPU_ARM_CORTEX_M0 or CMB_CPU_ARM_CORTEX_M3 or CMB_CPU_ARM_CORTEX_M4 or CMB_CPU_ARM_CORTEX_M7 */
+/* enable dump stack information */
+#define CMB_USING_DUMP_STACK_INFO
+/* language of print information */
+/*#define CMB_PRINT_LANGUAGE            /*  CMB_PRINT_LANGUAGE_ENGLISH(default) or CMB_PRINT_LANGUAGE_CHINESE */
+#endif /* _CMB_CFG_H_ */

+ 417 - 0
code/debug/cm_backtrace/cmb_def.h

@@ -0,0 +1,417 @@
+/*
+ * This file is part of the CmBacktrace Library.
+ *
+ * Copyright (c) 2016-2020, Armink, <armink.ztl@gmail.com>
+ *
+ * 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.
+ *
+ * Function: It is the macro definition head file for this library.
+ * Created on: 2016-12-15
+ */
+
+#ifndef _CMB_DEF_H_
+#define _CMB_DEF_H_
+
+#include <cmb_cfg.h>
+#include <stdint.h>
+#include <stdlib.h>
+
+/* library software version number */
+#define CMB_SW_VERSION                "1.4.1"
+
+#define CMB_CPU_ARM_CORTEX_M0             0
+#define CMB_CPU_ARM_CORTEX_M3             1
+#define CMB_CPU_ARM_CORTEX_M4             2
+#define CMB_CPU_ARM_CORTEX_M7             3
+#define CMB_CPU_ARM_CORTEX_M33            4
+
+#define CMB_OS_PLATFORM_RTT               0
+#define CMB_OS_PLATFORM_UCOSII            1
+#define CMB_OS_PLATFORM_UCOSIII           2
+#define CMB_OS_PLATFORM_FREERTOS          3
+#define CMB_OS_PLATFORM_RTX5              4
+
+#define CMB_PRINT_LANGUAGE_ENGLISH        0
+#define CMB_PRINT_LANGUAGE_CHINESE        1
+#define CMB_PRINT_LANGUAGE_CHINESE_UTF8   2
+
+/* name max length, default size: 32 */
+#ifndef CMB_NAME_MAX
+#define CMB_NAME_MAX                      32
+#endif
+
+/* print information language, default is English */
+#ifndef CMB_PRINT_LANGUAGE
+#define CMB_PRINT_LANGUAGE                CMB_PRINT_LANGUAGE_ENGLISH
+#endif
+
+
+#if defined(__ARMCC_VERSION)
+    /* C stack block name, default is STACK */
+    #ifndef CMB_CSTACK_BLOCK_NAME
+    #define CMB_CSTACK_BLOCK_NAME          STACK
+    #endif
+    /* code section name, default is ER_IROM1 */
+    #ifndef CMB_CODE_SECTION_NAME
+    #define CMB_CODE_SECTION_NAME          ER_IROM1
+    #endif
+#elif defined(__ICCARM__)
+    /* C stack block name, default is 'CSTACK' */
+    #ifndef CMB_CSTACK_BLOCK_NAME
+    #define CMB_CSTACK_BLOCK_NAME          "CSTACK"
+    #endif
+    /* code section name, default is '.text' */
+    #ifndef CMB_CODE_SECTION_NAME
+    #define CMB_CODE_SECTION_NAME          ".text"
+    #endif
+#elif defined(__GNUC__)
+    /* C stack block start address, defined on linker script file, default is _sstack */
+    #ifndef CMB_CSTACK_BLOCK_START
+    #define CMB_CSTACK_BLOCK_START         __Stack_start_c0
+    #endif
+    /* C stack block end address, defined on linker script file, default is _estack */
+    #ifndef CMB_CSTACK_BLOCK_END
+    #define CMB_CSTACK_BLOCK_END           __Stack_end_c0
+    #endif
+    /* code section start address, defined on linker script file, default is _stext */
+    #ifndef CMB_CODE_SECTION_START
+    #define CMB_CODE_SECTION_START         acfls_code_rom_start
+    #endif
+    /* code section end address, defined on linker script file, default is _etext */
+    #ifndef CMB_CODE_SECTION_END
+    #define CMB_CODE_SECTION_END           acfls_code_rom_end
+    #endif
+#else
+    #error "not supported compiler"
+#endif
+
+/* supported function call stack max depth, default is 16 */
+#ifndef CMB_CALL_STACK_MAX_DEPTH
+#define CMB_CALL_STACK_MAX_DEPTH       16
+#endif
+
+/* system handler control and state register */
+#ifndef CMB_SYSHND_CTRL
+#define CMB_SYSHND_CTRL                (*(volatile unsigned int*)  (0xE000ED24u))
+#endif
+
+/* memory management fault status register */
+#ifndef CMB_NVIC_MFSR
+#define CMB_NVIC_MFSR                  (*(volatile unsigned char*) (0xE000ED28u))
+#endif
+
+/* bus fault status register */
+#ifndef CMB_NVIC_BFSR
+#define CMB_NVIC_BFSR                  (*(volatile unsigned char*) (0xE000ED29u))
+#endif
+
+/* usage fault status register */
+#ifndef CMB_NVIC_UFSR
+#define CMB_NVIC_UFSR                  (*(volatile unsigned short*)(0xE000ED2Au))
+#endif
+
+/* hard fault status register */
+#ifndef CMB_NVIC_HFSR
+#define CMB_NVIC_HFSR                  (*(volatile unsigned int*)  (0xE000ED2Cu))
+#endif
+
+/* debug fault status register */
+#ifndef CMB_NVIC_DFSR
+#define CMB_NVIC_DFSR                  (*(volatile unsigned short*)(0xE000ED30u))
+#endif
+
+/* memory management fault address register */
+#ifndef CMB_NVIC_MMAR
+#define CMB_NVIC_MMAR                  (*(volatile unsigned int*)  (0xE000ED34u))
+#endif
+
+/* bus fault manage address register */
+#ifndef CMB_NVIC_BFAR
+#define CMB_NVIC_BFAR                  (*(volatile unsigned int*)  (0xE000ED38u))
+#endif
+
+/* auxiliary fault status register */
+#ifndef CMB_NVIC_AFSR
+#define CMB_NVIC_AFSR                  (*(volatile unsigned short*)(0xE000ED3Cu))
+#endif
+
+/**
+ * Cortex-M fault registers
+ */
+struct cmb_hard_fault_regs{
+  struct {
+    unsigned int r0;                     // Register R0
+    unsigned int r1;                     // Register R1
+    unsigned int r2;                     // Register R2
+    unsigned int r3;                     // Register R3
+    unsigned int r12;                    // Register R12
+    unsigned int lr;                     // Link register
+    unsigned int pc;                     // Program counter
+    union {
+      unsigned int value;
+      struct {
+#if (CMB_CPU_PLATFORM_TYPE == CMB_CPU_ARM_CORTEX_M33)
+        unsigned int IPSR : 9;           // Interrupt Program Status register (IPSR)
+        unsigned int EPSR : 18;          // Execution Program Status register (EPSR)
+        unsigned int APSR : 5;           // Application Program Status register (APSR)
+#else
+        unsigned int IPSR : 8;           // Interrupt Program Status register (IPSR)
+        unsigned int EPSR : 19;          // Execution Program Status register (EPSR)
+        unsigned int APSR : 5;           // Application Program Status register (APSR)
+#endif
+      } bits;
+    } psr;                               // Program status register.
+  } saved;
+
+  union {
+    unsigned int value;
+    struct {
+      unsigned int MEMFAULTACT    : 1;   // Read as 1 if memory management fault is active
+      unsigned int BUSFAULTACT    : 1;   // Read as 1 if bus fault exception is active
+#if (CMB_CPU_PLATFORM_TYPE == CMB_CPU_ARM_CORTEX_M33)
+      unsigned int HARDFAULTACT   : 1;   // Read as 1 if hardfault is active
+#else
+      unsigned int UnusedBits1    : 1;
+#endif
+      unsigned int USGFAULTACT    : 1;   // Read as 1 if usage fault exception is active
+#if (CMB_CPU_PLATFORM_TYPE == CMB_CPU_ARM_CORTEX_M33)
+      unsigned int SECUREFAULTACT : 1;   // Read as 1 if secure fault exception is active
+      unsigned int NMIACT         : 1;   // Read as 1 if NMI exception is active
+      unsigned int UnusedBits2    : 1;
+#else
+      unsigned int UnusedBits2    : 3;
+#endif
+      unsigned int SVCALLACT      : 1;   // Read as 1 if SVC exception is active
+      unsigned int MONITORACT     : 1;   // Read as 1 if debug monitor exception is active
+      unsigned int UnusedBits3    : 1;
+      unsigned int PENDSVACT      : 1;   // Read as 1 if PendSV exception is active
+      unsigned int SYSTICKACT     : 1;   // Read as 1 if SYSTICK exception is active
+      unsigned int USGFAULTPENDED : 1;   // Usage fault pended; usage fault started but was replaced by a higher-priority exception
+      unsigned int MEMFAULTPENDED : 1;   // Memory management fault pended; memory management fault started but was replaced by a higher-priority exception
+      unsigned int BUSFAULTPENDED : 1;   // Bus fault pended; bus fault handler was started but was replaced by a higher-priority exception
+      unsigned int SVCALLPENDED   : 1;   // SVC pended; SVC was started but was replaced by a higher-priority exception
+      unsigned int MEMFAULTENA    : 1;   // Memory management fault handler enable
+      unsigned int BUSFAULTENA    : 1;   // Bus fault handler enable
+      unsigned int USGFAULTENA    : 1;   // Usage fault handler enable
+#if (CMB_CPU_PLATFORM_TYPE == CMB_CPU_ARM_CORTEX_M33)
+      unsigned int SECUREFAULTENA : 1;   // Secure fault handler enable
+      unsigned int SECUREFAULTPENDED : 1;   // Secure fault pended; Secure fault handler was started but was replaced by a higher-priority exception
+      unsigned int HARDFAULTPENDED   : 1;   // Hard fault pended; Hard fault handler was started but was replaced by a higher-priority exception
+#else
+      // None
+#endif
+    } bits;
+  } syshndctrl;                          // System Handler Control and State Register (0xE000ED24)
+
+  union {
+    unsigned char value;
+    struct {
+      unsigned char IACCVIOL    : 1;     // Instruction access violation
+      unsigned char DACCVIOL    : 1;     // Data access violation
+      unsigned char UnusedBits  : 1;
+      unsigned char MUNSTKERR   : 1;     // Unstacking error
+      unsigned char MSTKERR     : 1;     // Stacking error
+      unsigned char MLSPERR     : 1;     // Floating-point lazy state preservation (M4/M7)
+      unsigned char UnusedBits2 : 1;
+      unsigned char MMARVALID   : 1;     // Indicates the MMAR is valid
+    } bits;
+  } mfsr;                                // Memory Management Fault Status Register (0xE000ED28)
+  unsigned int mmar;                     // Memory Management Fault Address Register (0xE000ED34)
+
+  union {
+    unsigned char value;
+    struct {
+      unsigned char IBUSERR    : 1;      // Instruction access violation
+      unsigned char PRECISERR  : 1;      // Precise data access violation
+      unsigned char IMPREISERR : 1;      // Imprecise data access violation
+      unsigned char UNSTKERR   : 1;      // Unstacking error
+      unsigned char STKERR     : 1;      // Stacking error
+      unsigned char LSPERR     : 1;      // Floating-point lazy state preservation (M4/M7)
+      unsigned char UnusedBits : 1;
+      unsigned char BFARVALID  : 1;      // Indicates BFAR is valid
+    } bits;
+  } bfsr;                                // Bus Fault Status Register (0xE000ED29)
+  unsigned int bfar;                     // Bus Fault Manage Address Register (0xE000ED38)
+
+  union {
+    unsigned short value;
+    struct {
+      unsigned short UNDEFINSTR : 1;     // Attempts to execute an undefined instruction
+      unsigned short INVSTATE   : 1;     // Attempts to switch to an invalid state (e.g., ARM)
+      unsigned short INVPC      : 1;     // Attempts to do an exception with a bad value in the EXC_RETURN number
+      unsigned short NOCP       : 1;     // Attempts to execute a coprocessor instruction
+#if (CMB_CPU_PLATFORM_TYPE == CMB_CPU_ARM_CORTEX_M33)
+      unsigned short STKOF      : 1;     // Indicates a stack overflow error has occured
+      unsigned short UnusedBits : 3;
+#else
+      unsigned short UnusedBits : 4;
+#endif
+      unsigned short UNALIGNED  : 1;     // Indicates that an unaligned access fault has taken place
+      unsigned short DIVBYZERO0 : 1;     // Indicates a divide by zero has taken place (can be set only if DIV_0_TRP is set)
+    } bits;
+  } ufsr;                                // Usage Fault Status Register (0xE000ED2A)
+
+  union {
+    unsigned int value;
+    struct {
+      unsigned int UnusedBits  : 1;
+      unsigned int VECTBL      : 1;      // Indicates hard fault is caused by failed vector fetch
+      unsigned int UnusedBits2 : 28;
+      unsigned int FORCED      : 1;      // Indicates hard fault is taken because of bus fault/memory management fault/usage fault
+      unsigned int DEBUGEVT    : 1;      // Indicates hard fault is triggered by debug event
+    } bits;
+  } hfsr;                                // Hard Fault Status Register (0xE000ED2C)
+
+  union {
+    unsigned int value;
+    struct {
+      unsigned int HALTED   : 1;         // Halt requested in NVIC
+      unsigned int BKPT     : 1;         // BKPT instruction executed
+      unsigned int DWTTRAP  : 1;         // DWT match occurred
+      unsigned int VCATCH   : 1;         // Vector fetch occurred
+      unsigned int EXTERNAL : 1;         // EDBGRQ signal asserted
+    } bits;
+  } dfsr;                                // Debug Fault Status Register (0xE000ED30)
+
+  unsigned int afsr;                     // Auxiliary Fault Status Register (0xE000ED3C), Vendor controlled (optional)
+};
+
+/* assert for developer. */
+#define CMB_ASSERT(EXPR)                                                       \
+if (!(EXPR))                                                                   \
+{                                                                              \
+    cmb_println("(%s) has assert failed at %s.", #EXPR, __FUNCTION__);         \
+    while (1);                                                                 \
+}
+
+/* ELF(Executable and Linking Format) file extension name for each compiler */
+#if defined(__ARMCC_VERSION)
+    #define CMB_ELF_FILE_EXTENSION_NAME          ".axf"
+#elif defined(__ICCARM__)
+    #define CMB_ELF_FILE_EXTENSION_NAME          ".out"
+#elif defined(__GNUC__)
+    #define CMB_ELF_FILE_EXTENSION_NAME          ".elf"
+#else
+    #error "not supported compiler"
+#endif
+
+#ifndef cmb_println
+    #error "cmb_println isn't defined in 'cmb_cfg.h'"
+#endif
+
+#ifndef CMB_CPU_PLATFORM_TYPE
+    #error "CMB_CPU_PLATFORM_TYPE isn't defined in 'cmb_cfg.h'"
+#endif
+
+#if (defined(CMB_USING_BARE_METAL_PLATFORM) && defined(CMB_USING_OS_PLATFORM))
+    #error "CMB_USING_BARE_METAL_PLATFORM and CMB_USING_OS_PLATFORM only one of them can be used"
+#elif defined(CMB_USING_OS_PLATFORM)
+    #if !defined(CMB_OS_PLATFORM_TYPE)
+        #error "CMB_OS_PLATFORM_TYPE isn't defined in 'cmb_cfg.h'"
+    #endif /* !defined(CMB_OS_PLATFORM_TYPE) */
+    #if (CMB_OS_PLATFORM_TYPE == CMB_OS_PLATFORM_RTT)
+        #include <rtthread.h>
+    #elif (CMB_OS_PLATFORM_TYPE == CMB_OS_PLATFORM_UCOSII)
+        #include <ucos_ii.h>
+    #elif (CMB_OS_PLATFORM_TYPE == CMB_OS_PLATFORM_UCOSIII)
+        #include <os.h>
+    #elif (CMB_OS_PLATFORM_TYPE == CMB_OS_PLATFORM_FREERTOS)
+        #include <FreeRTOS.h>  
+        extern uint32_t *vTaskStackAddr(void);/* need to modify the FreeRTOS/tasks source code */
+        extern uint32_t vTaskStackSize(void);
+        extern char * vTaskName(void);
+    #elif (CMB_OS_PLATFORM_TYPE == CMB_OS_PLATFORM_RTX5)
+        #include "rtx_os.h"
+    #else
+        #error "not supported OS type"
+    #endif /* (CMB_OS_PLATFORM_TYPE == CMB_OS_PLATFORM_RTT) */
+#endif /* (defined(CMB_USING_BARE_METAL_PLATFORM) && defined(CMB_USING_OS_PLATFORM)) */
+
+/* include or export for supported cmb_get_msp, cmb_get_psp and cmb_get_sp function */
+#if defined(__CC_ARM)
+    static __inline __asm uint32_t cmb_get_msp(void) {
+        mrs r0, msp
+        bx lr
+    }
+    static __inline __asm uint32_t cmb_get_psp(void) {
+        mrs r0, psp
+        bx lr
+    }
+    static __inline __asm uint32_t cmb_get_sp(void) {
+        mov r0, sp
+        bx lr
+    }
+#elif defined(__clang__)
+    __attribute__( (always_inline) ) static __inline uint32_t cmb_get_msp(void) {
+        uint32_t result;
+        __asm volatile ("mrs %0, msp" : "=r" (result) );
+        return (result);
+    }
+    __attribute__( (always_inline) ) static __inline uint32_t cmb_get_psp(void) {
+        uint32_t result;
+        __asm volatile ("mrs %0, psp" : "=r" (result) );
+        return (result);
+    }
+    __attribute__( (always_inline) ) static __inline uint32_t cmb_get_sp(void) {
+        uint32_t result;
+        __asm volatile ("mov %0, sp" : "=r" (result) );
+        return (result);
+    }
+#elif defined(__ICCARM__)
+/* IAR iccarm specific functions */
+/* Close Raw Asm Code Warning */  
+#pragma diag_suppress=Pe940    
+    static uint32_t cmb_get_msp(void)
+    {
+      __asm("mrs r0, msp");
+      __asm("bx lr");        
+    }
+    static uint32_t cmb_get_psp(void)
+    {
+      __asm("mrs r0, psp");
+      __asm("bx lr");        
+    }
+    static uint32_t cmb_get_sp(void)
+    {
+      __asm("mov r0, sp");
+      __asm("bx lr");       
+    }
+#pragma diag_default=Pe940  
+#elif defined(__GNUC__)
+    __attribute__( ( always_inline ) ) static inline uint32_t cmb_get_msp(void) {
+        register uint32_t result;
+        __asm volatile ("MRS %0, msp\n" : "=r" (result) );
+        return(result);
+    }
+    __attribute__( ( always_inline ) ) static inline uint32_t cmb_get_psp(void) {
+        register uint32_t result;
+        __asm volatile ("MRS %0, psp\n" : "=r" (result) );
+        return(result);
+    }
+    __attribute__( ( always_inline ) ) static inline uint32_t cmb_get_sp(void) {
+        register uint32_t result;
+        __asm volatile ("MOV %0, sp\n" : "=r" (result) );
+        return(result);
+    }
+#else
+    #error "not supported compiler"
+#endif
+
+#endif /* _CMB_DEF_H_ */

+ 43 - 0
code/debug/cm_backtrace/fault_handler/gcc/cmb_fault.S

@@ -0,0 +1,43 @@
+/*
+ * This file is part of the CmBacktrace Library.
+ *
+ * Copyright (c) 2016, Armink, <armink.ztl@gmail.com>
+ *
+ * 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.
+ *
+ * Function: Fault handler by GCC assembly code
+ * Created on: 2016-12-16
+ */
+
+.syntax unified
+.thumb
+.text
+
+/* NOTE: If use this file's HardFault_Handler, please comments the HardFault_Handler code on other file. */
+
+.global HardFault_Handler
+.type HardFault_Handler, %function
+HardFault_Handler:
+    MOV     r0, lr                  /* get lr */
+    MOV     r1, sp                  /* get stack pointer (current is MSP) */
+    BL      cm_backtrace_fault
+
+Fault_Loop:
+    BL      Fault_Loop              /* while(1) */

+ 47 - 0
code/debug/cm_backtrace/fault_handler/iar/cmb_fault.S

@@ -0,0 +1,47 @@
+;/*
+; * This file is part of the CmBacktrace Library.
+; *
+; * Copyright (c) 2016, Armink, <armink.ztl@gmail.com>
+; *
+; * 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.
+; *
+; * Function: Fault handler by EWARM assembly code
+; * Created on: 2016-12-16
+; */
+/*
+    SECTION    .text:CODE(2)
+    THUMB
+    REQUIRE8
+    PRESERVE8
+
+; NOTE: If use this file's HardFault_Handler, please comments the HardFault_Handler code on other file.
+    IMPORT cm_backtrace_fault
+    EXPORT HardFault_Handler
+
+HardFault_Handler:
+    MOV     r0, lr                  ; get lr
+    MOV     r1, sp                  ; get stack pointer (current is MSP)
+    BL      cm_backtrace_fault
+
+Fault_Loop
+    BL      Fault_Loop              ;while(1)
+
+    END
+*/

+ 48 - 0
code/debug/cm_backtrace/fault_handler/keil/cmb_fault.S

@@ -0,0 +1,48 @@
+;/*
+; * This file is part of the CmBacktrace Library.
+; *
+; * Copyright (c) 2016, Armink, <armink.ztl@gmail.com>
+; *
+; * 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.
+; *
+; * Function: Fault handler by MDK-ARM assembly code
+; * Created on: 2016-12-16
+; */
+/*
+    AREA |.text|, CODE, READONLY, ALIGN=2
+    THUMB
+    REQUIRE8
+    PRESERVE8
+
+; NOTE: If use this file's HardFault_Handler, please comments the HardFault_Handler code on other file.
+    IMPORT cm_backtrace_fault
+    EXPORT HardFault_Handler
+
+HardFault_Handler    PROC
+    MOV     r0, lr                  ; get lr
+    MOV     r1, sp                  ; get stack pointer (current is MSP)
+    BL      cm_backtrace_fault
+
+Fault_Loop
+    BL      Fault_Loop              ;while(1)
+    ENDP
+
+    END
+*/

+ 0 - 0
src/SL_Sc7a20_Driver.c → code/driver/SL_Sc7a20_Driver.c


+ 33 - 33
src/SL_Sc7a20_Driver.h → code/driver/SL_Sc7a20_Driver.h

@@ -5,26 +5,26 @@
 #include "StandardTypes.h"
 #include "Spi.h"
 
-/***使用驱动前请根据实际接线情况配置******/
-/**SC7A20的SDO 脚接地:  0****************/
-/**SC7A20的SDO 脚接电源:1****************/
+/***浣跨敤椹卞姩鍓嶈�鏍规嵁瀹為檯鎺ョ嚎鎯呭喌閰嶇疆******/
+/**SC7A20鐨凷DO 鑴氭帴鍦帮細  0****************/
+/**SC7A20鐨凷DO 鑴氭帴鐢垫簮锛�1****************/
 #define SC7A20_SDO_VDD_GND            1
 /*****************************************/
 
-/***使用驱动前请根据实际IIC情况进行配置***/
-/**SC7A20的IIC 接口地址类型 7bits:  0****/
-/**SC7A20的IIC 接口地址类型 8bits:  1****/
+/***浣跨敤椹卞姩鍓嶈�鏍规嵁瀹為檯IIC鎯呭喌杩涜�閰嶇疆***/
+/**SC7A20鐨処IC 鎺ュ彛鍦板潃绫诲瀷 7bits锛�  0****/
+/**SC7A20鐨処IC 鎺ュ彛鍦板潃绫诲瀷 8bits锛�  1****/
 #define SC7A20_IIC_7BITS_8BITS        0
 /*****************************************/
 
 #define  SL_SC7A20_16BIT_8BIT         1
-/**SC7A20的数据位数选择  16bits:    1****/
-/**SC7A20的数据位数选择   8bits:    0****/
+/**SC7A20鐨勬暟鎹�綅鏁伴€夋嫨  16bits锛�    1****/
+/**SC7A20鐨勬暟鎹�綅鏁伴€夋嫨   8bits锛�    0****/
 /*****************************************/
 
 #define  SL_SC7A20_SPI_IIC_MODE       0
-/**SC7A20 SPI IIC 选择    SPI:      0****/
-/**SC7A20 SPI IIC 选择    IIC:      1****/
+/**SC7A20 SPI IIC 閫夋嫨    SPI锛�      0****/
+/**SC7A20 SPI IIC 閫夋嫨    IIC锛�      1****/
 /*****************************************/
 
 #define SL_6D4D2D1D_SEL   			 6
@@ -89,11 +89,11 @@
 #define  SL_SC7A20_ACT_THS        (uint8)0x3E
 #define  SL_SC7A20_ACT_DURATION   (uint8)0x3F
 	
-/*连续读取数据时的数据寄存器地址*/
+/*杩炵画璇诲彇鏁版嵁鏃剁殑鏁版嵁瀵勫瓨鍣ㄥ湴鍧€*/
 #define  SL_SC7A20_DATA_OUT       (uint8)(SL_SC7A20_OUT_X_L)
 
-/**********特殊功能寄存器**********/
-/*非原厂技术人员请勿修改*/
+/**********鐗规畩鍔熻兘瀵勫瓨鍣�**********/
+/*闈炲師鍘傛妧鏈�汉鍛樿�鍕夸慨鏀�*/
 #define  SL_SC7A20_MTP_ENABLE            0x00
 #define  SL_SC7A20_MTP_CFG    	  (uint8)0x1E
 #define  SL_SC7A20_MTP_VALUE   	  (uint8)0x05
@@ -102,10 +102,10 @@
 #define  SL_SC7A20_I2C_PU_MSK     (uint8)0x04
 #define  SL_SC7A20_HR_ENABLE      (uint8)0X08
 #define  SL_SC7A20_BOOT_ENABLE    (uint8)0X80
-/*非原厂技术人员请勿修改*/
+/*闈炲師鍘傛妧鏈�汉鍛樿�鍕夸慨鏀�*/
 
 
-/***************数据更新速率**加速度计使能**********/
+/***************鏁版嵁鏇存柊閫熺巼**鍔犻€熷害璁′娇鑳�**********/
 #define  SL_SC7A20_ODR_POWER_DOWN (uint8)0x00
 #define  SL_SC7A20_ODR_1HZ        (uint8)0x17
 #define  SL_SC7A20_ODR_10HZ       (uint8)0x27
@@ -125,18 +125,18 @@
 #define  SL_SC7A20_LOWER_POWER_ODR_100HZ      (uint8)0x5F
 #define  SL_SC7A20_LOWER_POWER_ODR_200HZ      (uint8)0x6F
 #define  SL_SC7A20_LOWER_POWER_ODR_400HZ      (uint8)0x7F
-/***************数据更新速率**加速度计使能**********/
+/***************鏁版嵁鏇存柊閫熺巼**鍔犻€熷害璁′娇鑳�**********/
 
 
-/***************传感器量程设置**********************/
+/***************浼犳劅鍣ㄩ噺绋嬭�缃�**********************/
 #define  SL_SC7A20_FS_2G          (uint8)0x00
 #define  SL_SC7A20_FS_4G          (uint8)0x10
 #define  SL_SC7A20_FS_8G          (uint8)0x20
 #define  SL_SC7A20_FS_16G         (uint8)0x30
-/***************传感器量程设置**********************/
+/***************浼犳劅鍣ㄩ噺绋嬭�缃�**********************/
 
 
-/***取值在0-127之间,此处仅举例****/
+/***鍙栧€煎湪0-127涔嬮棿锛屾�澶勪粎涓句緥****/
 #define SL_SC7A20_INT_THS_5PERCENT   (uint8)0x06
 #define SL_SC7A20_INT_THS_10PERCENT  (uint8)0x0C
 #define SL_SC7A20_INT_THS_20PERCENT  (uint8)0x18
@@ -144,41 +144,41 @@
 #define SL_SC7A20_INT_THS_80PERCENT  (uint8)0x60
 
 
-/***取值在0-127之间,此处仅举例 乘以ODR单位时间****/
+/***鍙栧€煎湪0-127涔嬮棿锛屾�澶勪粎涓句緥 涔樹互ODR鍗曚綅鏃堕棿****/
 #define SL_SC7A20_INT_DURATION_2CLK  (uint8)0x02
 #define SL_SC7A20_INT_DURATION_5CLK  (uint8)0x05
 #define SL_SC7A20_INT_DURATION_10CLK (uint8)0x0A
 #define SL_SC7A20_INT_DURATION_30CLK  (uint8)0x2E
 
 
-/***中断有效时的电平设置,高电平相当于上升沿,低电平相当于下降沿****/
-#define SL_SC7A20_INT_ACTIVE_LOWER_LEVEL 0x02 //0x02:中断时INT1脚输出 低电平
-#define SL_SC7A20_INT_ACTIVE_HIGH_LEVEL  0x00 //0x00:中断时INT1脚输出 高电平 
+/***涓�柇鏈夋晥鏃剁殑鐢靛钩璁剧疆锛岄珮鐢靛钩鐩稿綋浜庝笂鍗囨部锛屼綆鐢靛钩鐩稿綋浜庝笅闄嶆部****/
+#define SL_SC7A20_INT_ACTIVE_LOWER_LEVEL 0x02 //0x02:涓�柇鏃禝NT1鑴氳緭鍑� 浣庣數骞�
+#define SL_SC7A20_INT_ACTIVE_HIGH_LEVEL  0x00 //0x00:涓�柇鏃禝NT1鑴氳緭鍑� 楂樼數骞� 
 
-/***中断有效时的电平设置,高电平相当于上升沿,低电平相当于下降沿****/
+/***涓�柇鏈夋晥鏃剁殑鐢靛钩璁剧疆锛岄珮鐢靛钩鐩稿綋浜庝笂鍗囨部锛屼綆鐢靛钩鐩稿綋浜庝笅闄嶆部****/
 #define SL_SC7A20_INT_AOI1_INT1          0x40 //AOI1 TO INT1
 #define SL_SC7A20_INT_AOI2_INT1          0x20 //AOI2 TO INT1
 
-/********客户需要进行的IIC接口封包函数****************/
+/********瀹㈡埛闇€瑕佽繘琛岀殑IIC鎺ュ彛灏佸寘鍑芥暟****************/
 Std_ReturnType Gsensor_SPI_Write(uint8 Addr,uint8 *DataBufferPtr,uint16 Length);
 Std_ReturnType Gsensor_SPI_Read(uint8 Addr,uint8 *DataBufferPtr,uint16 Length);
-/**Gsensor_SPI_Write 函数中, sl_spi_iic:0=spi  1=i2c  Reg:寄存器地址   data:寄存器的配置值******************/
-/**Gsensor_SPI_Write 函数 是一个单次写的函数*******************************************************************/
-/***Gsensor_SPI_Read 函数中, sl_spi_iic:0=spi  1=i2c Reg 同上,len:读取数据长度,buf:存储数据首地址(指针)***/
-/***Gsensor_SPI_Read 函数 是可以进行单次读或多次连续读取的函数*************************************************/
+/**Gsensor_SPI_Write 鍑芥暟涓�紝 sl_spi_iic:0=spi  1=i2c  Reg锛氬瘎瀛樺櫒鍦板潃   data锛氬瘎瀛樺櫒鐨勯厤缃�€�******************/
+/**Gsensor_SPI_Write 鍑芥暟 鏄�竴涓�崟娆″啓鐨勫嚱鏁�*******************************************************************/
+/***Gsensor_SPI_Read 鍑芥暟涓�紝 sl_spi_iic:0=spi  1=i2c Reg 鍚屼笂锛宭en:璇诲彇鏁版嵁闀垮害锛宐uf:瀛樺偍鏁版嵁棣栧湴鍧€锛堟寚閽堬級***/
+/***Gsensor_SPI_Read 鍑芥暟 鏄�彲浠ヨ繘琛屽崟娆¤�鎴栧�娆¤繛缁��鍙栫殑鍑芥暟*************************************************/
 
 
 
-/*** 客户IIC函数封装举例
+/*** 瀹㈡埛IIC鍑芥暟灏佽�涓句緥
 uint8 SL_MEMS_i2c_spi_Write(uint8 reg, uint8 data)
 {
-    i2cWrite(SC7A20_IIC_ADDRESS,  reg,  data);       //由客户的II函数接口决定
+    i2cWrite(SC7A20_IIC_ADDRESS,  reg,  data);       //鐢卞�鎴风殑II鍑芥暟鎺ュ彛鍐冲畾
     return 1;
 }
 
 uint8 SL_MEMS_i2c_spi_Read(uint8 reg, uint8 len, uint8 *buf)
 {
-    i2cRead( SC7A20_IIC_ADDRESS,  reg,  len, buf);//由客户的II函数接口决定
+    i2cRead( SC7A20_IIC_ADDRESS,  reg,  len, buf);//鐢卞�鎴风殑II鍑芥暟鎺ュ彛鍐冲畾
     return 1;
 }
 ***/
@@ -200,7 +200,7 @@ void  SL_SC7A20_AOI2_event(void);
 void  SL_SC7A20_Reg_read_all(void);
 Std_ReturnType GsensorInit(void);
 
-//步骤如下:
+//姝ラ�濡備笅锛�
 //0.signed char  SL_SC7A20_BOOT(void);
 //1.signed char  SL_SC7A20_Online_Test(void);
 //2.signed char  SL_SC7A20_FS_Config(uint8 Sc7a20_FS_Reg);

+ 17 - 4
src/Hal_Fls.c → code/hal/Hal_Fls.c

@@ -1,7 +1,7 @@
 /*
  * Hal_Fls.c
  *
- *  Created on: 2022Äê4ÔÂ6ÈÕ
+ *  Created on: 2022Äê4ÔÂ6ÈÕ
  *      Author: Zhengchao
  */
 #include "Hal_Fls.h"
@@ -34,6 +34,12 @@ static tAppDownloadType gs_stAppDownloadInfo = {APP_VECTOR_TABLE_OFFSET,0,0};
         gs_stAppFlashStatus.controllerName = bControolerName;\
     }while(0u)
 
+#define SetAppConter(appCounter)\
+	{\
+		gs_stAppFlashStatus.appCnt = appCounter;\
+		}
+
+
 #define SaveAppResetHandlerAddr(resetHandlerAddr, resetHnadlerAddrLen) \
     do{\
         gs_stAppFlashStatus.appStartAddr = resetHandlerAddr;\
@@ -61,6 +67,8 @@ static tAppDownloadType gs_stAppDownloadInfo = {APP_VECTOR_TABLE_OFFSET,0,0};
 
 static void Hal_FlsSaveFingerPrint(const uint8 *i_pFingerPrint, const uint8 i_FingerPrintLen);
 
+#define InitStAppFlashStatus()  memset(&gs_stAppFlashStatus,0xFF,sizeof(gs_stAppFlashStatus))
+
 
 #define SetFlashStructStatus(bIsAppFlashStructValid) \
     do{\
@@ -157,8 +165,11 @@ void Hal_SetAppInfo(uint32 appLength, uint32 appReceviedCRC,ControllerType contr
 	SetDownloadAppLength(appLength);
 	SetDownloadAppPackCRC(appReceviedCRC);
 	SetAppUpdateControllerName(controllerName);
+	uint8 appCounter = 0;
+	SetAppConter(appCounter);
 	uint32 fingerPrint = 0x5555;
 	Hal_FlsSaveFingerPrint(&fingerPrint, 2); //save finger print
+
 }
 
 
@@ -213,7 +224,6 @@ static uint8 FlashChecksum(void)
 {
     uint32 xCountCrc = 0u;
     CRC_HAL_CreatSoftwareCrc((const uint8 *)(gs_stAppDownloadInfo.appVectoTableStartAddr + APP_FLAST_START_PHY_ADDR), gs_stAppDownloadInfo.appLength, &xCountCrc);
-
     if(gs_stAppDownloadInfo.receivedCRC == xCountCrc)
     {
     	return TRUE;
@@ -284,7 +294,7 @@ static uint8 Hal_FlsWriteFlashAppInfo(void)
 
 	if(pAppStatusPtr != NULL_PTR)
 	{
-		 flsRet = Hal_FlsWrite(appInfoStartAddr,(uint8 *)pAppStatusPtr,sizeof(tAppFlashStatus),500);
+		 flsRet = Hal_FlsWrite(appInfoStartAddr,(uint8 *)pAppStatusPtr,(sizeof(tAppFlashStatus)+7)/8*8,500);
 	}
 	if(flsRet == MEMIF_JOB_OK)
 	{
@@ -321,4 +331,7 @@ uint8 Hal_FlsCheckIsTransferSucceed(void)
 	return ret;
 }
 
-
+void Hal_OTAFlashAppInfoInit(void)
+{
+	InitStAppFlashStatus();
+}

+ 3 - 2
src/Hal_Fls.h → code/hal/Hal_Fls.h

@@ -1,7 +1,7 @@
 /*
  * Hal_Fls.h
  *
- *  Created on: 2022Äê4ÔÂ6ÈÕ
+ *  Created on: 2022Äê4ÔÂ6ÈÕ
  *      Author: Zhengchao
  */
 
@@ -36,7 +36,7 @@ typedef struct
 #define RESET_HANDLER_OFFSET    (4u)     /* From top vector table to reset handle */
 #define RESET_HANDLER_ADDR_LEN  (4u)     /* Pointer length or reset handler length */
 /* Flash finger print length */
-#define FL_FINGER_PRINT_LENGTH  (17u)
+#define FL_FINGER_PRINT_LENGTH  (14u)
 
 /* Program data buffer max length */
 #define MAX_FLASH_DATA_LEN (512u)
@@ -115,6 +115,7 @@ void Hal_SetAppInfo(uint32 appLength, uint32 appReceviedCRC,ControllerType contr
 
 uint8 Hal_FlsCheckIsTransferSucceed(void);
 
+void Hal_OTAFlashAppInfoInit(void);
 extern void CRC_HAL_CreatSoftwareCrc(const uint8_t *i_pucDataBuf, const uint32_t i_ulDataLen, uint32_t *m_pCurCrc);
 
 //extern void CreatSoftwareCrc16(const uint8 *i_pDataBuf, const uint32 i_dataLen, uint32 *m_pCurCrc);

+ 1 - 1
src/Hal_Var.c → code/hal/Hal_Var.c

@@ -1,7 +1,7 @@
 /*
  * Hal_Var.c
  *
- *  Created on: 2022Äê3ÔÂ14ÈÕ
+ *  Created on: 2022Äę3ÔÂ14Č�
  *      Author: Zhengchao
  */
 #include "Hal_Var.h"

+ 1 - 1
src/Hal_Var.h → code/hal/Hal_Var.h

@@ -1,7 +1,7 @@
 /*
  * Hal_Var.h
  *
- *  Created on: 2022Äê3ÔÂ14ÈÕ
+ *  Created on: 2022Äê3ÔÂ14ÈÕ
  *      Author: Zhengchao
  */
 

+ 0 - 0
src/Hal_Wdg.c → code/hal/Hal_Wdg.c


+ 1 - 1
src/Hal_Wdg.h → code/hal/Hal_Wdg.h

@@ -1,7 +1,7 @@
 /*
  * Hal_Wdg.h
  *
- *  Created on: 2022Äê3ÔÂ14ÈÕ
+ *  Created on: 2022Äê3ÔÂ14ÈÕ
  *      Author: Zhengchao
  */
 

+ 963 - 0
code/hal/hal_adapter.c

@@ -0,0 +1,963 @@
+/*
+ * hal_adapter.c
+ *中间层函数调用库
+ *  Created on: 2022118
+ *      Author: QiXiang_CHENJIE
+ */
+#include "hal_adapter.h"
+#include "AppGlobalVar.h"
+#include "stdio.h"
+#include "stdarg.h"
+uint8_t __attribute__((section(".non_cacheable_data"))) RX_Buffer[3][BUFFER_SIZE];
+uint32_t bufferIdx[3] = {0};
+volatile uint32 VarNotification_0 = 0;
+volatile uint32 VarNotification_1 = 0;
+TP_Value_Type ConvertedBuffer[NUM_RESULTS];
+Adc_ValueGroupType ResultBuffer[NUM_RESULTS];
+volatile Uart_StatusType Uart_TransmitStatus[3] = {UART_STATUS_TIMEOUT,UART_STATUS_TIMEOUT,UART_STATUS_TIMEOUT};
+QueueHandle_t UartRecvQueue[3];
+QueueHandle_t UartSendQueue[3];
+QueueHandle_t UartHalQueueHandle;
+Std_ReturnType UartStartRecvFunc(uint8 channel);
+Std_ReturnType ADC_Converter(Adc_ValueGroupType *Buffer, TP_Value_Type *ConvertedValueR);
+void create_ringBuffer(ringbuffer_t *ringBuf, uint8_t *buf, uint32_t buf_len);
+void clear_ringBuffer(ringbuffer_t *ringBuf);
+uint32_t write_ringBuffer(uint8_t *buffer, uint32_t size, ringbuffer_t *ringBuf);
+uint32_t read_ringBuffer(uint8_t *buffer, uint32_t size, ringbuffer_t *ringBuf);
+uint8 ringBufferforUart[3][BUFFER_SIZE];
+ringbuffer_t uartRingBuffer[3];
+sint8 AtcmdDelayRecvFunc(uint8 recvChannel,char *ResultStrPtr,uint16 delayTime)
+{
+	sint8 outValue = -1;
+	uint8 delayCnt = 0;
+	uint8 UartData[256];
+	uint16 ReadLen = 0;
+	char *retptr = NULL;
+	while (delayCnt<(delayTime/1000)&&outValue!=0)
+	{
+		UART_Receive_Data(recvChannel,UartData, &ReadLen,1000);
+		if(ReadLen>0)
+		{
+			retptr = (char *)strstr((char *)UartData, ResultStrPtr);
+			if (retptr)
+			{
+				outValue = 0;
+				break;
+			}
+		}
+		else
+		{
+			delayCnt++;
+		}
+	}
+	return outValue;
+}
+#if 0
+	uint16 myPrintf(const char *fmt, ...)
+	{
+		int n;
+		uint8 databuffer[512]={0};
+		va_list args;
+		va_start(args, fmt);
+		n = vsprintf((char *)databuffer, fmt, args);
+		va_end(args);
+	    if( (printfRingBuffer.bw + n) <= printfRingBuffer.length  )
+	    {
+	        memcpy(printfRingBuffer.source + printfRingBuffer.bw, databuffer, n);
+	        UART_Send_Data(UART_LPUART0, printfRingBuffer.source + printfRingBuffer.bw, n, 10);
+	        printfRingBuffer.bw = printfRingBuffer.bw + n;
+	    }
+	    else
+	    {
+	    	printfRingBuffer.bw = 0;
+	    	memcpy(printfRingBuffer.source + printfRingBuffer.bw, databuffer, n);
+	    	UART_Send_Data(UART_LPUART0, printfRingBuffer.source + printfRingBuffer.bw, n, 10);
+	    }
+		return n;
+	}
+#endif
+void create_ringBuffer(ringbuffer_t *ringBuf, uint8_t *buf, uint32_t buf_len)
+{
+    ringBuf->br         = 0;
+    ringBuf->bw         = 0;
+    ringBuf->btoRead    = 0;
+    ringBuf->source     = buf;
+    ringBuf->length     = buf_len;
+}
+void clear_ringBuffer(ringbuffer_t *ringBuf)
+{
+    ringBuf->br         = 0;
+    ringBuf->bw         = 0;
+    ringBuf->btoRead    = 0;
+}
+uint32_t write_ringBuffer(uint8_t *buffer, uint32_t size, ringbuffer_t *ringBuf)
+{
+    uint32_t len            = 0;
+    volatile uint32_t ringBuf_bw     = ringBuf->bw;
+    uint32_t ringBuf_len    = ringBuf->length;
+    uint8_t *ringBuf_source = ringBuf->source;
+
+    if( (ringBuf_bw + size) > ringBuf_len  )
+    {
+    	ringBuf_bw = 0;
+    }
+    memcpy(ringBuf_source + ringBuf_bw, buffer, size);
+    ringBuf->bw = (ringBuf_bw + size) % ringBuf_len;
+    ringBuf->btoRead += size;
+/*
+    if(ringBuf->br!=0)
+    {
+        memcpy(ringBuf_source, buffer, size);
+        ringBuf->br = 0;
+    }
+*/
+/*
+    if( (ringBuf_bw + size) <= ringBuf_len  )
+    {
+        memcpy(ringBuf_source + ringBuf_bw, buffer, size);
+    }
+    else
+    {
+        len = ringBuf_len - ringBuf_bw;
+        memcpy(ringBuf_source + ringBuf_bw, buffer, len);
+        memcpy(ringBuf_source, buffer + ringBuf_bw, size - len);
+    }
+    ringBuf->bw = (ringBuf->bw + size) % ringBuf_len;
+    ringBuf->btoRead += size;
+*/
+
+    return size;
+}
+uint32_t read_ringBuffer(uint8_t *buffer, uint32_t size, ringbuffer_t *ringBuf)
+{
+    uint32_t len            = 0;
+    volatile uint32_t ringBuf_br     = ringBuf->br;
+    uint32_t ringBuf_len    = ringBuf->length;
+    uint8_t *ringBuf_source = ringBuf->source;
+
+    memcpy(buffer, ringBuf_source, size);
+    ringBuf->br = size;
+//    if( (ringBuf_br + size ) <= ringBuf_len )
+//    {
+//        memcpy(buffer, ringBuf_source + ringBuf_br, size);
+//    }
+//    else
+//    {
+//        len = ringBuf_len - ringBuf_br;
+//        memcpy(buffer, ringBuf_source + ringBuf_br, len);
+//        memcpy(buffer + len, ringBuf_source, size - len);
+//    }
+//    ringBuf->br = (ringBuf->br + size) % ringBuf_len;
+//    ringBuf->btoRead -= size;
+
+    return size;
+}
+Std_ReturnType UART_Query_Data(uint8 transChannel, uint8 recvChannel, uint8 *txBuffer, uint16 sendLength, uint8 *rxBuffer, uint16 *rxlen, uint32 T_timeout)
+{
+	UartMsg_t UartRecvMsg;
+	UartMsg_t UartSendMsg;
+	BaseType_t Sendret = pdFALSE;
+	BaseType_t Recvret = pdFALSE;
+	uint32 retVal = E_NOT_OK;
+	UartSendMsg.DataLen = sendLength;
+	UartSendMsg.dataPtr = txBuffer;
+	*rxlen = 0;
+	Sendret = xQueueSend(UartSendQueue[transChannel],&UartSendMsg,50);
+	if(Sendret == pdTRUE)
+	{
+		Recvret = xQueueReceive(UartRecvQueue[recvChannel],&UartRecvMsg,T_timeout);
+		if(Recvret == pdTRUE)
+		{
+			*rxlen = UartRecvMsg.DataLen;
+	//		read_ringBuffer(rxBuffer, queueRecvSize, &uartRingBuffer[recvChannel]);
+			memcpy(rxBuffer,(uint8 *)(UartRecvMsg.dataAddr),UartRecvMsg.DataLen);
+			retVal = E_OK;
+		}
+		else
+		{
+			retVal = 3;
+		}
+	}
+	else
+	{
+		retVal = 2;
+	}
+	return retVal;
+}
+Std_ReturnType UART_Receive_Data(uint8 recvChannel, uint8 *rxBuffer, uint8 *rxlen, uint32 T_timeout)
+{
+	UartMsg_t UartRecvMsg;
+	BaseType_t ret = pdFALSE;
+	uint32 retVal = E_NOT_OK;
+	*rxlen = 0;
+	ret = xQueueReceive(UartRecvQueue[recvChannel],&UartRecvMsg,T_timeout);
+	if(ret == pdTRUE)
+	{
+		*rxlen = UartRecvMsg.DataLen;
+//		read_ringBuffer(rxBuffer, queueRecvSize, &uartRingBuffer[recvChannel]);
+		memcpy(rxBuffer,(uint8 *)UartRecvMsg.dataAddr,UartRecvMsg.DataLen);
+		retVal = E_OK;
+	}
+	return retVal;
+}
+Std_ReturnType UART_Reset(uint8 recvChannel)
+{
+	uint32 retVal = E_NOT_OK;
+	retVal = xQueueReset(UartRecvQueue[recvChannel]);
+	return retVal;
+}
+Std_ReturnType UART_Send_Data(uint8 transChannel, const uint8 *txBuffer, uint32 sendLength, uint32 T_timeout)
+{
+	UartMsg_t UartSendMsg;
+	BaseType_t ret = pdFALSE;
+	uint32 retVal = E_NOT_OK;
+	UartSendMsg.DataLen = sendLength;
+	UartSendMsg.dataPtr = txBuffer;
+	ret = xQueueSend(UartSendQueue[transChannel],&UartSendMsg,T_timeout);
+	if(ret == pdTRUE)
+	{
+		retVal = E_OK;
+	}
+	return retVal;
+}
+ void UartInit(void)
+ {
+	 create_ringBuffer(&uartRingBuffer[0],ringBufferforUart[0],sizeof(ringBufferforUart[0]));
+	 create_ringBuffer(&uartRingBuffer[1],ringBufferforUart[1],sizeof(ringBufferforUart[1]));
+	 create_ringBuffer(&uartRingBuffer[2],ringBufferforUart[2],sizeof(ringBufferforUart[2]));
+	 UartRecvQueue[0] = xQueueCreate(6, sizeof(UartMsg_t));
+	 UartRecvQueue[1] = xQueueCreate(6, sizeof(UartMsg_t));
+	 UartRecvQueue[2] = xQueueCreate(6, sizeof(UartMsg_t));
+	 UartSendQueue[0] = xQueueCreate(3, sizeof(UartMsg_t));
+	 UartSendQueue[1] = xQueueCreate(1, sizeof(UartMsg_t));
+	 UartSendQueue[2] = xQueueCreate(1, sizeof(UartMsg_t));
+	 UartHalQueueHandle = xQueueCreate(9, sizeof(UartHalMsg_t));
+
+	 xTaskCreate(Uart_Hal_RecvTask, (const char *const)"UartRecv", 256, (void *)0, main_TASK_PRIORITY + 5, NULL);
+	 xTaskCreate(Uart_Hal_SendTask, (const char *const)"UartSend", 256, (void *)0, main_TASK_PRIORITY + 4, NULL);
+ }
+ Std_ReturnType UartStartRecvFunc(uint8 channel)
+ {
+	 sint8 out = 0;
+	 volatile Std_ReturnType R_Uart_Status=E_NOT_OK;
+	 bufferIdx[channel]=0;
+	 memset(RX_Buffer[channel],0x00,BUFFER_SIZE);
+	 switch(channel)
+	 {
+		case 0:
+			IP_LPUART0->CTRL |= LPUART_CTRL_ILIE(1);
+			break;
+		case 1:
+			IP_LPUART1->CTRL |= LPUART_CTRL_ILIE(1);
+			break;
+		case 2:
+			IP_LPUART2->CTRL |= LPUART_CTRL_ILIE(1);
+			break;
+		default:
+			break;
+	 }
+	 Uart_SetBuffer(channel, RX_Buffer[channel], DMA_SIZE, UART_RECEIVE);
+	 R_Uart_Status = Uart_AsyncReceive(channel, RX_Buffer[channel], DMA_SIZE);
+	  if (E_OK != R_Uart_Status)
+	  {
+		  Uart_Abort(channel, UART_RECEIVE);
+		  out = E_NOT_OK;
+	  }
+	 return out;
+ }
+ void Uart_Hal_RecvTask(void *pvParameters)
+ {
+	 UartHalMsg_t UartHalMsgRecv;
+	 UartMsg_t UartRecvMsg;
+	 uint16 recvSize = 0;
+	 BaseType_t ret = pdFALSE;
+	 BaseType_t ret_send = pdFALSE;
+	 uint32 T_bytesRemaining[3] = {0};
+	 uint16 T_timeout[3] = {0};
+	 volatile Uart_StatusType Uart_ReceiveStatus[3] = {UART_STATUS_TIMEOUT,UART_STATUS_TIMEOUT,UART_STATUS_TIMEOUT};
+	 uint8 UartIdx = UART_LPUART0;
+	 uint8 UartState[3] = {UartAbortRecv,UartAbortRecv,UartAbortRecv};
+	 while(1)
+	 {
+		 if((T_timeout[UartIdx]>1000) && (Uart_ReceiveStatus[UartIdx] != UART_STATUS_NO_ERROR) )//判定UART停止,超时停止,不是接收状态则停止
+		 {
+			  Uart_Abort(UartIdx, UART_RECEIVE);
+			  UartState[UartIdx] = UartAbortRecv;
+			  T_timeout[UartIdx] = 0;
+		 }
+		 else if(Uart_ReceiveStatus[UartIdx] == UART_STATUS_NO_ERROR)
+		 {
+			 UartState[UartIdx] = UartRecvComplete;
+		 }
+
+		 if((UartState[UartIdx] == UartAbortRecv) || (UartState[UartIdx] == UartRecvComplete)) //判定UART开始接收:UART停止后开始接收
+		 {
+			 if(E_OK == UartStartRecvFunc(UartIdx))
+			 {
+				 UartState[UartIdx] = UartStartRecv;
+			 }
+		 }
+		 Uart_ReceiveStatus[UartIdx] = Uart_GetStatus(UartIdx, &T_bytesRemaining[UartIdx], UART_RECEIVE);
+		 T_timeout[UartIdx]++;
+		 UartIdx = (UartIdx + 1) > 2 ? 0 : (UartIdx + 1);
+		 ret = xQueueReceive(UartHalQueueHandle,&UartHalMsgRecv,1);
+		  if(ret==pdTRUE)
+		  {
+			  if(UartHalMsgRecv.event==LPUART_UART_IP_EVENT_RECV_IDLE)
+			  {
+					if(UartHalMsgRecv.value>0)
+					{
+						recvSize = write_ringBuffer(RX_Buffer[UartHalMsgRecv.Channel],UartHalMsgRecv.value,&uartRingBuffer[UartHalMsgRecv.Channel]);
+						UartRecvMsg.DataLen = UartHalMsgRecv.value;
+						UartRecvMsg.dataAddr = (uint32)(uartRingBuffer[UartHalMsgRecv.Channel].bw + uartRingBuffer[UartHalMsgRecv.Channel].source - UartHalMsgRecv.value);
+						ret_send = xQueueSend(UartRecvQueue[UartHalMsgRecv.Channel],&UartRecvMsg,10);
+					}
+					T_timeout[UartHalMsgRecv.Channel] = 0;
+					UartState[UartHalMsgRecv.Channel] = UartRecvComplete;
+			  }
+		  }
+	 }
+ }
+ void Uart_Hal_SendTask(void *pvParameters)
+ {
+	 UartMsg_t UartSendMsg;
+	 BaseType_t ret = pdFALSE;
+	 uint32 T_bytesRemaining[3] = {0};
+	 uint16 T_timeout[3] = {0};
+	 volatile Std_ReturnType T_Uart_Status[3];
+	 uint8 UartIdx = UART_LPUART0;
+	 uint8 UartSendState[3] = {UartNoDataSend,UartNoDataSend,UartNoDataSend};
+	 while(1)
+	 {
+		 ret = xQueueReceive(UartSendQueue[UartIdx],&UartSendMsg,1);
+		 if(ret==pdTRUE)
+		 {
+			 if(UartIdx==UART_LPUART0)
+			 {
+				 Dio_WriteChannel(DioConf_DioChannel_PTB4_GPIO_OUT_MCU_RS485_EN, STD_ON);
+			 }
+			 T_Uart_Status[UartIdx] = Uart_AsyncSend(UartIdx, UartSendMsg.dataPtr, UartSendMsg.DataLen);
+		     if (E_OK != T_Uart_Status[UartIdx])
+		     {
+		         Uart_Abort(UartIdx, UART_SEND);
+		         UartSendState[UartIdx] = UartAbortSend;
+		     }
+		     else
+		     {
+		    	 UartSendState[UartIdx] = UartStartSend;
+		     }
+		 }
+		 /*开始发送后的判定*/
+		 if(UartSendState[UartIdx] == UartStartSend)
+		 {
+			 Uart_TransmitStatus[UartIdx] = Uart_GetStatus(UartIdx, &T_bytesRemaining[UartIdx], UART_SEND);
+			 T_timeout[UartIdx]++;
+		 }
+		 if(T_timeout[UartIdx]>=1000 || ((Uart_TransmitStatus[UartIdx] != UART_STATUS_OPERATION_ONGOING) && (UartSendState[UartIdx] == UartStartSend)))
+		 {
+			 if(T_timeout[UartIdx]>=1000)
+			 {
+				 Uart_Abort(UartIdx, UART_SEND);
+				 UartSendState[UartIdx] = UartAbortSend;
+			 }
+			 else if(Uart_TransmitStatus[UartIdx] == UART_STATUS_NO_ERROR)
+			 {
+				 UartSendState[UartIdx] = UartSendComplete;
+			 }
+			 T_timeout[UartIdx] = 0;
+		 }
+
+		 UartIdx = (UartIdx + 1) > 2 ? 0 : (UartIdx + 1);
+	 }
+
+ }
+//
+//Std_ReturnType UART_Query_Data(uint8 transChannel, uint8 recvChannel, const uint8 *txBuffer, uint32 sendLength, uint8 *rxBuffer, uint16 *rxlen, uint32 T_timeout)
+//{
+//    volatile Std_ReturnType R_Uart_Status;
+//    volatile Std_ReturnType T_Uart_Status;
+//    volatile Uart_StatusType Uart_ReceiveStatus = UART_STATUS_TIMEOUT;
+//    volatile Uart_StatusType Uart_TransmitStatus = UART_STATUS_TIMEOUT;
+//    uint32 T_bytesRemaining;
+//    uint32 R_bytesRemaining;
+//    uint32 timeout = T_timeout;
+//    uint32 retVal = E_NOT_OK;
+//    bufferIdx[recvChannel] = 0;
+//    switch (recvChannel)
+//    {
+//    case 0:
+//        IP_LPUART0->CTRL |= LPUART_CTRL_ILIE(1);
+//        break;
+//    case 1:
+//        IP_LPUART1->CTRL |= LPUART_CTRL_ILIE(1);
+//        break;
+//    case 2:
+//        IP_LPUART2->CTRL |= LPUART_CTRL_ILIE(1);
+//        break;
+//    default:
+//        break;
+//    }
+//    if (txBuffer == NULL || rxBuffer == NULL)
+//    {
+//        return retVal;
+//    }
+//
+//    /* Uart_AsyncSend transmit data */
+//    Uart_SetBuffer(transChannel, txBuffer, sendLength, UART_SEND);
+//    T_Uart_Status = Uart_AsyncSend(transChannel, txBuffer, sendLength);
+//    if (E_OK != T_Uart_Status)
+//    {
+//        Uart_Abort(transChannel, UART_SEND);
+//        return E_NOT_OK;
+//    }
+//    Uart_SetBuffer(recvChannel, &RX_Buffer[recvChannel][0], DMA_SIZE, UART_RECEIVE);
+//    R_Uart_Status = Uart_AsyncReceive(recvChannel, rxBuffer, DMA_SIZE);
+//    if (E_OK != R_Uart_Status)
+//    {
+//        Uart_Abort(recvChannel, UART_RECEIVE);
+//        return E_NOT_OK;
+//    }
+//    /* Check for no on-going transmission */
+//    do
+//    {
+//        if (Uart_TransmitStatus != UART_STATUS_NO_ERROR)
+//        {
+//            Uart_TransmitStatus = Uart_GetStatus(transChannel, &T_bytesRemaining, UART_SEND);
+//        }
+//        if (Uart_ReceiveStatus != UART_STATUS_NO_ERROR)
+//        {
+//            Uart_ReceiveStatus = Uart_GetStatus(recvChannel, &R_bytesRemaining, UART_RECEIVE);
+//        }
+//        vTaskDelay(pdMS_TO_TICKS(1));
+//    } while (((UART_STATUS_NO_ERROR != Uart_TransmitStatus || UART_STATUS_NO_ERROR != Uart_ReceiveStatus) && 0 < --timeout));
+//    if ((UART_STATUS_NO_ERROR != Uart_TransmitStatus))
+//    {
+//        Uart_Abort(transChannel, UART_SEND);
+//        retVal = E_NOT_OK;
+//    }
+//    else
+//    {
+//        retVal = E_OK;
+//    }
+//    if ((UART_STATUS_NO_ERROR != Uart_ReceiveStatus))
+//    {
+//        Uart_Abort(recvChannel, UART_RECEIVE);
+//        *rxlen = bufferIdx[recvChannel];
+//        retVal = E_NOT_OK;
+//    }
+//    else
+//    {
+//        *rxlen = bufferIdx[recvChannel];
+//        retVal = E_OK;
+//    }
+//    return retVal;
+//}
+//
+//Std_ReturnType UART_Send_Data(uint8 transChannel, const uint8 *txBuffer, uint32 sendLength, uint32 T_timeout)
+//{
+//
+//    volatile Std_ReturnType T_Uart_Status;
+//    volatile Uart_StatusType Uart_TransmitStatus = UART_STATUS_TIMEOUT;
+//    uint32 T_bytesRemaining;
+//    uint32 timeout = T_timeout;
+//    uint32 retVal = E_NOT_OK;
+//    if (txBuffer == NULL)
+//    {
+//        return retVal;
+//    }
+//
+//    /* Uart_AsyncSend transmit data */
+//    T_Uart_Status = Uart_AsyncSend(transChannel, txBuffer, sendLength);
+//    if (E_OK != T_Uart_Status)
+//    {
+//        Uart_Abort(transChannel, UART_SEND);
+//        return E_NOT_OK;
+//    }
+//    /* Check for no on-going transmission */
+//    do
+//    {
+//        Uart_TransmitStatus = Uart_GetStatus(transChannel, &T_bytesRemaining, UART_SEND);
+//        vTaskDelay(pdMS_TO_TICKS(1));
+//    } while ((UART_STATUS_NO_ERROR != Uart_TransmitStatus && 0 < --timeout));
+//
+//    if ((UART_STATUS_NO_ERROR != Uart_TransmitStatus))
+//    {
+//        retVal = E_NOT_OK;
+//    }
+//    else
+//    {
+//        retVal = E_OK;
+//    }
+//    return retVal;
+//}
+//
+//Std_ReturnType UART_Receive_Data(uint8 recvChannel, uint8 *rxBuffer, uint16 *rxlen, sint32 T_timeout)
+//{
+//    volatile Std_ReturnType R_Uart_Status = E_NOT_OK;
+//    volatile Uart_StatusType Uart_ReceiveStatus = UART_STATUS_TIMEOUT;
+//    uint32 T_bytesRemaining = 0;
+//    uint32 retVal = E_NOT_OK;
+//    //    uint8 Rx_Buffer[MSG_LEN];
+//    bufferIdx[recvChannel] = 0;
+//    *rxlen = 0;
+//    if (rxBuffer == NULL)
+//    {
+//        return retVal;
+//    }
+//    /* Uart_AsyncReceive transmit data */
+//    switch (recvChannel)
+//    {
+//    case 0:
+//        IP_LPUART0->CTRL |= LPUART_CTRL_ILIE(1);
+//        break;
+//    case 1:
+//        IP_LPUART1->CTRL |= LPUART_CTRL_ILIE(1);
+//        break;
+//    case 2:
+//        IP_LPUART2->CTRL |= LPUART_CTRL_ILIE(1);
+//        break;
+//    default:
+//        break;
+//    }
+//    Uart_SetBuffer(recvChannel, rxBuffer, DMA_SIZE, UART_RECEIVE);
+//    R_Uart_Status = Uart_AsyncReceive(recvChannel, rxBuffer, DMA_SIZE);
+//    if (E_OK != R_Uart_Status)
+//    {
+//        Uart_Abort(recvChannel, UART_RECEIVE);
+//        return E_NOT_OK;
+//    }
+//    /* Check for no on-going transmission */
+//    do
+//    {
+//        Uart_ReceiveStatus = Uart_GetStatus(recvChannel, &T_bytesRemaining, UART_RECEIVE);
+//        vTaskDelay(pdMS_TO_TICKS(1));
+//
+//    } while ((UART_STATUS_NO_ERROR != Uart_ReceiveStatus) && 0 < T_timeout--);
+//    if ((UART_STATUS_NO_ERROR != Uart_ReceiveStatus))
+//    {
+//        Uart_Abort(recvChannel, UART_RECEIVE);
+//        *rxlen = bufferIdx[recvChannel];
+//        retVal = E_NOT_OK;
+//    }
+//    else
+//    {
+//        *rxlen = bufferIdx[recvChannel];
+//        retVal = E_OK;
+//    }
+//    return retVal;
+//}
+extern Lpuart_Uart_Ip_StateStructureType *Lpuart_Uart_Ip_apStateStructuresArray[LPUART_UART_IP_NUMBER_OF_INSTANCES];
+void UART_Callback(uint32 hwInstance, Lpuart_Uart_Ip_EventType event)
+{
+    //    (void)userData;
+		Lpuart_Uart_Ip_StateStructureType * UartState;
+		UartState = (Lpuart_Uart_Ip_StateStructureType *)Lpuart_Uart_Ip_apStateStructuresArray[hwInstance];
+	if (hwInstance==0&&event == LPUART_UART_IP_EVENT_END_TRANSFER)
+	{
+		Dio_WriteChannel(DioConf_DioChannel_PTB4_GPIO_OUT_MCU_RS485_EN, STD_OFF);
+	}
+    /* Check the event type */
+    if (event == LPUART_UART_IP_EVENT_RX_FULL)
+    {
+        /* The reception stops when receiving idle is detected or the buffer is full */
+        if (bufferIdx[hwInstance] <= (BUFFER_SIZE - DMA_SIZE))
+        {
+            /* Update the buffer index and the rx buffer */
+            bufferIdx[hwInstance] += DMA_SIZE;
+            Uart_SetBuffer(hwInstance, &RX_Buffer[hwInstance][bufferIdx[hwInstance]], DMA_SIZE, UART_RECEIVE);
+            // Lpuart_Uart_Ip_SetRxBuffer(hwInstance, &RX_Buffer[bufferIdx], DMA_SIZE);
+        }
+    }
+    if (event == LPUART_UART_IP_EVENT_ERROR)
+    {
+        //     	/*Get the transfered data size. DMA Channel 1 is used for LPUART DMA receiving, please modify accordingly.*/
+        //     	temp = DMA_SIZE - (uint32_t)IP_DMA->TCD->CITER.ELINKNO;
+        //     	/*Add the remaining data size to the sum of the received size*/
+        //     	bufferIdx[hwInstance] += temp;
+        /*Abort the receiving after detecting IDLE receiving*/
+        Lpuart_Uart_Ip_AbortReceivingData(hwInstance);
+        Lpuart_Uart_Ip_AbortSendingData(hwInstance);
+        //    	bufferIdx = 0;
+    }
+    if (event == LPUART_UART_IP_EVENT_RECV_IDLE)
+    {
+         uint32_t temp;
+         UartHalMsg_t UartHalMsg;
+         UartHalMsg.Channel = hwInstance;
+         UartHalMsg.event = event;
+        /*Get the transfered data size. DMA Channel 1 is used for LPUART DMA receiving, please modify accordingly.*/
+        temp = DMA_SIZE - (uint32_t)IP_DMA->TCD[hwInstance].CITER.ELINKNO;
+        /*Add the remaining data size to the sum of the received size*/
+        bufferIdx[hwInstance] += temp;
+        /*Abort the receiving after detecting IDLE receiving*/
+ 		UartHalMsg.value = bufferIdx[hwInstance];
+ 		xQueueSendFromISR(UartHalQueueHandle,&UartHalMsg,pdFALSE);
+    }
+}
+
+/*CAN*/
+Can_PduType Can_CreatePduInfo(Can_IdType id, CAN_IdFrameType idFrame, PduIdType swPduHandle, uint8 length, uint8 *sdu)
+{
+    Can_PduType PduInfo;
+    switch (idFrame)
+    {
+    case CAN_STANDARD_ID_TYPE:
+        id = id & 0x7FF;
+        break;
+    case CANFD_STANDARD_ID_TYPE:
+        id = (id & 0x7FF) | 0x40000000;
+        break;
+    case CAN_EXTENDED_ID_TYPE:
+        id = id | 0x80000000;
+        break;
+    case CANFD_EXTENDED_ID_TYPE:
+        id = id | 0xC0000000;
+        break;
+    default:
+        id = id & 0x7FF;
+        break;
+    }
+    PduInfo.id = id;
+    PduInfo.swPduHandle = swPduHandle;
+    PduInfo.length = length;
+    PduInfo.sdu = sdu;
+    return PduInfo;
+}
+Std_ReturnType CanIf_SendMessage(uint8 ControllerId, Can_Msg_Type CanMsg)
+{
+    volatile Can_PduType Can_PduInfo;
+    volatile Std_ReturnType CAN_Write_Status;
+    Std_ReturnType retVal = E_NOT_OK;
+    uint32 u8TimeOut = 100 * 100;
+    Can_HwHandleType Hth = Can0HardwareObject_TX + (Can_HwHandleType)ControllerId; // controller 0 --> Can0HardwareObject_TX
+
+    Can_PduInfo = Can_CreatePduInfo(CanMsg.id, CanMsg.idFrame, 0, CanMsg.length, CanMsg.sdu);
+
+    CAN_Write_Status = Can_Write(Hth, &Can_PduInfo);
+
+    CanIf_bTxFlag = FALSE;
+    if (CAN_Write_Status == E_OK)
+    {
+        while ((!CanIf_bTxFlag) && (u8TimeOut != 0U))
+        {
+            Can_MainFunction_Write();
+            u8TimeOut--;
+        }
+    }
+
+    if (CanIf_bTxFlag == TRUE)
+    {
+        retVal = E_OK;
+    }
+    else
+    {
+        retVal = E_NOT_OK;
+    }
+    return retVal;
+}
+Can_Msg_Type Can_GetMsgInfo(Can_IdType id, uint8 length, uint8 *sdu)
+{
+    Can_Msg_Type CanMsgInfo;
+
+    CanMsgInfo.idFrame = (CAN_IdFrameType)((id >> 30) & 0x03);
+    if (CanMsgInfo.idFrame & 0x01)
+    {
+        CanMsgInfo.id = id & 0x7FF;
+    }
+    else
+    {
+        CanMsgInfo.id = id & 0x1FFFFFFF;
+    }
+    CanMsgInfo.length = length;
+    CanMsgInfo.sdu = sdu;
+
+    return CanMsgInfo;
+}
+
+void CanIf_ControllerBusOff(uint8 ControllerId)
+{
+    (void)ControllerId;
+}
+
+void CanIf_ControllerModeIndication(uint8 ControllerId, Can_ControllerStateType ControllerMode)
+{
+    (void)ControllerId;
+    (void)ControllerMode;
+}
+void CanIf_TxConfirmation(PduIdType CanTxPduId)
+{
+    CanIf_u8TxConfirmCnt++;
+    CanIf_bTxFlag = TRUE;
+    (void)CanTxPduId;
+}
+void CanIf_RxIndication(const Can_HwType *Mailbox, const PduInfoType *PduInfoPtr)
+{
+    Can_Msg_Type canRxMsg_Buff;
+    Can_Msg_Type_Data canRxMsgQueueData;
+    CanIf_bRxFlag = TRUE; // should not be delete
+    // should put the msg into message queue
+    canRxMsg_Buff = Can_GetMsgInfo(Mailbox->CanId, PduInfoPtr->SduLength, PduInfoPtr->SduDataPtr);
+    canRxMsgQueueData.id = canRxMsg_Buff.id;
+    canRxMsgQueueData.length = canRxMsg_Buff.length;
+    memcpy(canRxMsgQueueData.data, canRxMsg_Buff.sdu, canRxMsgQueueData.length);
+    xQueueSend(CanRecvQueueHandle, &canRxMsgQueueData, 0);
+}
+
+void CanIf_CurrentIcomConfiguration(uint8 ControllerId, IcomConfigIdType ConfigurationId, IcomSwitch_ErrorType Error)
+{
+    (void)ControllerId;
+    (void)ConfigurationId;
+    (void)Error;
+}
+
+void Notification_0(void)
+{
+    ADC_Converter(ResultBuffer, ConvertedBuffer);
+    memcpy(BattTempR, &ConvertedBuffer[3], 4 * sizeof(uint32));
+}
+
+void Notification_1(void)
+{
+    VarNotification_1++;
+}
+
+Std_ReturnType ADC_Converter(Adc_ValueGroupType *Buffer, TP_Value_Type *ConvertedValueR)
+{
+    Adc_ValueGroupType REFH, REFL;
+    REFH = Buffer[0];
+    REFL = Buffer[2];
+    for (int i = 3; i < NUM_RESULTS; i++)
+    {
+        if (Buffer[i] >= REFH)
+        {
+            ConvertedValueR[i] = 40930000;
+        }
+        else if (Buffer[i] <= REFL)
+        {
+            ConvertedValueR[i] = 0x00;
+        }
+        else
+        {
+            ConvertedValueR[i] = (TP_Value_Type)((float)(10000 * (Buffer[i] - REFL) / (float)(REFH - REFL)) / (1 - (float)((Buffer[i] - REFL) / (float)(REFH - REFL))));
+        }
+    }
+    return 0;
+}
+
+Std_ReturnType ADC_ReadValue()
+{
+    Std_ReturnType ret = E_NOT_OK;
+    for (uint8 i = 0; i < NUM_RESULTS; i++)
+    {
+        ResultBuffer[i] = 0xFFFF;
+        ConvertedBuffer[i] = 0x00;
+    }
+    Adc_SetupResultBuffer(AdcGroupSoftwareOneShot, ResultBuffer);
+    Adc_EnableGroupNotification(AdcGroupSoftwareOneShot);
+    VarNotification_0 = 0;
+    Adc_StartGroupConversion(AdcGroupSoftwareOneShot);
+    return ret;
+}
+
+/*EEP*/
+static Std_ReturnType TestEep_FlexNvmProgramPartCmd(
+    VAR(TestEep_CsecKeySize, AUTOMATIC) eepKeysize,
+    VAR(TestEep_SfeType, AUTOMATIC) eepSecurityFlagExtension,
+    VAR(TestEep_LoadFlexRamType, AUTOMATIC) eepLoadFlexRamAtReset,
+    VAR(TestEep_Eeprom_FlexRamPartitionType, AUTOMATIC) eepFlexRamPartition,
+    VAR(TestEep_Eeprom_FlexNvmPartitionType, AUTOMATIC) eepFlexNvmPartition)
+{
+    Std_ReturnType u8RetVal = (Std_ReturnType)E_OK;
+    uint32 u32FlexNvmPartSize = 0;
+
+    uint32 u32RegSimFcfg1 = 0UL;
+
+    u32RegSimFcfg1 = IP_SIM->FCFG1;
+
+    /*get DEPART value */
+    u32FlexNvmPartSize = (uint32)((u32RegSimFcfg1 & SIM_FCFG1_DEPART_MASK) >> SIM_FCFG1_DEPART_SHIFT);
+
+    /* check that it was not partitioned before */
+    if (u32FlexNvmPartSize == 0xF)
+    {
+        //         /* if error flags are set the cmd is not executed */
+        //         REG_WRITE8(TEST_EEP_EEPROM_FSTAT_ADDR32, TEST_EEP_EEPROM_FSTAT_ACCERR_U8 | TEST_EEP_EEPROM_FSTAT_FPVIOL_U8);
+        //
+        //         /*erase DF 0 sector*/
+        //         u32Addr=(TEST_EEP_DEEPROM_SECTOR_0_ADDR32 - D_EEPROM_BASE_ADDR) + 0x800000UL;
+        //
+        //         REG_WRITE8(TEST_EEP_EEPROM_FCCOB0_ADDR32, TEST_EEP_EEPROM_CMD_ERASE_SECTOR);
+        //         REG_WRITE8(TEST_EEP_EEPROM_FCCOB1_ADDR32, (uint8)(u32Addr >> 16UL));
+        //         REG_WRITE8(TEST_EEP_EEPROM_FCCOB2_ADDR32, (uint8)(u32Addr >> 8UL));
+        //         REG_WRITE8(TEST_EEP_EEPROM_FCCOB3_ADDR32, (uint8)(u32Addr >> 0UL));
+        //         REG_WRITE8(TEST_EEP_EEPROM_FSTAT_ADDR32 , TEST_EEP_EEPROM_FSTAT_CCIF_U8);
+        //         while((0U == REG_BIT_GET8(TEST_EEP_EEPROM_FSTAT_ADDR32, TEST_EEP_EEPROM_FSTAT_CCIF_U8)))
+        //         {
+        //         }
+        //
+        if (0U == REG_BIT_GET8(TEST_EEP_EEPROM_FSTAT_ADDR32, TEST_EEP_EEPROM_FSTAT_ACCERR_U8 | TEST_EEP_EEPROM_FSTAT_FPVIOL_U8))
+        {
+            /* run program partition command */
+            REG_WRITE8(TEST_EEP_EEPROM_FCCOB0_ADDR32, EEPROM_CMD_PROGRAM_PARTITION);
+            REG_WRITE8(TEST_EEP_EEPROM_FCCOB1_ADDR32, (uint8)eepKeysize);
+            REG_WRITE8(TEST_EEP_EEPROM_FCCOB2_ADDR32, (uint8)eepSecurityFlagExtension);
+            REG_WRITE8(TEST_EEP_EEPROM_FCCOB3_ADDR32, (uint8)eepLoadFlexRamAtReset);
+            REG_WRITE8(TEST_EEP_EEPROM_FCCOB4_ADDR32, (uint8)eepFlexRamPartition);
+            REG_WRITE8(TEST_EEP_EEPROM_FCCOB5_ADDR32, (uint8)eepFlexNvmPartition);
+            REG_WRITE8(TEST_EEP_EEPROM_FSTAT_ADDR32, TEST_EEP_EEPROM_FSTAT_CCIF_U8);
+            while ((0U == REG_BIT_GET8(TEST_EEP_EEPROM_FSTAT_ADDR32, TEST_EEP_EEPROM_FSTAT_CCIF_U8)))
+            {
+                /* wait for operation to finish */
+            }
+            /* check if errors occured  */
+            if (REG_BIT_GET8(TEST_EEP_EEPROM_FSTAT_ADDR32, TEST_EEP_EEPROM_FSTAT_ACCERR_U8 | TEST_EEP_EEPROM_FSTAT_FPVIOL_U8))
+            {
+                /* NOK, error flags are set */
+                u8RetVal = (Std_ReturnType)E_NOT_OK;
+            }
+        }
+        else
+        {
+            /* NOK, error flags are set */
+            u8RetVal = (Std_ReturnType)E_NOT_OK;
+        }
+    }
+    else
+    {
+        /* NOK, partitioned already */
+        u8RetVal = (Std_ReturnType)E_NOT_OK;
+    }
+    return u8RetVal;
+}
+
+void Eep_DepartParitition(TestEep_Eeprom_FlexNvmPartitionType T_EEP_SIZE)
+{
+    uint32 u32FlexNvmPartSize = 0;
+
+    uint32 u32RegSimFcfg1 = 0UL;
+
+    u32RegSimFcfg1 = IP_SIM->FCFG1;
+
+    /*get DEPART value */
+    u32FlexNvmPartSize = (uint32)((u32RegSimFcfg1 & SIM_FCFG1_DEPART_MASK) >> SIM_FCFG1_DEPART_SHIFT);
+    if (u32FlexNvmPartSize == 0xF) /* We just partition again if curent size different with expected */
+    {
+        /* partition for EERAM 64K with NOT loading EERAM at reset in hardware */
+        TestEep_FlexNvmProgramPartCmd(EEP_FTFC_KEY_SIZE_0_BYTES, EEP_FTFC_VERIFY_ONLY_DISABLED,
+                                      EEP_FTFC_LOAD_AT_RESET_ENABLED, EEP_FTFC_EERAM_SIZE_4K, T_EEP_SIZE);
+    }
+}
+/* Erase memory by writing erase value */
+Std_ReturnType HAL_EEP_Erase(uint32 eepEraseStartAddr, uint32 eepEraseSize)
+{
+    Std_ReturnType retReturnType = E_OK;
+    MemIf_JobResultType retJobResultType;
+    retReturnType = Eep_Erase(eepEraseStartAddr, eepEraseSize);
+    if (E_OK != retReturnType)
+    {
+        return E_NOT_OK;
+    }
+    while (MEMIF_IDLE != Eep_GetStatus())
+    {
+        Eep_MainFunction();
+    }
+    retJobResultType = Eep_GetJobResult();
+    if (MEMIF_JOB_OK != retJobResultType)
+    {
+        return E_NOT_OK;
+    }
+    return E_OK;
+}
+
+/* Write one or more complete eeprom pages to the eeprom device */
+Std_ReturnType HAL_EEP_Write(uint32 eepWriteStartAddr, uint8 *pDataNeedtoWrite, uint32 dataSize)
+{
+    Std_ReturnType retReturnType = E_OK;
+    MemIf_JobResultType retJobResultType;
+
+    /*Erase the EEP before write*/
+    retReturnType = HAL_EEP_Erase(eepWriteStartAddr, dataSize);
+    if (E_OK != retReturnType)
+    {
+        return E_NOT_OK;
+    }
+
+    retReturnType = Eep_Write(eepWriteStartAddr, pDataNeedtoWrite, dataSize);
+    if (E_OK != retReturnType)
+    {
+        return E_NOT_OK;
+    }
+    while (MEMIF_IDLE != Eep_GetStatus())
+    {
+        Eep_MainFunction();
+    }
+    retJobResultType = Eep_GetJobResult();
+    if (MEMIF_JOB_OK != retJobResultType)
+    {
+        return E_NOT_OK;
+    }
+    return E_OK;
+}
+
+/* Reads from eeprom memory */
+Std_ReturnType HAL_EEP_Read(uint32 eepReadStartAddr, uint8 *pDataBuffer, uint32 dataSize)
+{
+    Std_ReturnType retReturnType = E_OK;
+    MemIf_JobResultType retJobResultType;
+    retReturnType = Eep_Read(eepReadStartAddr, pDataBuffer, dataSize);
+    if (E_OK != retReturnType)
+    {
+        return E_NOT_OK;
+    }
+    while (MEMIF_IDLE != Eep_GetStatus())
+    {
+        Eep_MainFunction();
+    }
+    retJobResultType = Eep_GetJobResult();
+    if (MEMIF_JOB_OK != retJobResultType)
+    {
+        return E_NOT_OK;
+    }
+    return E_OK;
+}
+
+/* Compares a eeprom memory area with an application data buffer */
+Std_ReturnType HAL_EEP_Compare(uint32 eepCompareStartAddr, uint8 *pDataNeedtoCompare, uint32 dataSize)
+{
+    Std_ReturnType retReturnType = E_OK;
+    MemIf_JobResultType retJobResultType;
+    retReturnType = Eep_Compare(eepCompareStartAddr, pDataNeedtoCompare, dataSize);
+    if (E_OK != retReturnType)
+    {
+        return E_NOT_OK;
+    }
+    while (MEMIF_IDLE != Eep_GetStatus())
+    {
+        Eep_MainFunction();
+    }
+    retJobResultType = Eep_GetJobResult();
+    if (MEMIF_JOB_OK != retJobResultType)
+    {
+        return E_NOT_OK;
+    }
+    return E_OK;
+}
+/* @brief VECTKEY value so that AIRCR register write is not ignored. */
+#define FEATURE_SCB_VECTKEY               (0x05FAU)
+void SystemSoftwareReset(void)
+{
+    uint32_t regValue;
+
+    /* Read Application Interrupt and Reset Control Register */
+    regValue = S32_SCB->AIRCR;
+
+    /* Clear register key */
+    regValue &= ~( S32_SCB_AIRCR_VECTKEY_MASK);
+
+    /* Configure System reset request bit and Register Key */
+    regValue |= S32_SCB_AIRCR_VECTKEY(FEATURE_SCB_VECTKEY);
+    regValue |= S32_SCB_AIRCR_SYSRESETREQ(0x1u);
+
+    /* Write computed register value */
+    S32_SCB->AIRCR = regValue;
+}

+ 250 - 0
code/hal/hal_adapter.h

@@ -0,0 +1,250 @@
+/*
+ * @Author       : ChenJie
+ * @Date         : 2022-01-23 13:52:10
+ * @Version      : V3.0
+ * @LastEditors  : ChenJie
+ * @LastEditTime : 2022-05-17 16:22:16
+ * @Description  : file content
+ * @FilePath     : \S32K146_4G\src\hal_adapter.h
+ */
+/*
+ * hal_adapter.h
+ *中间层函数调用库
+ *  Created on: 2022年1月18日
+ *      Author: QiXiang_CHENJIE
+ */
+
+#ifndef HAL_ADAPTER_H_
+#define HAL_ADAPTER_H_
+#include "Mcal.h"
+#include "CAN.h"
+#include "SchM_Can.h"
+#include "Mcu.h"
+#include "Mcl.h"
+#include "Port.h"
+#include "Dio.h"
+#include "Uart.h"
+#include "Platform.h"
+#include "Lpuart_Uart_Ip_Irq.h"
+#include "Flexio_Uart_Ip_Irq.h"
+#include <string.h>
+#include <stdlib.h>
+#include "Dma_Ip.h"
+#include "Dma_Ip_Irq.h"
+#include "Lpuart_Uart_Ip.h"
+#include "FreeRTOS.h"
+#include "timers.h"
+#include "task.h"
+#include "semphr.h"
+#include "Adc.h"
+#include "Eep.h"
+#include "Fls.h"
+#include "SchM_Fls.h"
+#include "SL_Sc7a20_Driver.h"
+#include "SEGGER_RTT_Conf.h"
+#include "SEGGER_RTT.h"
+/*适应性定义*/
+typedef unsigned char UINT8;
+typedef unsigned short UINT16;
+typedef unsigned long UINT32;
+typedef unsigned char BOOL;
+typedef signed char INT8;
+typedef signed short INT16;
+typedef signed long INT32;
+
+#define CAN0 0
+#define CAN1 1
+#ifndef min
+#define min(A, B) ((A) <= (B) ? (A) : (B))
+#endif
+#ifndef max
+#define max(A, B) ((A) < (B) ? (B) : (A))
+#endif
+#define getbit(x, y) ((x) >> (y)&1) //获取x的第y位的数值
+#define setbit(x, y) x |= (1 << y)  // x的第y位置1
+#define clrbit(x, y) x &= ~(1 << y) // x的第y位置0
+#define UART_LPUART0 0
+#define UART_LPUART1 1
+#define UART_LPUART2 2
+#define FLEXIO_RX 3
+#define FLEXIO_TX 4
+#define main_TASK_PRIORITY (tskIDLE_PRIORITY + 7)
+
+#define MSG_LEN 50U
+#define TJA1153_START_ID (uint32_t)(0x555u)
+#define TJA1153_CONFIG_ID (uint32_t)(0x18DA00F1u)
+#define NUM_RESULTS ADC_CFGSET_VS_0_GROUP_0_CHANNELS
+#define BUFFER_SIZE 1024
+#define DMA_SIZE 128
+void Uart_Hal_RecvTask(void *pvParameters);
+void Uart_Hal_SendTask(void *pvParameters);
+typedef struct {
+    uint8_t *source;
+    uint32_t br;
+    uint32_t bw;
+    uint32_t btoRead;
+    uint32_t length;
+}ringbuffer_t;
+
+ typedef struct
+ {
+     uint16 DataLen;
+     uint8 *dataPtr;
+     uint32 dataAddr;
+ } UartMsg_t;
+ typedef struct
+ {
+	 uint8 Channel;
+	 Lpuart_Uart_Ip_EventType event;
+     uint16  value;
+ } UartHalMsg_t;
+ typedef enum
+ {
+	 UartStartRecv = 0,
+	 UartAbortRecv,
+	 UartRecvOnGoing,
+	 UartRecvComplete,
+
+	 UartStartSend,
+	 UartAbortSend,
+	 UartSendOnGoing,
+	 UartSendComplete,
+	 UartNoDataSend,
+ };
+ typedef enum
+ {
+	 SystemTPChannel = 0,
+	 SlowChargeTPChannel,
+	 QuickChargeTPChannel,
+	 CC1TPChannel,
+	 ChannelCounter = 4,
+ }ADC_TP_Channel_Type;
+
+typedef uint32 TP_Value_Type;
+/*CAN*/
+typedef enum
+{
+    CAN_STANDARD_ID_TYPE = 0x00,   /**< * -00b CAN message with Standard CAN ID  */
+    CANFD_STANDARD_ID_TYPE = 0x01, /**< * -01b CAN FD frame with Standard CAN ID  */
+    CAN_EXTENDED_ID_TYPE = 0x02,   /**< * -10b CAN message with Extended CAN ID  */
+    CANFD_EXTENDED_ID_TYPE = 0x03, /**< * -11b CAN FD frame with Extended CAN ID  */
+} CAN_IdFrameType;
+
+typedef struct
+{
+    Can_IdType id;
+
+    CAN_IdFrameType idFrame;
+
+    uint8 length; /**< @brief DLC = Data Length Code (part of L-PDU that describes
+                                            the SDU length). */
+    uint8 *sdu;   /**< @brief CAN L-SDU = Link Layer Service Data
+                                                           Unit. Data that is transported inside
+                                                           the L-PDU. */
+} Can_Msg_Type;
+typedef struct
+{
+    Can_IdType id;
+    uint8 length;
+    uint8 data[8];
+} Can_Msg_Type_Data;
+/*EEP*/
+
+typedef enum
+{
+    EEP_FTFC_KEY_SIZE_0_BYTES = 0x0,   /**< @brief control code for key size 0 bytes, used for the partitioning command */
+    EEP_FTFC_KEY_SIZE_128_BYTES = 0x1, /**< @brief control code for key size 128 bytes, used for the partitioning command */
+    EEP_FTFC_KEY_SIZE_256_BYTES = 0x2, /**< @brief control code for key size 256 bytes, used for the partitioning command */
+    EEP_FTFC_KEY_SIZE_512_BYTES = 0x3  /**< @brief control code for key size 512 bytes, used for the partitioning command */
+} TestEep_CsecKeySize;
+
+/**
+    @brief FlexRamPartition Type used for the partitioning command
+*/
+typedef enum
+{
+    EEP_FTFC_EERAM_SIZE_0K = 0xF, /**< @brief control code for flexram partitioned as sram, used for the partitioning command */
+    EEP_FTFC_EERAM_SIZE_4K = 0x2, /**< @brief control code for flexram partitioned as eeram, used for the partitioning command */
+    EEP_FTFC_EERAM_SIZE_2K = 0x3  /**< @brief control code for flexram partitioned as eeram, used for the partitioning command */
+} TestEep_Eeprom_FlexRamPartitionType;
+
+/**
+    @brief FlexNvmPartition Type used for the partitioning command
+*/
+typedef enum
+{
+    EEP_FTFC_EEEPROM_SIZE_0K_V1 = 0x0,  /**< @brief control code to partition EEPROM backup size as 0K, used for the partitioning command */
+    EEP_FTFC_EEEPROM_SIZE_0K_V2 = 0xC,  /**< @brief control code to partition EEPROM backup size as 0K, used for the partitioning command */
+    EEP_FTFC_EEEPROM_SIZE_0K_V3 = 0x0F, /**< @brief control code to partition EEPROM backup size as 0K, used for the partitioning command */
+    EEP_FTFC_EEEPROM_SIZE_32K_V1 = 0x3, /**< @brief control code to partition EEPROM backup size as 32K, used for the partitioning command */
+    EEP_FTFC_EEEPROM_SIZE_32K_V2 = 0xB, /**< @brief control code to partition EEPROM backup size as 32K, used for the partitioning command */
+    EEP_FTFC_EEEPROM_SIZE_48K_V1 = 0xA, /**< @brief control code to partition EEPROM backup size as 48K, used for the partitioning command */
+    EEP_FTFC_EEEPROM_SIZE_64K_V1 = 0x8, /**< @brief control code to partition EEPROM backup size as 64K, used for the partitioning command */
+    EEP_FTFC_EEEPROM_SIZE_64K_V2 = 0x4, /**< @brief control code to partition EEPROM backup size as 64K, used for the partitioning command */
+    EEP_FTFC_EEEPROM_SIZE_24K_V2 = 0x9  /**< @brief control code to partition EEPROM backup size as 24K, used for the partitioning command */
+} TestEep_Eeprom_FlexNvmPartitionType;
+/**
+    @brief Sfe Type used for the partitioning command
+*/
+typedef enum
+{
+    EEP_FTFC_VERIFY_ONLY_DISABLED = 0x0, /**< @brief control code for sfe verify only disabled, used for the partitioning command */
+    EEP_FTFC_VERIFY_ONLY_ENABLED = 0x1   /**< @brief control code for sfe verify only enabled, used for the partitioning command */
+} TestEep_SfeType;
+
+/**
+    @brief LoadFlexRam at reset Type used for the partitioning command
+*/
+typedef enum
+{
+    EEP_FTFC_LOAD_AT_RESET_ENABLED = 0x0, /**< @brief control code for loading flexram at reset, used for the partitioning command */
+    EEP_FTFC_LOAD_AT_RESET_DISABLED = 0x1 /**< @brief control code for not loading flexram at reset, used for the partitioning command */
+} TestEep_LoadFlexRamType;
+
+#define EEP_ERASE_START_ADD (0U)
+#define EEP_WRTESTPATT_SIZE (33U)
+#define EEP_RDTESTPATT_SIZE (33U)
+
+#define REG_WRITE8(address, value) (*((volatile uint8 *)(address)) = (value))
+#define REG_BIT_GET8(address, mask) ((*(volatile uint8 *)(address)) & (mask))
+
+#define T_EEEPROM_SIZE EEP_FTFC_EEEPROM_SIZE_32K_V2
+#define TEST_EEP_EEPROM_FSTAT_ADDR32 ((uint32)(IP_FTFC_BASE + (uint32)0x00UL))  /**< @brief Eeprom Status Register (FTFE_FSTAT) */
+#define TEST_EEP_EEPROM_FCCOB3_ADDR32 ((uint32)(IP_FTFC_BASE + (uint32)0x04UL)) /**< @brief Eeprom Common Command Object Registers(FTFE_FCCOB3) */
+#define TEST_EEP_EEPROM_FCCOB2_ADDR32 ((uint32)(IP_FTFC_BASE + (uint32)0x05UL)) /**< @brief Eeprom Common Command Object Registers(FTFE_FCCOB2) */
+#define TEST_EEP_EEPROM_FCCOB1_ADDR32 ((uint32)(IP_FTFC_BASE + (uint32)0x06UL)) /**< @brief Eeprom Common Command Object Registers(FTFE_FCCOB1) */
+#define TEST_EEP_EEPROM_FCCOB0_ADDR32 ((uint32)(IP_FTFC_BASE + (uint32)0x07UL)) /**< @brief Eeprom Common Command Object Registers(FTFE_FCCOB0) */
+#define TEST_EEP_EEPROM_FCCOB7_ADDR32 ((uint32)(IP_FTFC_BASE + (uint32)0x08UL)) /**< @brief Eeprom Common Command Object Registers(FTFE_FCCOB7) */
+#define TEST_EEP_EEPROM_FCCOB6_ADDR32 ((uint32)(IP_FTFC_BASE + (uint32)0x09UL)) /**< @brief Eeprom Common Command Object Registers(FTFE_FCCOB6) */
+#define TEST_EEP_EEPROM_FCCOB5_ADDR32 ((uint32)(IP_FTFC_BASE + (uint32)0x0AUL)) /**< @brief Eeprom Common Command Object Registers(FTFE_FCCOB5) */
+#define TEST_EEP_EEPROM_FCCOB4_ADDR32 ((uint32)(IP_FTFC_BASE + (uint32)0x0BUL)) /**< @brief Eeprom Common Command Object Registers(FTFE_FCCOB4) */
+
+#define TEST_EEP_EEPROM_FSTAT_CCIF_U8 (0x0080U)
+#define TEST_EEP_EEPROM_FSTAT_ACCERR_U8 (0x0020U)
+#define TEST_EEP_EEPROM_FSTAT_FPVIOL_U8 (0x0010U)
+/* Start address for DFLASH sector 0 */
+#define TEST_EEP_DEEPROM_SECTOR_0_ADDR32 0x10000000
+#define D_EEPROM_BASE_ADDR (0x10000000UL)
+#define TEST_EEP_EEPROM_CMD_ERASE_SECTOR (0x09UL)
+
+#define EEPROM_CMD_PROGRAM_PARTITION (0x80UL)
+extern Std_ReturnType CanIf_SendMessage(uint8 ControllerId, Can_Msg_Type CanMsg);
+void Eep_DepartParitition(TestEep_Eeprom_FlexNvmPartitionType T_EEP_SIZE);
+Std_ReturnType HAL_EEP_Erase(uint32 eepEraseStartAddr, uint32 eepEraseSize);
+Std_ReturnType HAL_EEP_Read(uint32 eepReadStartAddr, uint8 *pDataBuffer, uint32 dataSize);
+Std_ReturnType HAL_EEP_Write(uint32 eepWriteStartAddr, uint8 *pDataNeedtoWrite, uint32 dataSize);
+Std_ReturnType HAL_EEP_Compare(uint32 eepCompareStartAddr, uint8 *pDataNeedtoCompare, uint32 dataSize);
+Std_ReturnType ADC_ReadValue(void);
+sint8 AtcmdDelayRecvFunc(uint8 recvChannel,char *ResultStrPtr,uint16 delayTime);
+Std_ReturnType UART_Query_Data(uint8 transChannel, uint8 recvChannel, uint8 *txBuffer, uint16 sendLength, uint8 *rxBuffer, uint16 *rxlen, uint32 T_timeout);
+Std_ReturnType UART_Send_Data(uint8 transChannel, const uint8 *txBuffer, uint32 sendLength, uint32 T_timeout);
+Std_ReturnType UART_Receive_Data(uint8 recvChannel, uint8 *rxBuffer, uint8 *rxlen, uint32 T_timeout);
+Std_ReturnType UART_Reset(uint8 recvChannel);
+void UART_Callback(uint32 hwInstance, Lpuart_Uart_Ip_EventType event);
+void UartInit(void);
+void SystemSoftwareReset(void);
+void create_ringBuffer(ringbuffer_t *ringBuf, uint8_t *buf, uint32_t buf_len);
+void clear_ringBuffer(ringbuffer_t *ringBuf);
+uint32_t write_ringBuffer(uint8_t *buffer, uint32_t size, ringbuffer_t *ringBuf);
+uint32_t read_ringBuffer(uint8_t *buffer, uint32_t size, ringbuffer_t *ringBuf);
+#endif /* HAL_ADAPTER_H_ */

+ 25 - 19
src/main.c → code/main.c

@@ -24,7 +24,7 @@
 
 /**
  *   @file main.c
- * Ö÷º¯ÊýÈë¿Ú
+ * 主函数入�
  *   @addtogroup main_module main module documentation
  *   @{
  */
@@ -61,14 +61,14 @@
 #include "AppTaskCan.h"
 #include "AppTaskGps.h"
 #include "Hal_Fls.h"
-
-
-
-
+#include "SEGGER_SYSVIEW.h"
+#include "cm_backtrace.h"
+#define APPNAME                        "S32K146_4G"
+#define HARDWARE_VERSION               "V1.0.0"
+#define SOFTWARE_VERSION               "V0.0.1"
 int main(void)
 {
-
-	volatile int exit_code = 0;
+ 	volatile int exit_code = 0;
 	/* Initialize the Mcu driver */
 #if (MCU_PRECOMPILE_SUPPORT == STD_ON)
 	Mcu_Init(NULL_PTR);
@@ -122,7 +122,7 @@ int main(void)
 	Adc_Init(&Adc_Config_VS_0);
 #endif /* ADC_PRECOMPILE_SUPPORT == STD_ON */
     /* Partition only if it was not partitioned before for EERAM with code 0x4 */
-    Eep_DepartParitition(T_EEEPROM_SIZE);
+//    Eep_DepartParitition(T_EEEPROM_SIZE);
     /* Initialize Eep driver */
 #if defined (EEP_PRECOMPILE_SUPPORT)
     Eep_Init(NULL_PTR);
@@ -157,14 +157,12 @@ int main(void)
 	Gpt_EnableNotification(GptConf_GptChannelConfiguration_GptChannelConfiguration_0);
 
 	WdgInit();
-
-
 	IP_LPUART0->CTRL |= LPUART_CTRL_ILT(1);
 	IP_LPUART1->CTRL |= LPUART_CTRL_ILT(1);
 	IP_LPUART2->CTRL |= LPUART_CTRL_ILT(1);
-	IP_LPUART0->CTRL |= LPUART_CTRL_IDLECFG(7);
-	IP_LPUART1->CTRL |= LPUART_CTRL_IDLECFG(7);
-	IP_LPUART2->CTRL |= LPUART_CTRL_IDLECFG(7);
+	IP_LPUART0->CTRL |= LPUART_CTRL_IDLECFG(5);
+	IP_LPUART1->CTRL |= LPUART_CTRL_IDLECFG(3);
+	IP_LPUART2->CTRL |= LPUART_CTRL_IDLECFG(3);
 
 	Dio_WriteChannel(DioConf_DioChannel_PTE0_GPIO_OUT_MCU_LED1, STD_OFF);
 	Dio_WriteChannel(DioConf_DioChannel_PTE1_GPIO_OUT_MCU_LED2, STD_OFF);
@@ -172,12 +170,21 @@ int main(void)
 	Dio_WriteChannel(DioConf_DioChannel_PTE8_GPIO_OUT_MCU_LED4, STD_OFF);
 	Dio_WriteChannel(DioConf_DioChannel_PTE9_GPIO_OUT_MCU_LED5, STD_OFF);
 
-	xTaskCreate(MainTask, (const char *const)"MainTask", 128, (void *)0, main_TASK_PRIORITY + 7, NULL);
-	UartInit();
-	xTaskCreate(Uart_4G_Task, (const char *const)"Uart_4G_Task", 2048, (void *)0, main_TASK_PRIORITY + 3, NULL);
-//	xTaskCreate(CanTask, (const char *const)"CanTask", 512, (void *)0, main_TASK_PRIORITY + 4, NULL);
-	xTaskCreate(GpsTask, (const char *const)"GpsTask", 512, (void *)0, main_TASK_PRIORITY + 2, NULL);
+#ifdef SEGGER_SYSTEMVIEW
+	SEGGER_SYSVIEW_Conf();
+#endif
 
+#ifdef SEGGER_RTT_PRINTF
+	SEGGER_RTT_Init();
+	cm_backtrace_init(APPNAME,HARDWARE_VERSION,SOFTWARE_VERSION);
+	SEGGER_RTT_printf("[%d] boot\r\n",__LINE__);
+#endif
+	UartInit();
+	xTaskCreate(MainTask, (const char *const)"MainTask", 256, (void *)0, main_TASK_PRIORITY + 6, NULL);
+	// xTaskCreate(Uart0Task, (const char *const)"Uart0_Bms_Task", 1024, (void *)0, main_TASK_PRIORITY + 2, NULL);
+	xTaskCreate(CanTask, (const char *const)"CanTask", 512, (void *)0, main_TASK_PRIORITY + 2, NULL);
+	xTaskCreate(GpsTask, (const char *const)"GpsTask", 512, (void *)0, main_TASK_PRIORITY + 1, NULL);
+	xTaskCreate(Uart_4G_Task, (const char *const)"Uart_4G_Task", 2048, (void *)0, main_TASK_PRIORITY + 0, NULL);
 	vTaskStartScheduler();
 	for (;;)
 	{
@@ -188,5 +195,4 @@ int main(void)
 	}
 	return exit_code;
 }
-
 /** @} */

+ 11 - 11
generate/src/Power_Ip_VS_0_PBcfg.c

@@ -161,17 +161,17 @@ static const Power_Ip_RCM_ConfigType Power_Ip_RCM_ConfigPB_VS_0 =
     ),
     /* System Reset Interrupt Enable Register (RCM_SRIE) */
     (
-        RCM_SRIE_SACKERR_INT_DIS_U32 |
-        RCM_SRIE_MDM_AP_INT_DIS_U32 |
-        RCM_SRIE_SSW_INT_DIS_U32 |
-        RCM_SRIE_LOCKUP_INT_DIS_U32 |
-        RCM_SRIE_JTAG_INT_DIS_U32 |
-        RCM_SRIE_GIE_INT_DIS_U32 |
-        RCM_SRIE_PIN_INT_DIS_U32 |
-        RCM_SRIE_WDOG_INT_DIS_U32 |
-        RCM_SRIE_CMU_INT_DIS_U32 |
-        RCM_SRIE_LOL_INT_DIS_U32 |
-        RCM_SRIE_LOC_INT_DIS_U32 |
+        RCM_SRIE_SACKERR_INT_EN_U32 |
+        RCM_SRIE_MDM_AP_INT_EN_U32 |
+        RCM_SRIE_SW_INT_EN_U32 |
+        RCM_SRIE_LOCKUP_INT_EN_U32 |
+        RCM_SRIE_JTAG_INT_EN_U32 |
+        RCM_SRIE_GIE_INT_EN_U32 |
+        RCM_SRIE_PIN_INT_EN_U32 |
+        RCM_SRIE_WDOG_INT_EN_U32 |
+        RCM_SRIE_CMU_INT_EN_U32 |
+        RCM_SRIE_LOL_INT_EN_U32 |
+        RCM_SRIE_LOC_INT_EN_U32 |
         RCM_SRIE_DELAY_10_LPO_CYCLES_U32
     )
 };

+ 0 - 16
src/AppTaskMain.h

@@ -1,16 +0,0 @@
-/*
- * AppTaskMain.h
- *
- *  Created on: 2022Äê2ÔÂ22ÈÕ
- *      Author: QiXiang_CHENJIE
- */
-
-#ifndef APPTASKMAIN_H_
-#define APPTASKMAIN_H_
-#include "hal_adapter.h"
-#include "AppFunclib.h"
-#include "AppGlobalVar.h"
-#include "Hal_Wdg.h"
-void MainTask(void *pvParameters);
-
-#endif /* APPTASKMAIN_H_ */

+ 0 - 13
src/AppTaskUart0.h

@@ -1,13 +0,0 @@
-/*
- * AppTaskUart0.h
- *
- *  Created on: 2022Äê2ÔÂ22ÈÕ
- *      Author: QiXiang_CHENJIE
- */
-
-#ifndef APPTASKUART0_H_
-#define APPTASKUART0_H_
-#include "hal_adapter.h"
-#include "AppFunclib.h"
-#include "AppGlobalVar.h"
-#endif /* APPTASKUART0_H_ */