embeded/Cortex-M3 STM2026. 3. 6. 10:33

이런식으로 코드가 보이길래 했더니 실행이 안되서 디버거 물려보니

그냥 먼가.. 무한루프만 돌고 원하는 곳의 코드가 실행이 되지 않길래

/* USER CODE BEGIN 1 */
typedef  void (*pFunction)(void);
uint32_t JumpAddress;
void (*Jump_To_Application)();
/* USER CODE END 1 */

/* USER CODE BEGIN 2 */
  if (HAL_GPIO_ReadPin(Firmup_Pin_GPIO_Port, Firmup_Pin_Pin) != GPIO_PIN_RESET)
  {
    if (((*(__IO uint32_t*)USBD_DFU_APP_DEFAULT_ADD - 1) & 0x2FFFB000 ) == 0x20000000)
    {
      JumpAddress = *(__IO uint32_t*) (USBD_DFU_APP_DEFAULT_ADD + 4);
      Jump_To_Application = (pFunction) JumpAddress;
      __set_MSP(*(__IO uint32_t*) USBD_DFU_APP_DEFAULT_ADD);
      Jump_To_Application();
    }
  }
  MX_USB_DEVICE_Init();
  /* USER CODE END 2 */

[링크 : https://www.os4all.com/69]

 

먼가 더 필요한거 같아서 검색!

​1. 링커스크립트에서 인터럽트벡터가 있는 .isr_vector 섹션의 위치를 수정
2. SystemInit() 함수에서 SCB->VTOR 레지스터를 변경하고자 하는 섹션의 위치로 수정

SCB->VTOR = (uint32_t)&__isr_vector_addr;

[링크 : https://m.blog.naver.com/chcbaram/222580261732]

[링크 : https://m.blog.naver.com/chcbaram/221347218232]

 

먼가 초기화 하면서 손대는게 점점 많아지는 느낌..

아무튼 스택포인터를 옮겨주고 isr 테이블의 리셋 핸들러를 실행해줌으로서 초기화 하고 전체 프로그램을 다시 돌리는 구조인 듯.

void JumpToBootloader(void) {
    // Deinit HAL and Clocks
    HAL_DeInit();
    HAL_RCC_DeInit();
    
    // Disable all interrupts
    __disable_irq();

    // Disable Systick
    SysTick->CTRL = 0;
    SysTick->LOAD = 0;
    SysTick->VAL = 0;

    // Disable interrupts and clear pending ones
    for (size_t i = 0; i < sizeof(NVIC->ICER)/sizeof(NVIC->ICER[0]); i++) {
        NVIC->ICER[i]=0xFFFFFFFF;
        NVIC->ICPR[i]=0xFFFFFFFF;
    }

    // Re-enable interrupts
    __enable_irq();

    // Map Bootloader (system flash) memory to 0x00000000. This is STM32 family dependant.
    __HAL_SYSCFG_REMAPMEMORY_SYSTEMFLASH();
    
    // Set embedded bootloader vector table base offset
    WRITE_REG(SCB->VTOR, SCB_VTOR_TBLOFF_Msk & 0x00000000);

    // Switch to Main Stack Pointer (in case it was using the Process Stack Pointer)
    __set_CONTROL(0);
    
    // Instruction synchronization barrier
    __ISB();

    // Set Main Stack Pointer to the Bootloader defined value.
    __set_MSP(BOOTLOADER_VECTOR_TABLE->stack_pointer);

    __DSB(); // Data synchronization barrier
    __ISB(); // Instruction synchronization barrier

    // Jump to Bootloader Reset Handler
    BOOTLOADER_VECTOR_TABLE->reset_handler();
    
    // The next instructions will not be reached
    while (1){}
}

[링크 : https://gist.github.com/gonzabrusco/fd47e89e4c6fb302fc54b83637a3a101

[링크 : https://blog.naver.com/alfee0/224043194861]

 

'embeded > Cortex-M3 STM' 카테고리의 다른 글

stm32cubeide cpp 변환이후 generate code  (0) 2026.02.25
mbed + stm32cube hal...?  (0) 2026.02.23
Mbed studio on ubuntu 22.04  (0) 2026.02.23
stm32f103c8t6 cpp std::cout 실패  (0) 2026.02.18
stm32 rtc tamper  (0) 2026.01.29
Posted by 구차니
embeded/Cortex-M3 STM2026. 2. 25. 16:39

어.. 그냥 얘네는 먼가 하나씩 엇박인 느낌이냐..

CubeIDE 에서 해당 프로젝트를 cpp로 바꾸어도

CubeMX 로 생성되는 파일은 main.c로 나온다. -_-

그냥 알아서(?) 복사해서 넣던가, 아니면 cpp를 c로 바꾸고 generate code 해주던가

영 귀찮네..

 

[링크 : https://community.st.com/t5/stm32cubemx-mcus/generating-c-projects-with-stm32cubemx/td-p/53253]

'embeded > Cortex-M3 STM' 카테고리의 다른 글

stm32 다른 영역으로 점프(부트로더)  (0) 2026.03.06
mbed + stm32cube hal...?  (0) 2026.02.23
Mbed studio on ubuntu 22.04  (0) 2026.02.23
stm32f103c8t6 cpp std::cout 실패  (0) 2026.02.18
stm32 rtc tamper  (0) 2026.01.29
Posted by 구차니
embeded/Cortex-M3 STM2026. 2. 23. 21:58

[링크 : https://os.mbed.com/forum/mbed/topic/33580/]

[링크 : https://m.blog.naver.com/rlackd93/222449859004]

 

대충 본걸로는 두 개 같이 정상적(?)으로 사용하는건 쉽지않거나 사실상 불가능한 수준?

 

가능 + 방향

일단 mbed 는 cpp 이고

stm32 hal은 c로 되어있는데 cpp 컴파일러에서 extern c를 통해서 c를 끌어올수 있으니

mbed에서 stm32 hal을 끌어올수는 있다 정도?

 

차이점

arm 의 레지스터를 접근해서 설정하도록 구현되어 있어서

mbed hal과 stm32 hal은 코드레벨에서 호환되지 않는다.

서로 관리하는 구조체도 달라서 두개를 무작정 쓰다 보면 충돌나기 쉽고

isr이 관련될 경우 mbed쪽은 다시 덮어 써버리면서 stm32 hal쪽이 정상작동하지 않게 될 가능성이 높아 보인다.

 

추가로 라이브러리 레벨에서는.. mbed가 cpp를 써서 그런가

isr을 런타임중에 교체 가능하도록 구성되어 있어서 이걸 stm32 hal로 구현하려면 어우..

함수 포인터로 비슷하게 할순 있겠지만 아무튼.. 제법 깊게 짱박혀 있어서 구현해보려면 좀 더 깊숙히 봐야할 것 같다.

mbed 예제보다가 가장 신기했던 타이머 이벤트 추가하는 Timeout 클래스

#include "mbed.h"
Timeout response;
DigitalIn button (p14);
DigitalOut led1(LED1);
DigitalOut led2(LED2);
DigitalOut led3(LED3);

void blink() {
  led2 = 1;
  wait(0.5);
  led2 = 0;
}

int main() {
  while(true) {
    if(button == 1){
      response.attach(&blink, 3.0);
      led3=1;
    } else {
      led3=0;
    }
    led1=!led1;     
    wait(0.2);
  }
}

[링크 : https://os.mbed.com/teams/TVZ-Mechatronics-Team/wiki/Timers-interrupts-and-tasks]

 

[링크 : https://os.mbed.com/docs/mbed-os/v6.16/apis/timeout.html]

 

 

'embeded > Cortex-M3 STM' 카테고리의 다른 글

stm32 다른 영역으로 점프(부트로더)  (0) 2026.03.06
stm32cubeide cpp 변환이후 generate code  (0) 2026.02.25
Mbed studio on ubuntu 22.04  (0) 2026.02.23
stm32f103c8t6 cpp std::cout 실패  (0) 2026.02.18
stm32 rtc tamper  (0) 2026.01.29
Posted by 구차니
embeded/Cortex-M3 STM2026. 2. 23. 11:00

fuse 3.x가 아니라 fuse 2.x를 요구하는 듯.

~/.local/bin$ ./mbed-studio
dlopen(): error loading libfuse.so.2

AppImages require FUSE to run. 
You might still be able to extract the contents of this AppImage 
if you run it with the --appimage-extract option. 
See https://github.com/AppImage/AppImageKit/wiki/FUSE 
for more information

 

부랴부랴 깔고

$ sudo apt-get install libfuse2
패키지 목록을 읽는 중입니다... 완료
의존성 트리를 만드는 중입니다... 완료
상태 정보를 읽는 중입니다... 완료        
다음 새 패키지를 설치할 것입니다:
  libfuse2
0개 업그레이드, 1개 새로 설치, 0개 제거 및 4개 업그레이드 안 함.
90.3 k바이트 아카이브를 받아야 합니다.
이 작업 후 330 k바이트의 디스크 공간을 더 사용하게 됩니다.
받기:1 http://kr.archive.ubuntu.com/ubuntu jammy/universe amd64 libfuse2 amd64 2.9.9-5ubuntu3 [90.3 kB]
내려받기 90.3 k바이트, 소요시간 0초 (290 k바이트/초)
Selecting previously unselected package libfuse2:amd64.
(데이터베이스 읽는중 ...현재 468242개의 파일과 디렉터리가 설치되어 있습니다.)
Preparing to unpack .../libfuse2_2.9.9-5ubuntu3_amd64.deb ...
Unpacking libfuse2:amd64 (2.9.9-5ubuntu3) ...
libfuse2:amd64 (2.9.9-5ubuntu3) 설정하는 중입니다 ...
Processing triggers for libc-bin (2.35-0ubuntu3.13) ...

 

콘솔에서 하던 메뉴에서 하던 아무튼 잘 실행된다.

~/.local/bin$ ./mbed-studio
[2026-02-23T10:56:45.744] [INFO] MbedStudio - Configuration directory URI: 'file:///home/falinux/.theia' []
[2026-02-23T10:56:45.745] [DEBUG] MbedStudio - Backend Object.initialize took: 5.4 ms []
[2026-02-23T10:56:45.745] [ERROR] MbedStudio - (node:3182744) [DEP0005] DeprecationWarning: Buffer() is deprecated due to security and usability issues. Please use the Buffer.alloc(), Buffer.allocUnsafe(), or Buffer.from() methods instead. []
[2026-02-23T10:56:45.745] [DEBUG] MbedStudio - Backend ElectronTokenBackendContribution.configure took: 3.9 ms []
[2026-02-23T10:56:45.745] [DEBUG] MbedStudio - Backend ElectronMessagingContribution.onStart took: 1.3 ms []
[2026-02-23T10:56:45.746] [DEBUG] MbedStudio - Backend MbedEnvContribution.initialize took: 0.7 ms []
[2026-02-23T10:56:45.746] [DEBUG] MbedStudio - Backend FileDownloadEndpoint.configure took: 0.5 ms []
[2026-02-23T10:56:45.746] [DEBUG] MbedStudio - Backend TaskBackendApplicationContribution.onStart took: 0.2 ms []
[2026-02-23T10:56:45.746] [DEBUG] MbedStudio - Starting the deployer with the list of resolvers [
  [
    LocalDirectoryPluginDeployerResolver {},
    GithubPluginDeployerResolver {
      unpackedFolder: '/tmp/github-remote'
    },
    HttpPluginDeployerResolver { unpackedFolder: '/tmp/http-remote' }
  ]
]
[2026-02-23T10:56:45.747] [DEBUG] MbedStudio - STUDIO_ACTIVITY_URL variable not set. Activity monitoring is disabled. []
[2026-02-23T10:56:45.748] [DEBUG] MbedStudio - Backend PluginDeployerContribution.initialize took: 0.8 ms []
[2026-02-23T10:56:45.748] [DEBUG] MbedStudio - Backend AuthenticationServerImpl.configure took: 0.4 ms []
[2026-02-23T10:56:45.748] [DEBUG] MbedStudio - Backend ActivityServiceImpl.onStart took: 0.1 ms []
[2026-02-23T10:56:45.748] [INFO] MbedStudio - Configuring to accept webviews on '.+.webview..+' hostname. []
[2026-02-23T10:56:45.748] [INFO] root/mbs-device - Starting USB detection []
[2026-02-23T10:56:45.748] [DEBUG] MbedStudio - Found the list of default plugins ID on env: [ undefined ]
[2026-02-23T10:56:45.748] [DEBUG] MbedStudio - Found the list of plugins ID on env: [ undefined ]
[2026-02-23T10:56:45.748] [DEBUG] MbedStudio - Found the list of default plugins ID from CLI: [ undefined ]
[2026-02-23T10:56:45.749] [DEBUG] MbedStudio - Backend PluginApiContribution.configure took: 1.2 ms []
[2026-02-23T10:56:45.749] [DEBUG] MbedStudio - Backend DeviceManager.onStart took: 0.8 ms []
[2026-02-23T10:56:45.751] [DEBUG] MbedStudio - Backend HostedPluginReader.configure took: 2.5 ms []
[2026-02-23T10:56:45.751] [DEBUG] MbedStudio - Backend GitDetailsManager.onStart took: 2.7 ms []
[2026-02-23T10:56:45.751] [DEBUG] MbedStudio - Removing all user plugins []
[2026-02-23T10:56:45.751] [DEBUG] MbedStudio - Appending system plugins: local-dir:/home/falinux/mbs-plugins, local-dir:/tmp/.mount_mbed-skHNrFk/resources/app/plugins/electron, local-dir:/tmp/.mount_mbed-skHNrFk/resources/app/theia-plugins []
[2026-02-23T10:56:45.751] [WARN] MbedStudio - The directory referenced by local-dir:/home/falinux/mbs-plugins does not exist. []
[2026-02-23T10:56:45.752] [INFO] MbedStudio - Theia app listening on http://localhost:33937. []
[2026-02-23T10:56:45.762] [INFO] MbedStudio - PluginTheiaDirectoryHandler: accepting plugin with path [
  '/tmp/.mount_mbed-skHNrFk/resources/app/plugins/electron/mbs-plugin-electron-mbed'
]
[2026-02-23T10:56:45.763] [DEBUG] MbedStudio - Resolving "mbs-plugin-electron-mbed" as a VS Code extension... []
[2026-02-23T10:56:45.767] [INFO] MbedStudio - PluginTheiaDirectoryHandler: accepting plugin with path [
  '/tmp/.mount_mbed-skHNrFk/resources/app/theia-plugins/vscode-builtin-cpp'
]
[2026-02-23T10:56:45.767] [DEBUG] MbedStudio - Resolving "vscode-builtin-cpp" as a VS Code extension... []
[2026-02-23T10:56:45.767] [INFO] MbedStudio - Resolved "vscode-builtin-cpp" to a VS Code extension "cpp@1.44.2" with engines: [ { vscode: '*' } ]
[2026-02-23T10:56:45.768] [INFO] MbedStudio - PluginTheiaDirectoryHandler: accepting plugin with path [
  '/tmp/.mount_mbed-skHNrFk/resources/app/theia-plugins/vscode-builtin-json'
]
[2026-02-23T10:56:45.768] [DEBUG] MbedStudio - Resolving "vscode-builtin-json" as a VS Code extension... []
[2026-02-23T10:56:45.768] [INFO] MbedStudio - Resolved "vscode-builtin-json" to a VS Code extension "json@1.44.2" with engines: [ { vscode: '0.10.x' } ]
[2026-02-23T10:56:45.768] [INFO] MbedStudio - PluginTheiaDirectoryHandler: accepting plugin with path [
  '/tmp/.mount_mbed-skHNrFk/resources/app/theia-plugins/vscode-builtin-python'
]
[2026-02-23T10:56:45.768] [DEBUG] MbedStudio - Resolving "vscode-builtin-python" as a VS Code extension... []
[2026-02-23T10:56:45.768] [INFO] MbedStudio - Resolved "vscode-builtin-python" to a VS Code extension "python@1.44.2" with engines: [ { vscode: '*' } ]
[2026-02-23T10:56:45.768] [INFO] MbedStudio - PluginTheiaDirectoryHandler: accepting plugin with path [
  '/tmp/.mount_mbed-skHNrFk/resources/app/theia-plugins/vscode-builtin-shellscript'
]
[2026-02-23T10:56:45.768] [DEBUG] MbedStudio - Resolving "vscode-builtin-shellscript" as a VS Code extension... []
[2026-02-23T10:56:45.768] [INFO] MbedStudio - Resolved "vscode-builtin-shellscript" to a VS Code extension "shellscript@1.44.2" with engines: [ { vscode: '*' } ]
[2026-02-23T10:56:45.769] [INFO] MbedStudio - PluginTheiaDirectoryHandler: accepting plugin with path [
  '/tmp/.mount_mbed-skHNrFk/resources/app/theia-plugins/vscode-builtin-xml'
]
[2026-02-23T10:56:45.769] [DEBUG] MbedStudio - Resolving "vscode-builtin-xml" as a VS Code extension... []
[2026-02-23T10:56:45.769] [INFO] MbedStudio - Resolved "vscode-builtin-xml" to a VS Code extension "xml@1.44.2" with engines: [ { vscode: '*' } ]
[2026-02-23T10:56:45.769] [INFO] MbedStudio - PluginTheiaDirectoryHandler: accepting plugin with path [
  '/tmp/.mount_mbed-skHNrFk/resources/app/theia-plugins/vscode-builtin-yaml'
]
[2026-02-23T10:56:45.769] [DEBUG] MbedStudio - Resolving "vscode-builtin-yaml" as a VS Code extension... []
[2026-02-23T10:56:45.769] [INFO] MbedStudio - Resolved "vscode-builtin-yaml" to a VS Code extension "yaml@1.44.2" with engines: [ { vscode: '*' } ]
[2026-02-23T10:56:45.774] [DEBUG] MbedStudio - the accepted plugins are [ [] ]
[2026-02-23T10:56:45.775] [DEBUG] MbedStudio - the acceptedFrontendPlugins plugins are [ [] ]

 

'embeded > Cortex-M3 STM' 카테고리의 다른 글

stm32cubeide cpp 변환이후 generate code  (0) 2026.02.25
mbed + stm32cube hal...?  (0) 2026.02.23
stm32f103c8t6 cpp std::cout 실패  (0) 2026.02.18
stm32 rtc tamper  (0) 2026.01.29
stm32f103 rtc backup register  (0) 2026.01.29
Posted by 구차니
embeded/Cortex-M3 STM2026. 2. 18. 22:14

아래코드까진 문제가 없는데

class my_class
{
public:
	int i_var;
	int f();
};

int my_class::f()
{
	return ++i_var;
}

int main(void)
{
	my_class *p_my_class = new my_class();
	p_my_class->f();
}

 

iostream을 추가해서 (아직 uart 출력을 연결하진 않고 빌드만 했지만)

std::cout을 통해 출력만 해보려고 했는데

#include <iostream>

class my_class
{
public:
	int i_var;
	int f();
};

int my_class::f()
{
	return ++i_var;
}

int main(void)
{
	my_class *p_my_class = new my_class();
	std::cout << p_my_class->f();
}

 

플래시 용량이 터져나가 버렸다.

cout을 쓰려면 최소 192KB 이상의 flash는 되어야 한다는건가?

22:05:02 **** Incremental Build of configuration Debug for project cpp_test ****
make -j4 all 
arm-none-eabi-g++ "../Core/Src/main.cpp" -mcpu=cortex-m3 -std=gnu++14 -g3 -DDEBUG -DUSE_HAL_DRIVER -DSTM32F103xB -c -I../Core/Inc -I../Drivers/STM32F1xx_HAL_Driver/Inc/Legacy -I../Drivers/STM32F1xx_HAL_Driver/Inc -I../Drivers/CMSIS/Device/ST/STM32F1xx/Include -I../Drivers/CMSIS/Include -O0 -ffunction-sections -fdata-sections -fno-exceptions -fno-rtti -fno-use-cxa-atexit -Wall -fstack-usage -fcyclomatic-complexity -MMD -MP -MF"Core/Src/main.d" -MT"Core/Src/main.o" --specs=nano.specs -mfloat-abi=soft -mthumb -o "Core/Src/main.o"
arm-none-eabi-g++ -o "cpp_test.elf" @"objects.list"   -mcpu=cortex-m3 -T"/home/minimonk/STM32CubeIDE/workspace_1.19.0_cpp/cpp_test/STM32F103C8TX_FLASH.ld" --specs=nosys.specs -Wl,-Map="cpp_test.map" -Wl,--gc-sections -static --specs=nano.specs -mfloat-abi=soft -mthumb -Wl,--start-group -lc -lm -lstdc++ -lsupc++ -Wl,--end-group
/home/minimonk/st/stm32cubeide_1.19.0/plugins/cohttp://m.st.stm32cube.ide.mcu.externaltools.gnu-tools-for-stm32.13.3.rel1.linux64_1.0.0.202410170706/tools/bin/../lib/gcc/arm-none-eabi/13.3.1/../../../../arm-none-eabi/bin/ld: /home/minimonk/st/stm32cubeide_1.19.0/plugins/cohttp://m.st.stm32cube.ide.mcu.externaltools.gnu-tools-for-stm32.13.3.rel1.linux64_1.0.0.202410170706/tools/bin/../lib/gcc/arm-none-eabi/13.3.1/../../../../arm-none-eabi/lib/thumb/v7-m/nofp/libc_nano.a(libc_a-getentropyr.o): in function `_getentropy_r':
(.text._getentropy_r+0xe): warning: _getentropy is not implemented and will always fail
/home/minimonk/st/stm32cubeide_1.19.0/plugins/cohttp://m.st.stm32cube.ide.mcu.externaltools.gnu-tools-for-stm32.13.3.rel1.linux64_1.0.0.202410170706/tools/bin/../lib/gcc/arm-none-eabi/13.3.1/../../../../arm-none-eabi/bin/ld: /home/minimonk/st/stm32cubeide_1.19.0/plugins/cohttp://m.st.stm32cube.ide.mcu.externaltools.gnu-tools-for-stm32.13.3.rel1.linux64_1.0.0.202410170706/tools/bin/../lib/gcc/arm-none-eabi/13.3.1/../../../../arm-none-eabi/lib/thumb/v7-m/nofp/libc_nano.a(libc_a-getentropyr.o): note: the message above does not take linker garbage collection into account
/home/minimonk/st/stm32cubeide_1.19.0/plugins/cohttp://m.st.stm32cube.ide.mcu.externaltools.gnu-tools-for-stm32.13.3.rel1.linux64_1.0.0.202410170706/tools/bin/../lib/gcc/arm-none-eabi/13.3.1/../../../../arm-none-eabi/bin/ld: cpp_test.elf section `.text' will not fit in region `FLASH'
/home/minimonk/st/stm32cubeide_1.19.0/plugins/cohttp://m.st.stm32cube.ide.mcu.externaltools.gnu-tools-for-stm32.13.3.rel1.linux64_1.0.0.202410170706/tools/bin/../lib/gcc/arm-none-eabi/13.3.1/../../../../arm-none-eabi/bin/ld: region `FLASH' overflowed by 109220 bytes
collect2: error: ld returned 1 exit status
make: *** [makefile:88: cpp_test.elf] Error 1
"make -j4 all" terminated with exit code 2. Build might be incomplete.

22:05:04 Build Failed. 4 errors, 1 warnings. (took 2s.252ms)

[링크 : https://igotit.tistory.com/entry/STM32CubeIDE-임베디드-코드에서-C-클래스-활용]

 


gpt 말로는 아래를 설정해주라는데, std::cout 하면 버퍼부터 하위시스템 다 끌려온다는거 치고는 너무 큰디..

데드 코드 삭제
-ffunction-sections
-fdata-sections

링커옵션
-Wl,--gc-sections


예외/RTTI 끄기
-fno-exceptions
-fno-rtti

newlib nano
--specs=nano.specs

 

그래서 설정을 보는데, 기본으로 부동소수점 출력/입력은 안하게 되어있고

 

g++ 쪽은 기본적으로 아래의 4개 플래그가 설정되어 있다.

-ffunctions-sections

-fdata-sections

-fno-exceptions

-fno-rtti

 

링커도 -Wl,--gc-sections 되어 있어서 더 옵션으로 먼가 줄일수 있는 상태는 아닌데..

[링크 : https://vuzwa.tistory.com/entry/STM32CubeIDE에서-개발환경-C-or-C로-전환하기]

 

그래서 std::cout 은 포기하고 printf나 쓰라고 하는건가?

그런데 rtti 까지 사용하지 않으면 cpp를 쓰는 이유가 머가 남지 -ㅁ-?

'embeded > Cortex-M3 STM' 카테고리의 다른 글

mbed + stm32cube hal...?  (0) 2026.02.23
Mbed studio on ubuntu 22.04  (0) 2026.02.23
stm32 rtc tamper  (0) 2026.01.29
stm32f103 rtc backup register  (0) 2026.01.29
stm32 hal rcc flag  (0) 2026.01.27
Posted by 구차니
embeded/Cortex-M3 STM2026. 1. 29. 15:48

pc13번 언급이 있어서 확인해보니 RTC_OUT / RTC_TAMPER로 설정이 가능하다.

 

Tamper를 활성화 하면 RTC_OUT 에서 RTC Output on the Tamper pin이 사용 불가능해진다.

 

Tamper는 인터럽트가 있는걸 봐서는.. 일종의 input 으로 설정되나보다.

 

rtc_Tamper를 rtc out으로 쓰지 않으면, 기본으로 tamper는 disble 되는 듯

stm32f1xx_hal_rtc.c

  *** Tamper configuration ***
  ============================
  [..]
    (+) Enable the RTC Tamper and configure the Tamper Level using the
        HAL_RTCEx_SetTamper() function. You can configure RTC Tamper with interrupt
        mode using HAL_RTCEx_SetTamper_IT() function.
    (+) The TAMPER1 alternate function can be mapped to PC13


/**
  * @brief  Initializes the RTC peripheral
  * @param  hrtc   pointer to a RTC_HandleTypeDef structure that contains
  *                the configuration information for RTC.
  * @retval HAL status
  */
HAL_StatusTypeDef HAL_RTC_Init(RTC_HandleTypeDef *hrtc)
{
  /* Set Initialization mode */
  if (RTC_EnterInitMode(hrtc) != HAL_OK)
  {
    /* Set RTC state */
    hrtc->State = HAL_RTC_STATE_ERROR;

    return HAL_ERROR;
  }
  else
  {
    /* Clear Flags Bits */
    CLEAR_BIT(hrtc->Instance->CRL, (RTC_FLAG_OW | RTC_FLAG_ALRAF | RTC_FLAG_SEC));

    if (hrtc->Init.OutPut != RTC_OUTPUTSOURCE_NONE)
    {
      /* Disable the selected Tamper pin */
      CLEAR_BIT(BKP->CR, BKP_CR_TPE);
    }

    /* Set the signal which will be routed to RTC Tamper pin*/
    MODIFY_REG(BKP->RTCCR, (BKP_RTCCR_CCO | BKP_RTCCR_ASOE | BKP_RTCCR_ASOS), hrtc->Init.OutPut);
  }
}

 

stm32f1xx_hal_rtc.h

/** @defgroup RTC_output_source_to_output_on_the_Tamper_pin Output source to output on the Tamper pin
  * @{
  */

#define RTC_OUTPUTSOURCE_NONE               0x00000000U                       /*!< No output on the TAMPER pin  */
#define RTC_OUTPUTSOURCE_CALIBCLOCK         BKP_RTCCR_CCO                     /*!< RTC clock with a frequency divided by 64 on the TAMPER pin  */
#define RTC_OUTPUTSOURCE_ALARM              BKP_RTCCR_ASOE                    /*!< Alarm pulse signal on the TAMPER pin  */
#define RTC_OUTPUTSOURCE_SECOND             (BKP_RTCCR_ASOS | BKP_RTCCR_ASOE) /*!< Second pulse signal on the TAMPER pin  */

'embeded > Cortex-M3 STM' 카테고리의 다른 글

Mbed studio on ubuntu 22.04  (0) 2026.02.23
stm32f103c8t6 cpp std::cout 실패  (0) 2026.02.18
stm32f103 rtc backup register  (0) 2026.01.29
stm32 hal rcc flag  (0) 2026.01.27
stm32 ivt  (0) 2026.01.27
Posted by 구차니
embeded/Cortex-M3 STM2026. 1. 29. 14:39

rtc에 백업 레지스터라고 해서, software reset 걸려도 살아남는게 있다고 ai가 이야기 하길래 검색

rtc 활성화 하고나니 아래 초기화 코드가 추가되서 따라가서 보면 평범한(?) HAL_RTC_Init() 이 있고

/**
  * @brief RTC Initialization Function
  * @param None
  * @retval None
  */
static void MX_RTC_Init(void)
{

  /* USER CODE BEGIN RTC_Init 0 */

  /* USER CODE END RTC_Init 0 */

  /* USER CODE BEGIN RTC_Init 1 */

  /* USER CODE END RTC_Init 1 */

  /** Initialize RTC Only
  */
  hrtc.Instance = RTC;
  hrtc.Init.AsynchPrediv = RTC_AUTO_1_SECOND;
  hrtc.Init.OutPut = RTC_OUTPUTSOURCE_ALARM;
  if (HAL_RTC_Init(&hrtc) != HAL_OK)
  {
    Error_Handler();
  }
  /* USER CODE BEGIN RTC_Init 2 */

  /* USER CODE END RTC_Init 2 */

}

 

HAL_RTC_MspInit()을 통해

stm32f1xx_hal_rtc.c

    (+) To write to the RTC Backup Data registers, use the HAL_RTCEx_BKUPWrite()
        function.
    (+) To read the RTC Backup Data registers, use the HAL_RTCEx_BKUPRead()
        function.

/**
  * @brief  Initializes the RTC peripheral
  * @param  hrtc   pointer to a RTC_HandleTypeDef structure that contains
  *                the configuration information for RTC.
  * @retval HAL status
  */
HAL_StatusTypeDef HAL_RTC_Init(RTC_HandleTypeDef *hrtc)
{
  uint32_t prescaler = 0U;
  /* Check input parameters */
  if (hrtc == NULL)
  {
    return HAL_ERROR;
  }

  /* Check the parameters */
  assert_param(IS_RTC_ALL_INSTANCE(hrtc->Instance));
  assert_param(IS_RTC_CALIB_OUTPUT(hrtc->Init.OutPut));
  assert_param(IS_RTC_ASYNCH_PREDIV(hrtc->Init.AsynchPrediv));

#if (USE_HAL_RTC_REGISTER_CALLBACKS == 1)
#else
  if (hrtc->State == HAL_RTC_STATE_RESET)
  {
    /* Allocate lock resource and initialize it */
    hrtc->Lock = HAL_UNLOCKED;

    /* Initialize RTC MSP */
    HAL_RTC_MspInit(hrtc);
  }
}

/**
  * @brief  Initializes the RTC MSP.
  * @param  hrtc   pointer to a RTC_HandleTypeDef structure that contains
  *                the configuration information for RTC.
  * @retval None
  */
__weak void HAL_RTC_MspInit(RTC_HandleTypeDef *hrtc)
{
  /* Prevent unused argument(s) compilation warning */
  UNUSED(hrtc);
  /* NOTE : This function Should not be modified, when the callback is needed,
            the HAL_RTC_MspInit could be implemented in the user file
   */
}

 

백업 레지스터에 접근할수 있도록 풀어준다.
Core/Src/stm32f1xx_hal_msp.c

/**
* @brief RTC MSP Initialization
* This function configures the hardware resources used in this example
* @param hrtc: RTC handle pointer
* @retval None
*/
void HAL_RTC_MspInit(RTC_HandleTypeDef* hrtc)
{
  if(hrtc->Instance==RTC)
  {
  /* USER CODE BEGIN RTC_MspInit 0 */

  /* USER CODE END RTC_MspInit 0 */
    HAL_PWR_EnableBkUpAccess();
    /* Enable BKP CLK enable for backup registers */
    __HAL_RCC_BKP_CLK_ENABLE();
    /* Peripheral clock enable */
    __HAL_RCC_RTC_ENABLE();
  /* USER CODE BEGIN RTC_MspInit 1 */

  /* USER CODE END RTC_MspInit 1 */

  }

}

 

CR_DBP_BB 라는 레지스터에 활성화 해주는것 코드 느낌. 무슨 레지스터인지 따라가긴 귀찮으니 패스

stm32f1xx_hal_pwr.c

/**
  * @brief  Enables access to the backup domain (RTC registers, RTC
  *         backup data registers ).
  * @note   If the HSE divided by 128 is used as the RTC clock, the
  *         Backup Domain Access should be kept enabled.
  * @retval None
  */
void HAL_PWR_EnableBkUpAccess(void)
{
  /* Enable access to RTC and backup registers */
  *(__IO uint32_t *) CR_DBP_BB = (uint32_t)ENABLE;
}

/**
  * @brief  Disables access to the backup domain (RTC registers, RTC
  *         backup data registers).
  * @note   If the HSE divided by 128 is used as the RTC clock, the
  *         Backup Domain Access should be kept enabled.
  * @retval None
  */
void HAL_PWR_DisableBkUpAccess(void)
{
  /* Disable access to RTC and backup registers */
  *(__IO uint32_t *) CR_DBP_BB = (uint32_t)DISABLE;
}

 

아무튼 백업레지스터 접근이 허용되면

HAL_RTCEx_BKUPWrite() 를 통해 쓰고

HAL_RTCEx_BKUPRead() 를 통해 읽을 수 있다.

stm32f1xx_hal_rtc_ex.c

/**
  * @brief  Writes a data in a specified RTC Backup data register.
  * @param  hrtc: pointer to a RTC_HandleTypeDef structure that contains
  *                the configuration information for RTC.
  * @param  BackupRegister: RTC Backup data Register number.
  *          This parameter can be: RTC_BKP_DRx where x can be from 1 to 10 (or 42) to
  *                                 specify the register (depending devices).
  * @param  Data: Data to be written in the specified RTC Backup data register.
  * @retval None
  */
void HAL_RTCEx_BKUPWrite(RTC_HandleTypeDef *hrtc, uint32_t BackupRegister, uint32_t Data)
{
  uint32_t tmp = 0U;

  /* Prevent unused argument(s) compilation warning */
  UNUSED(hrtc);

  /* Check the parameters */
  assert_param(IS_RTC_BKP(BackupRegister));

  tmp = (uint32_t)BKP_BASE;
  tmp += (BackupRegister * 4U);

  *(__IO uint32_t *) tmp = (Data & BKP_DR1_D);
}

/**
  * @brief  Reads data from the specified RTC Backup data Register.
  * @param  hrtc: pointer to a RTC_HandleTypeDef structure that contains
  *                the configuration information for RTC.
  * @param  BackupRegister: RTC Backup data Register number.
  *          This parameter can be: RTC_BKP_DRx where x can be from 1 to 10 (or 42) to
  *                                 specify the register (depending devices).
  * @retval Read value
  */
uint32_t HAL_RTCEx_BKUPRead(RTC_HandleTypeDef *hrtc, uint32_t BackupRegister)
{
  uint32_t backupregister = 0U;
  uint32_t pvalue = 0U;

  /* Prevent unused argument(s) compilation warning */
  UNUSED(hrtc);

  /* Check the parameters */
  assert_param(IS_RTC_BKP(BackupRegister));

  backupregister = (uint32_t)BKP_BASE;
  backupregister += (BackupRegister * 4U);

  pvalue = (*(__IO uint32_t *)(backupregister)) & BKP_DR1_D;

  /* Read the specified register */
  return pvalue;
}

 

F103의 경우 10개가 있나 보다. 그런데 BKP_DRn_D 마스크는 왜 전부 0xFFFF 으로 동일한걸까?

stm32f103xb.h

/******************************************************************************/
/*                                                                            */
/*                            Backup registers                                */
/*                                                                            */
/******************************************************************************/

/*******************  Bit definition for BKP_DR1 register  ********************/
#define BKP_DR1_D_Pos                       (0U)                               
#define BKP_DR1_D_Msk                       (0xFFFFUL << BKP_DR1_D_Pos)         /*!< 0x0000FFFF */
#define BKP_DR1_D                           BKP_DR1_D_Msk                      /*!< Backup data */

/*******************  Bit definition for BKP_DR2 register  ********************/
#define BKP_DR2_D_Pos                       (0U)                               
#define BKP_DR2_D_Msk                       (0xFFFFUL << BKP_DR2_D_Pos)         /*!< 0x0000FFFF */
#define BKP_DR2_D                           BKP_DR2_D_Msk                      /*!< Backup data */

/*******************  Bit definition for BKP_DR3 register  ********************/
#define BKP_DR3_D_Pos                       (0U)                               
#define BKP_DR3_D_Msk                       (0xFFFFUL << BKP_DR3_D_Pos)         /*!< 0x0000FFFF */
#define BKP_DR3_D                           BKP_DR3_D_Msk                      /*!< Backup data */

/*******************  Bit definition for BKP_DR4 register  ********************/
#define BKP_DR4_D_Pos                       (0U)                               
#define BKP_DR4_D_Msk                       (0xFFFFUL << BKP_DR4_D_Pos)         /*!< 0x0000FFFF */
#define BKP_DR4_D                           BKP_DR4_D_Msk                      /*!< Backup data */

/*******************  Bit definition for BKP_DR5 register  ********************/
#define BKP_DR5_D_Pos                       (0U)                               
#define BKP_DR5_D_Msk                       (0xFFFFUL << BKP_DR5_D_Pos)         /*!< 0x0000FFFF */
#define BKP_DR5_D                           BKP_DR5_D_Msk                      /*!< Backup data */

/*******************  Bit definition for BKP_DR6 register  ********************/
#define BKP_DR6_D_Pos                       (0U)                               
#define BKP_DR6_D_Msk                       (0xFFFFUL << BKP_DR6_D_Pos)         /*!< 0x0000FFFF */
#define BKP_DR6_D                           BKP_DR6_D_Msk                      /*!< Backup data */

/*******************  Bit definition for BKP_DR7 register  ********************/
#define BKP_DR7_D_Pos                       (0U)                               
#define BKP_DR7_D_Msk                       (0xFFFFUL << BKP_DR7_D_Pos)         /*!< 0x0000FFFF */
#define BKP_DR7_D                           BKP_DR7_D_Msk                      /*!< Backup data */

/*******************  Bit definition for BKP_DR8 register  ********************/
#define BKP_DR8_D_Pos                       (0U)                               
#define BKP_DR8_D_Msk                       (0xFFFFUL << BKP_DR8_D_Pos)         /*!< 0x0000FFFF */
#define BKP_DR8_D                           BKP_DR8_D_Msk                      /*!< Backup data */

/*******************  Bit definition for BKP_DR9 register  ********************/
#define BKP_DR9_D_Pos                       (0U)                               
#define BKP_DR9_D_Msk                       (0xFFFFUL << BKP_DR9_D_Pos)         /*!< 0x0000FFFF */
#define BKP_DR9_D                           BKP_DR9_D_Msk                      /*!< Backup data */

/*******************  Bit definition for BKP_DR10 register  *******************/
#define BKP_DR10_D_Pos                      (0U)                               
#define BKP_DR10_D_Msk                      (0xFFFFUL << BKP_DR10_D_Pos)        /*!< 0x0000FFFF */
#define BKP_DR10_D                          BKP_DR10_D_Msk                     /*!< Backup data */

#define RTC_BKP_NUMBER 10

 

[링크 : https://fuhehe.tistory.com/27]

 

1.9 Backup registers
RTC_BKPxR, where x=0 to n backup registers (80 bytes), are reset when a tamper detection event occurs. These registers are powered-on by VBAT when VDD is switched off, so that they are not reset by a system reset, and their contents remain valid when the device operates in low-power mode.
Note: The number “n” of backup registers depends on the product. Please refer to Table 15: Advanced RTC features.

[링크 : https://www.st.com/resource/en/application_note/an3371-using-the-hardware-realtime-clock-rtc-in-stm32-f0-f2-f3-f4-and-l1-series-of-mcus-stmicroelectronics.pdf]

 

보안상 문제가 발생하면 그걸 TAMP 라는것 같은데, 아무튼 그 때는 백업 레지스터가 초기화 된다고 한다.

 

[링크 : https://www.st.com/resource/en/product_training/STM32MP1-Security-Tamper_TAMP.pdf]

'embeded > Cortex-M3 STM' 카테고리의 다른 글

stm32f103c8t6 cpp std::cout 실패  (0) 2026.02.18
stm32 rtc tamper  (0) 2026.01.29
stm32 hal rcc flag  (0) 2026.01.27
stm32 ivt  (0) 2026.01.27
bluepill stm32f103c8t6 USB CDC 리셋이후 안되는 문제  (0) 2026.01.27
Posted by 구차니
embeded/Cortex-M3 STM2026. 1. 27. 18:26

대충 보니

BOR Reset(brown out detection reset - 전압 강하로 인한 재기동)

PIN Reset (NRST pin reset - 하드웨어 리셋)

POR Reset (Power on Reset)

SFT Reset (Software Reset)

IWDG1 Reset (Independent Watchdog reset)

WWDG Reset (window Watchdog reset)

#define RCC_FLAG_BORRST                ((uint8_t)0x95)
#define RCC_FLAG_PINRST                ((uint8_t)0x96)
#define RCC_FLAG_PORRST                ((uint8_t)0x97)
#define RCC_FLAG_SFTRST                ((uint8_t)0x98)
#define RCC_FLAG_IWDG1RST              ((uint8_t)0x9A)
#define RCC_FLAG_WWDG1RST              ((uint8_t)0x9C)
#define RCC_FLAG_LPWR1RST              ((uint8_t)0x9E)
#define RCC_FLAG_LPWR2RST              ((uint8_t)0x9F)

[링크 : https://community.st.com/t5/stm32-mcus-products/software-reset-flag-sftrstf-in-rcc-csr-register-what-source/td-p/544463]

[링크 : https://community.st.com/t5/stm32-mcus-products/stm32f407-spurious-reset-rcc-flag-pinrst/td-p/147931]

 

저전력 모드 보안 리셋은 멀까?

3.7.2 System reset sources
Power-on reset initializes all registers while system reset reinitializes the system except for
the debug, part of the RCC and power controller status registers, as well as the backup
power domain.
A system reset is generated in the following cases:
• Power-on reset (pwr_por_rst)
• Brownout reset
• Low level on NRST pin (external reset)
• Independent watchdog 1 (from D1 domain)
• Independent watchdog 2 (from D2 domain)
• Window watchdog 1 (from D1 domain)
• Window watchdog 2 (from D2 domain)
• Software reset
• Low-power mode security reset
• Exit from Standby

[링크 :https://www.st.com/resource/en/datasheet/stm32h757ai.pdf]

 

stop / standby mode 오갈때 뜨는 듯?

A low-power-mode security reset (which is generated when Stop or Standby mode is entered but is prohibited by the option byte configuration)

[링크 : https://www.st.com/content/ccc/resource/training/technical/product_training/group0/81/96/f3/1a/55/d9/40/52/STM32H7-System-Reset_and_clock_control_RCC/files/STM32H7-System-Reset_and_clock_control_RCC.pdf/_jcr_content/translations/en.STM32H7-System-Reset_and_clock_control_RCC.pdf]

 

'embeded > Cortex-M3 STM' 카테고리의 다른 글

stm32 rtc tamper  (0) 2026.01.29
stm32f103 rtc backup register  (0) 2026.01.29
stm32 ivt  (0) 2026.01.27
bluepill stm32f103c8t6 USB CDC 리셋이후 안되는 문제  (0) 2026.01.27
stm32cubeide 2.0 에서 ioc 파일이 생성 안되네?  (0) 2026.01.11
Posted by 구차니
embeded/Cortex-M3 STM2026. 1. 27. 17:08

startup_stm32f103retx.s

  .syntax unified
  .cpu cortex-m3
  .fpu softvfp
  .thumb

.global g_pfnVectors
.global Default_Handler

/**
 * @brief  This is the code that gets called when the processor first
 *          starts execution following a reset event. Only the absolutely
 *          necessary set is performed, after which the application
 *          supplied main() routine is called.
 * @param  None
 * @retval : None
*/

  .section .text.Reset_Handler
  .weak Reset_Handler
  .type Reset_Handler, %function
Reset_Handler:


/******************************************************************************
*
* The minimal vector table for a Cortex M3.  Note that the proper constructs
* must be placed on this to ensure that it ends up at physical address
* 0x0000.0000.
*
******************************************************************************/
  .section .isr_vector,"a",%progbits
  .type g_pfnVectors%object
  .size g_pfnVectors, .-g_pfnVectors


g_pfnVectors:

  .word _estack
  .word Reset_Handler
  .word NMI_Handler
  .word HardFault_Handler
  .word MemManage_Handler
  .word BusFault_Handler
  .word UsageFault_Handler
  .word 0
  .word 0
  .word 0
  .word 0
  .word SVC_Handler
  .word DebugMon_Handler
  .word 0
  .word PendSV_Handler
  .word SysTick_Handler
  .word WWDG_IRQHandler
  .word PVD_IRQHandler
  .word TAMPER_IRQHandler
  .word RTC_IRQHandler
  .word FLASH_IRQHandler
  .word RCC_IRQHandler
  .word EXTI0_IRQHandler
  .word EXTI1_IRQHandler
  .word EXTI2_IRQHandler
  .word EXTI3_IRQHandler
  .word EXTI4_IRQHandler
  .word DMA1_Channel1_IRQHandler
  .word DMA1_Channel2_IRQHandler
  .word DMA1_Channel3_IRQHandler
  .word DMA1_Channel4_IRQHandler
  .word DMA1_Channel5_IRQHandler
  .word DMA1_Channel6_IRQHandler
  .word DMA1_Channel7_IRQHandler
  .word ADC1_2_IRQHandler
  .word USB_HP_CAN1_TX_IRQHandler
  .word USB_LP_CAN1_RX0_IRQHandler
  .word CAN1_RX1_IRQHandler
  .word CAN1_SCE_IRQHandler
  .word EXTI9_5_IRQHandler
  .word TIM1_BRK_IRQHandler
  .word TIM1_UP_IRQHandler
  .word TIM1_TRG_COM_IRQHandler
  .word TIM1_CC_IRQHandler
  .word TIM2_IRQHandler
  .word TIM3_IRQHandler
  .word TIM4_IRQHandler
  .word I2C1_EV_IRQHandler
  .word I2C1_ER_IRQHandler
  .word I2C2_EV_IRQHandler
  .word I2C2_ER_IRQHandler
  .word SPI1_IRQHandler
  .word SPI2_IRQHandler
  .word USART1_IRQHandler
  .word USART2_IRQHandler
  .word USART3_IRQHandler
  .word EXTI15_10_IRQHandler
  .word RTC_Alarm_IRQHandler
  .word USBWakeUp_IRQHandler
  .word TIM8_BRK_IRQHandler
  .word TIM8_UP_IRQHandler
  .word TIM8_TRG_COM_IRQHandler
  .word TIM8_CC_IRQHandler
  .word ADC3_IRQHandler
  .word FSMC_IRQHandler
  .word SDIO_IRQHandler
  .word TIM5_IRQHandler
  .word SPI3_IRQHandler
  .word UART4_IRQHandler
  .word UART5_IRQHandler
  .word TIM6_IRQHandler
  .word TIM7_IRQHandler
  .word DMA2_Channel1_IRQHandler
  .word DMA2_Channel2_IRQHandler
  .word DMA2_Channel3_IRQHandler
  .word DMA2_Channel4_5_IRQHandler
  .word 0
  .word 0
  .word 0
  .word 0
  .word 0
  .word 0
  .word 0
  .word 0
  .word 0
  .word 0
  .word 0
  .word 0
  .word 0
  .word 0
  .word 0
  .word 0
  .word 0
  .word 0
  .word 0
  .word 0
  .word 0
  .word 0
  .word 0
  .word 0
  .word 0
  .word 0
  .word 0
  .word 0
  .word 0
  .word 0
  .word 0
  .word 0
  .word 0
  .word 0
  .word 0
  .word 0
  .word 0
  .word 0
  .word 0
  .word 0
  .word 0
  .word 0
  .word 0
  .word 0
  .word BootRAM       /* @0x1E0. This is for boot in RAM mode for
                         STM32F10x High Density devices. */

 

STM32F103RETX_FLASH.ld

/* Memories definition */
MEMORY
{
  RAM    (xrw)    : ORIGIN = 0x20000000,   LENGTH = 64K
  FLASH    (rx)    : ORIGIN = 0x8000000,   LENGTH = 512K
}

/* Sections */
SECTIONS
{
  /* The startup code into "FLASH" Rom type memory */
  .isr_vector :
  {
    . = ALIGN(4);
    KEEP(*(.isr_vector)) /* Startup code */
    . = ALIGN(4);
  } >FLASH

  /* The program code and other data into "FLASH" Rom type memory */
  .text :
  {
    . = ALIGN(4);
    *(.text)           /* .text sections (code) */
    *(.text*)          /* .text* sections (code) */
    *(.glue_7)         /* glue arm to thumb code */
    *(.glue_7t)        /* glue thumb to arm code */
    *(.eh_frame)

    KEEP (*(.init))
    KEEP (*(.fini))

    . = ALIGN(4);
    _etext = .;        /* define a global symbols at end of code */
  } >FLASH

  /* Constant data into "FLASH" Rom type memory */
  .rodata :
  {
    . = ALIGN(4);
    *(.rodata)         /* .rodata sections (constants, strings, etc.) */
    *(.rodata*)        /* .rodata* sections (constants, strings, etc.) */
    . = ALIGN(4);
  } >FLASH
}

 

$ readelf -a test.elf 
ELF Header:
  Magic:   7f 45 4c 46 01 01 01 00 00 00 00 00 00 00 00 00 
  Class:                             ELF32
  Data:                              2's complement, little endian
  Version:                           1 (current)
  OS/ABI:                            UNIX - System V
  ABI Version:                       0
  Type:                              EXEC (Executable file)
  Machine:                           ARM
  Version:                           0x1
  Entry point address:               0x8009499
  Start of program headers:          52 (bytes into file)
  Start of section headers:          1299152 (bytes into file)
  Flags:                             0x5000200, Version5 EABI, soft-float ABI
  Size of this header:               52 (bytes)
  Size of program headers:           32 (bytes)
  Number of program headers:         4
  Size of section headers:           40 (bytes)
  Number of section headers:         26
  Section header string table index: 25

Section Headers:
  [Nr] Name              Type            Addr     Off    Size   ES Flg Lk Inf Al
  [ 0]                   NULL            00000000 000000 000000 00      0   0  0
  [ 1] .isr_vector       PROGBITS        08000000 001000 0001e4 00   A  0   0  1
  [ 2] .text             PROGBITS        080001e8 0011e8 012144 00  AX  0   0  8
  [ 3] .rodata           PROGBITS        08012330 013330 002338 00   A  0   0  8
  [ 4] .ARM.extab        PROGBITS        08014668 01622c 000000 00   W  0   0  1
  [ 5] .ARM              ARM_EXIDX       08014668 015668 000008 00  AL  2   0  4
  [ 6] .preinit_array    PREINIT_ARRAY   08014670 01622c 000000 04  WA  0   0  1
  [ 7] .init_array       INIT_ARRAY      08014670 015670 000004 04   A  0   0  4
  [ 8] .fini_array       FINI_ARRAY      08014674 015674 000004 04   A  0   0  4
  [ 9] .data             PROGBITS        20000000 016000 00022c 00  WA  0   0  4
  [10] .bss              NOBITS          20000230 016230 001b44 00  WA  0   0  8
  [11] ._user_heap_stack NOBITS          20001d74 016d74 000604 00  WA  0   0  1
  [12] .ARM.attributes   ARM_ATTRIBUTES  00000000 01622c 000029 00      0   0  1
  [13] .debug_info       PROGBITS        00000000 016255 01da16 00      0   0  1
  [14] .debug_abbrev     PROGBITS        00000000 033c6b 0056f5 00      0   0  1
  [15] .debug_aranges    PROGBITS        00000000 039360 001bf8 00      0   0  8
  [16] .debug_rnglists   PROGBITS        00000000 03af58 0015ba 00      0   0  1
  [17] .debug_macro      PROGBITS        00000000 03c512 0206fd 00      0   0  1
  [18] .debug_line       PROGBITS        00000000 05cc0f 022fc5 00      0   0  1
  [19] .debug_str        PROGBITS        00000000 07fbd4 0aae1c 01  MS  0   0  1
  [20] .comment          PROGBITS        00000000 12a9f0 000043 01  MS  0   0  1
  [21] .debug_frame      PROGBITS        00000000 12aa34 008440 00      0   0  4
  [22] .debug_line_str   PROGBITS        00000000 132e74 000064 01  MS  0   0  1
  [23] .symtab           SYMTAB          00000000 132ed8 0072e0 10     24 1208  4
  [24] .strtab           STRTAB          00000000 13a1b8 002ffa 00      0   0  1
  [25] .shstrtab         STRTAB          00000000 13d1b2 00011c 00      0   0  1
Key to Flags:
  W (write), A (alloc), X (execute), M (merge), S (strings), I (info),
  L (link order), O (extra OS processing required), G (group), T (TLS),
  C (compressed), x (unknown), o (OS specific), E (exclude),
  D (mbind), y (purecode), p (processor specific)

There are no section groups in this file.

Program Headers:
  Type           Offset   VirtAddr   PhysAddr   FileSiz MemSiz  Flg Align
  LOAD           0x001000 0x08000000 0x08000000 0x14678 0x14678 R E 0x1000
  LOAD           0x016000 0x20000000 0x08014678 0x0022c 0x0022c RW  0x1000
  LOAD           0x000230 0x20000230 0x080148a4 0x00000 0x01b44 RW  0x1000
  LOAD           0x000d74 0x20001d74 0x080148a4 0x00000 0x00604 RW  0x1000

 Section to Segment mapping:
  Segment Sections...
   00     .isr_vector .text .rodata .ARM .init_array .fini_array 
   01     .data 
   02     .bss 
   03     ._user_heap_stack 

There is no dynamic section in this file.

There are no relocations in this file.

Unwind section '.ARM' at offset 0x15668 contains 1 entry:

0x8000228 <strlen>: 0x1 [cantunwind]


Symbol table '.symtab' contains 1838 entries:
   Num:    Value  Size Type    Bind   Vis      Ndx Name
     0: 00000000     0 NOTYPE  LOCAL  DEFAULT  UND 
     1: 08000000     0 SECTION LOCAL  DEFAULT    1 .isr_vector
     2: 080001e8     0 SECTION LOCAL  DEFAULT    2 .text
     3: 08012330     0 SECTION LOCAL  DEFAULT    3 .rodata
     4: 08014668     0 SECTION LOCAL  DEFAULT    4 .ARM.extab
     5: 08014668     0 SECTION LOCAL  DEFAULT    5 .ARM
     6: 08014670     0 SECTION LOCAL  DEFAULT    6 .preinit_array
     7: 08014670     0 SECTION LOCAL  DEFAULT    7 .init_array
     8: 08014674     0 SECTION LOCAL  DEFAULT    8 .fini_array
     9: 20000000     0 SECTION LOCAL  DEFAULT    9 .data
    10: 20000230     0 SECTION LOCAL  DEFAULT   10 .bss
    11: 20001d74     0 SECTION LOCAL  DEFAULT   11 ._user_heap_stack
(많아서 생략)

No version information found in this file.
Attribute Section: aeabi
File Attributes
  Tag_CPU_name: "7-M"
  Tag_CPU_arch: v7
  Tag_CPU_arch_profile: Microcontroller
  Tag_THUMB_ISA_use: Thumb-2
  Tag_ABI_PCS_wchar_t: 4
  Tag_ABI_FP_denormal: Needed
  Tag_ABI_FP_exceptions: Needed
  Tag_ABI_FP_number_model: IEEE 754
  Tag_ABI_align_needed: 8-byte
  Tag_ABI_enum_size: small
  Tag_CPU_unaligned_access: v6

 

 

[링크 : https://hackmd.io/@SgyGB0h2QGWBfbHp9n_ArQ/BygAD3fU_]

 

플래시를 읽어보면 

0x8000000 은 _estack 값 같고

0x8000004 는 Reset_Handler의 주소 같다. 그런데 왜 1로 끝나지..? 4바이트 정렬 안하나?

 

근처에 읽어보면 모르겠...다(!)

 

NMI_Handler로 보는데 0x0800 7F01 인데 왜 1로 끝나냐도 모르겠고, 본다고 기계어가 어셈으로 눈에 들어오는것도 아니고..

[링크 : https://fuhehe.tistory.com/13]

 

벡터위치 변경하는 것을 요약하면 



1. 링커스크립트에서 인터럽트벡터가 있는 .isr_vector 섹션의 위치를 수정

2. SystemInit() 함수에서 SCB->VTOR 레지스터를 변경하고자 하는 섹션의 위치로 수정

[링크 : https://m.blog.naver.com/chcbaram/222580261732]

 

암튼 object는 굳이 표현하면 array 나 variable 이라는데

딱히 pointer라는 개념이.. 어셈에 없을리가 없는데 멀까.

For ELF targets, the .type directive is used like this:

.type name , type description
This sets the type of symbol name to be either a function symbol or an object symbol. There are five different syntaxes supported for the type description field, in order to provide compatibility with various other assemblers.

Because some of the characters used in these syntaxes (such as ‘@’ and ‘#’) are comment characters for some architectures, some of the syntaxes below do not work on all architectures. The first variant will be accepted by the GNU assembler on all architectures so that variant should be used for maximum portability, if you do not need to assemble your code with other assemblers.

The syntaxes supported are:

  .type <name> STT_<TYPE_IN_UPPER_CASE>
  .type <name>,#<type>
  .type <name>,@<type>
  .type <name>,%<type>
  .type <name>,"<type>"
The types supported are:

STT_FUNC
function
Mark the symbol as being a function name.

STT_GNU_IFUNC
gnu_indirect_function
Mark the symbol as an indirect function when evaluated during reloc processing. (This is only supported on assemblers targeting GNU systems).

STT_OBJECT
object
Mark the symbol as being a data object.

[링크 : https://sourceware.org/binutils/docs/as/Type.html?utm_source=chatgpt.com]

 

The .type directive allows you to tell the assembler what type a symbol is. Most of the time we just use %function and %object.

                    .type               hexTable,%object

...or...

                    .type               qsort,%function

[링크 : https://developer.arm.com/community/arm-community-blogs/b/architectures-and-processors-blog/posts/useful-assembler-directives-and-macros-for-the-gnu-assembler]

[링크 : https://stackoverflow.com/questions/70061418/what-does-the-object-and-object-mean-in-this-inline-assembly?utm_source=chatgpt.com]

Posted by 구차니
embeded/Cortex-M3 STM2026. 1. 27. 11:35

USB 에서 장치를 다시 인식시키려면, D+ 라인을 풀다운 해주어야 한다고 한다.

그래서 reset 누르고 재기동 하면 ACM이 살아는 있지만 정상적으로 작동을 하지 않는건가?

If you reset the bluepill you need to pull down the D+ line for several milliseconds to let know the host that it has to start the enumeration process.

[링크 : https://stackoverflow.com/questions/54939948/stm32-usb-cdc-after-hardware-reset]

 

USB_DEVICE/App/usb_device.c 에 있는 MX_USB_DEVICE_Init() 을 아래와 같이 추가해준다.

그러면 일정 시간 이후에 다시 붙으면서 /dev/ttyACM0로 데이터가 출력된다.

void MX_USB_DEVICE_Init(void)
{
  /* USER CODE BEGIN USB_DEVICE_Init_PreTreatment */

  /* Rendering hardware reset harmless (no need to replug USB cable): */
  GPIO_InitTypeDef GPIO_InitStruct = {0};

  /* GPIO Ports Clock Enable */
  __HAL_RCC_GPIOA_CLK_ENABLE();

  /*Configure GPIO pin Output Level */
  HAL_GPIO_WritePin(GPIOA, GPIO_PIN_12, GPIO_PIN_RESET);

  /*Configure GPIO pin : PA12, a.k.a. USB_DP */
  GPIO_InitStruct.Pin = GPIO_PIN_12;
  GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
  GPIO_InitStruct.Pull = GPIO_NOPULL;
  GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
  HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);

  HAL_Delay(5);
  /* Hardware reset rendered harmless! */

  /* USER CODE END USB_DEVICE_Init_PreTreatment */
  ...
}

[링크 : https://stackoverflow.com/questions/54939948/stm32-usb-cdc-after-hardware-reset]

'embeded > Cortex-M3 STM' 카테고리의 다른 글

stm32 hal rcc flag  (0) 2026.01.27
stm32 ivt  (0) 2026.01.27
stm32cubeide 2.0 에서 ioc 파일이 생성 안되네?  (0) 2026.01.11
stm32cubeide에 x-cube-ai 설치  (0) 2026.01.06
stm32f103c9t6(bluepill) + stlinkv2 + cdc(vcp)  (0) 2026.01.05
Posted by 구차니