Since it works on the STM32F407, it's likely a hardware or configuration issue.
Try this out
Clock speed: Ensure the clock speed is set correctly for the STM32F031K6T6.
Pin mappings: Double-check that the pin mappings match the new hardware.
Peripheral configurations: Verify that the peripheral configurations (e.g., UART, PWM) are correct.
Power supply: Ensure the motor and MCU have sufficient power supply.
Debugging: Use a debugger or print statements to identify where the code gets stuck.