STM32CubeMX will override code not included in user code comment brackets when changes are made to the hardware configuration. Please, only include code in vendor generated files as shown: // User Code Begin --- // place your code here // User Code End --- //