Code Appears to reset and repeat before finishing on MKR Vidor 4000

Hardware: MKR Vidor 4000, MKR motor carrier
IDE: 1.8.13

I am trying to use my arduino to run a stepper motor. My arduino is hooked up to a stepper motor through an arduino brand motor shield. I do not believe that this problem is related to the hardware setup as I did not have any problems with this a month ago.

My first problem is that the code does not appear to run as written.

#include <Stepper.h>

const int stepsPerRevolution = 400;  // change this to fit the number of steps per revolution
// for your motor

// initialize the stepper library on pins 8 through 11:
Stepper myStepper(stepsPerRevolution, 2, 3, 4, 5);
boolean hasnotrun = true;

void setup() {
  // set the speed at 60 rpm:
  myStepper.setSpeed(60);
  // initialize the serial port:
  Serial.begin(9600);
  


}

void loop() {

  if(hasnotrun == true){
   hasnotrun = false;
    delay(2000);
    myStepper.step(200);
    delay(2000);
    myStepper.step(-200);  
  }
  
}

As I understand it, this code should initialize the stepper motor and set my flag variable to true. Then inside the loop section of the code it should check if the flag is true, set the flag to false and then run the motor clockwise and counterclockwise a little bit. This should result in the motor turning back and forth once and then stopping for good.

This is not what is happening. When I run this code, the motor runs only in one direction, stops for 2 seconds (from the delay line, I have varied the delay time to verify that this is the reason for the pause), and then repeats until power is cut. To troubleshoot I tried removing the first delay statement, this resulted in the motor spinning , stopping for a split second and then repeating. This leads me to believe that after my code hits the first myStepper.step line, the program is somehow resetting. I have tried about a dozen different methods of creating a flag variable to no avail but the program neither runs the entire loop, or stops after one run like it should based on the flag variable. This is my main problem.

My second problem is that I can only upload to my ardunio after pressing and holding the reset button. If I do not do this, the IDE tells me that there is no device on the port and no device shows up in the “port” option under tools. After reset another option appears under “port” and I am able to upload a single program.

I am not sure whether these two issues are related.

Any help is greatly appreciated.

Are you sure the power supply is strong enough?

Sounds like there is some kind of voltage or current spike, which resets the microcontroller, assuming you're right and it actually resets.

Maybe try a different usb cable, try using a powerful phone charger instead of your computer and then try powering it externally with a powerful power supply (5V on the 5V pin)...

EDIT: Never power it externally and from USB at the same time!