STM32L476RG Upload Failure "Open OCD init Failed"

I’m basically brand new to PlatformIO, and pretty new to embedded system development in general. I just yesterday installed PlatformIO on VSCode and tried uploading some test programs onto my STML476RG board. This worked for the first two uploads seamlessly, but suddenly after only a couple of uploads, it stopped working. I have searched through every related article on this website and stack overflow. I’ve tried unplugging/replugging, erasing the flash load over st-link utility, changing the upload to upload under reset, and restarting my PC. I’ll include the platformio.ini and my test code below.

platformio.ini:

[env:nucleo_l476rg]

platform = ststm32

board = nucleo_l476rg

framework = cmsis

upload_protocol = stlink

main.cpp:

#include “stm32l476xx.h”

int main(){
RCC->AHB2ENR |= RCC_AHB2ENR_GPIOAEN;

GPIOA->MODER |= (GPIO_MODER_MODE5_0);
GPIOA->MODER &= (~GPIO_MODER_MODE5_1);
GPIOA->ODR |= GPIO_ODR_OD5;

while(1);

}

And this is the error I get when trying to upload:

Error: init mode failed (unable to connect to the target)
in procedure ‘program’
** OpenOCD init failed **
shutdown command invoked

*** [upload] Error 1

Any help would be greatly appreciated, because I’m at a total loss.

Can you upload again when you hold down the reset button of the Nucleo board, only releasing it very shortly before OpenOCD tries to access it during the upload? The timing might be tricky.

You can also verify easily check if your code is the point of failure by creating an Arduino project instead and see if you can repeadedly upload that.

That worked! Could you explain why it worked and if there’s any way to prevent having to do that for future uploads?

When you upload your code again, does it reproducibly fail to upload after that?

No, it’s consistently uploading now, I’m just curious as to the theory