Skip to main content
Associate
September 11, 2025
Solved

STM32F1 USB Crash if turn on optimisation

  • September 11, 2025
  • 2 replies
  • 405 views

Hi, I use lasted available library’s and software Cube IDE and stm32f103 mcu. I create clear project with minimum required parameters for use usb MSD or COM, with using USB HAL, So I compile it and connect usb, device recognised and OS propose format it, all works correctly.
So the problem: if in settings project optimisation select any type not include “none” after programing device not recognised by OS if I connect it by usb. No meter what optimization level i select. In debug mode initialisation comes without return error, (OS still not recognized usb device)

Best answer by MichaelQuant

so I find solution, in file usbd_desc.c in function Get_SerialNum(void)

need to assign values ​​to variables or make it volatile and it fix problem

2 replies

Ghofrane GSOURI
Technical Moderator
September 12, 2025

Hello @MichaelQuant 

This issue is typically caused by compiler optimizations affecting timing, variable access, or interrupt handling—especially if shared variables are not declared as volatile. To resolve this, ensure all variables shared between main code and interrupts are declared volatile, check that all variables are properly initialized.  You can also set optimization to -O0 specifically for USB-related files (like usb_device.c and usbd_core.c) while keeping the rest of the project optimized. These steps should help maintain USB functionality across all optimization levels.

THX

Ghofrane

To give better visibility on the answered topics, please click on Accept as Solution on the reply which solved your issue or answered your question.
MichaelQuantAuthorBest answer
Associate
September 12, 2025

so I find solution, in file usbd_desc.c in function Get_SerialNum(void)

need to assign values ​​to variables or make it volatile and it fix problem