cancel
Showing results for 
Search instead for 
Did you mean: 

STM32F1 USB Crash if turn on optimisation

MichaelQuant
Visitor

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)

1 ACCEPTED SOLUTION

Accepted Solutions
MichaelQuant
Visitor

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

View solution in original post

2 REPLIES 2
Ghofrane GSOURI
ST Employee

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.

MichaelQuant
Visitor

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