Step motor freezing arduino

I have 2 stepper motors connected to a CNC shield (that is connected to 12v) using drivers. The shield is connected to an arduino uno. The motors move based on the readings provided by the MPU6050 gyrosenzor. When i run the code without the step motors plugged in it works fine, but when the motors are connected it freezes at random times, usually a couple seconds in. Sometimes it runs without freezing but thats rare.

This is the code:

#include <Wire.h>
#include <MPU6050.h>

MPU6050 mpu;

// Motor pins
#define XstepPin 2
#define XdirPin 5
#define YstepPin 3
#define YdirPin 6
#define enable 8

// Thresholds (bice postavljeni nakon kalibracije)
float xThresholdLow;
float xThresholdHigh;
float yThresholdLow;
float yThresholdHigh;

// Step delay (microseconds)
const float filterFactor = 0.2;  // Smoothing factor (0.1-0.5)

// Variables for filtered readings
float filteredX = 0;
float filteredY = 0;

void setup() {
  Serial.begin(9600);
  
  // Initialize MPU6050
  while(!mpu.begin(MPU6050_SCALE_2000DPS, MPU6050_RANGE_2G)) {
    Serial.println("Could not find a valid MPU6050 sensor, check wiring!");
    delay(500);
  }

  // Motor control pins
  pinMode(XstepPin, OUTPUT);
  pinMode(XdirPin, OUTPUT);
  pinMode(YstepPin, OUTPUT);
  pinMode(YdirPin, OUTPUT);
  pinMode(enable, OUTPUT);
  digitalWrite(enable, LOW);

  // Kalibracija - citanje 10 puta i odredivanje min/max
  float minX = 1000, maxX = -1000;
  float minY = 1000, maxY = -1000;

  Serial.println("Kalibracija u toku...");
  for (int i = 0; i < 50; i++) {
    Vector acc = mpu.readNormalizeAccel();
    if (acc.XAxis < minX) minX = acc.XAxis;
    if (acc.XAxis > maxX) maxX = acc.XAxis;
    if (acc.YAxis < minY) minY = acc.YAxis;
    if (acc.YAxis > maxY) maxY = acc.YAxis;

    delay(100); // da se ne cita prebrzo
  }

  // Postavljanje granica (dodajemo mali margine ako želiš deadband)
  float margin = 0.05;  // opcioni "mrtvi prostor"
  xThresholdLow = minX - margin;
  xThresholdHigh = maxX + margin;
  yThresholdLow = minY - margin;
  yThresholdHigh = maxY + margin;

  // Inicijalni filter setup
  Vector normAccel = mpu.readNormalizeAccel();
  filteredX = normAccel.XAxis;
  filteredY = normAccel.YAxis;

  // Prikaz rezultata kalibracije
  Serial.println("Kalibracija završena.");
  Serial.print("xThresholdLow: "); Serial.println(xThresholdLow);
  Serial.print("xThresholdHigh: "); Serial.println(xThresholdHigh);
  Serial.print("yThresholdLow: "); Serial.println(yThresholdLow);
  Serial.print("yThresholdHigh: "); Serial.println(yThresholdHigh);
}

void loop() {
  // Read raw sensor data
  Vector normAccel = mpu.readNormalizeAccel();
  
  // Apply low-pass filter
  filteredX = filteredX * (1 - filterFactor) + normAccel.XAxis * filterFactor;
  filteredY = filteredY * (1 - filterFactor) + normAccel.YAxis * filterFactor;
  
  bool moveX = false;
  bool moveY = false;

  // X axis control
  if (filteredX < xThresholdLow) {
    digitalWrite(XdirPin, HIGH);
    moveX = true;
  } else if (filteredX > xThresholdHigh) {
    digitalWrite(XdirPin,LOW);
    moveX = true;
  }

  // Y axis control
  if (filteredY < yThresholdLow) {
    digitalWrite(YdirPin, LOW);
    moveY = true;
  } else if (filteredY > yThresholdHigh) {
    digitalWrite(YdirPin,HIGH);
    moveY = true;
  }

  // Execute movements
  if (moveX) {
    digitalWrite(XstepPin, HIGH);
    delayMicroseconds(10);
    digitalWrite(XstepPin, LOW);
  }

  if (moveY) {
    digitalWrite(YstepPin, HIGH);
    delayMicroseconds(10);
    digitalWrite(YstepPin, LOW);
  }

  // Speed control
  delayMicroseconds(300);

  // Debug output
  Serial.print("X: ");
  Serial.print(normAccel.XAxis);
  Serial.print(" Y: ");
  Serial.println(normAccel.YAxis);
}

Likely your power supply is not able to supply enough current to your motors causing arduino to reset.
To have anything better than a guess, you need to post your wiring, components and power supplies used on your setup.

12V BUT how much current?

When stepper motors are connected and running, they draw significant current, causing voltage dips or noise on the Arduino or MPU6050 supply line. The MPU6050 uses I2C, which is sensitive to electrical noise. Noise or undervoltage can cause the MPU6050 to stop responding or the Arduino to crash/freeze/reset. Place a 100µF electrolytic capacitor and a 0.1µF ceramic capacitor across VCC and GND of the MPU6050 breakout board. Also put a 470µF–1000µF capacitor across Arduino VCC and GND. This helps stabilize power and reduce spikes.
You can also make a 2-axis laser CNC Shield driver for Arduino Uno. You can download the gerber and BOM from here:

This is OP using a different account

How would you go about connecting it? MPU VCC is connected to 5v on the CNC shield, and MPU GND is connected to GND on CNC shield. Do i place both capacitors between VCC and GND parallel? If so does it matter which one is behind the other

I have 2 stepper motors connected to a CNC shield (that is connected to 12v) using drivers. The shield is connected to an arduino uno. The motors move based on the readings provided by the MPU6050 gyrosenzor. When i run the code without the step motors plugged in it works fine, but when the motors are connected it freezes at random times, usually a couple seconds in. Sometimes it runs without freezing but thats rare.

This is the code:

#include <Wire.h>
#include <MPU6050.h>

MPU6050 mpu;

// Motor pins
#define XstepPin 2
#define XdirPin 5
#define YstepPin 3
#define YdirPin 6
#define enable 8

// Thresholds (bice postavljeni nakon kalibracije)
float xThresholdLow;
float xThresholdHigh;
float yThresholdLow;
float yThresholdHigh;

// Step delay (microseconds)
const float filterFactor = 0.2;  // Smoothing factor (0.1-0.5)

// Variables for filtered readings
float filteredX = 0;
float filteredY = 0;

void setup() {
  Serial.begin(9600);
  
  // Initialize MPU6050
  while(!mpu.begin(MPU6050_SCALE_2000DPS, MPU6050_RANGE_2G)) {
    Serial.println("Could not find a valid MPU6050 sensor, check wiring!");
    delay(500);
  }

  // Motor control pins
  pinMode(XstepPin, OUTPUT);
  pinMode(XdirPin, OUTPUT);
  pinMode(YstepPin, OUTPUT);
  pinMode(YdirPin, OUTPUT);
  pinMode(enable, OUTPUT);
  digitalWrite(enable, LOW);

  // Kalibracija - citanje 10 puta i odredivanje min/max
  float minX = 1000, maxX = -1000;
  float minY = 1000, maxY = -1000;

  Serial.println("Kalibracija u toku...");
  for (int i = 0; i < 50; i++) {
    Vector acc = mpu.readNormalizeAccel();
    if (acc.XAxis < minX) minX = acc.XAxis;
    if (acc.XAxis > maxX) maxX = acc.XAxis;
    if (acc.YAxis < minY) minY = acc.YAxis;
    if (acc.YAxis > maxY) maxY = acc.YAxis;

    delay(100); // da se ne cita prebrzo
  }

  // Postavljanje granica (dodajemo mali margine ako želiš deadband)
  float margin = 0.05;  // opcioni "mrtvi prostor"
  xThresholdLow = minX - margin;
  xThresholdHigh = maxX + margin;
  yThresholdLow = minY - margin;
  yThresholdHigh = maxY + margin;

  // Inicijalni filter setup
  Vector normAccel = mpu.readNormalizeAccel();
  filteredX = normAccel.XAxis;
  filteredY = normAccel.YAxis;

  // Prikaz rezultata kalibracije
  Serial.println("Kalibracija završena.");
  Serial.print("xThresholdLow: "); Serial.println(xThresholdLow);
  Serial.print("xThresholdHigh: "); Serial.println(xThresholdHigh);
  Serial.print("yThresholdLow: "); Serial.println(yThresholdLow);
  Serial.print("yThresholdHigh: "); Serial.println(yThresholdHigh);
}

void loop() {
  // Read raw sensor data
  Vector normAccel = mpu.readNormalizeAccel();
  
  // Apply low-pass filter
  filteredX = filteredX * (1 - filterFactor) + normAccel.XAxis * filterFactor;
  filteredY = filteredY * (1 - filterFactor) + normAccel.YAxis * filterFactor;
  
  bool moveX = false;
  bool moveY = false;

  // X axis control
  if (filteredX < xThresholdLow) {
    digitalWrite(XdirPin, HIGH);
    moveX = true;
  } else if (filteredX > xThresholdHigh) {
    digitalWrite(XdirPin,LOW);
    moveX = true;
  }

  // Y axis control
  if (filteredY < yThresholdLow) {
    digitalWrite(YdirPin, LOW);
    moveY = true;
  } else if (filteredY > yThresholdHigh) {
    digitalWrite(YdirPin,HIGH);
    moveY = true;
  }

  // Execute movements
  if (moveX) {
    digitalWrite(XstepPin, HIGH);
    delayMicroseconds(10);
    digitalWrite(XstepPin, LOW);
  }

  if (moveY) {
    digitalWrite(YstepPin, HIGH);
    delayMicroseconds(10);
    digitalWrite(YstepPin, LOW);
  }

  // Speed control
  delayMicroseconds(300);

  // Debug output
  Serial.print("X: ");
  Serial.print(normAccel.XAxis);
  Serial.print(" Y: ");
  Serial.println(normAccel.YAxis);
}

I realized it was a power problem. The motors were drawing too much power and making dips in voltage for the sensor and so the code would freeze after around 2 seconds. Then i added capacitors to make the power stable to the sensor (100µF electrolytic capacitor and a 0.1µF ceramic capacitor) . The code doesent freeze now, and when i take out the capacitors it freezes, which means they are making the power stable. But now the motors arent turning. They are turned on and i can feel them being on and getting hotter but its not turning anymore even when i take out the capacitors

More information required. Please post the required wiring diagram (pencil and paper is fine, with all pins, parts and connections clearly labeled), along with the specifications for the motors, motor drivers and motor power supply.

You may have damaged the motor drivers by incorrectly wiring the setup.

That is good but it does not make up the power the power supply should be supplying. Put a scope on it and you will see. Note where the bottom of the voltage goes with and without the capacitor.

i dont think its damaged because before using the capacitors it worked fine. when i put them in it stopped working even tho its the exact same wiring

Since it does not work, there is no point in making uninformed assumptions.

Whatever you did made it stop working, and a common mistake that instantly destroys stepper drivers is to change wiring while it is still powered.

Post the requested information. A picture of the setup would help, too.

I have merged your cross-posts @ricko12345 (AKA @adadaadgggg).

Cross-posting is against the Arduino forum rules. The reason is that duplicate posts can waste the time of the people trying to help. Someone might spend a lot of time investigating and writing a detailed answer on one topic, without knowing that someone else already did the same in the other topic.

Repeated cross-posting can result in a suspension from the forum.

In the future, please only create one topic for each distinct subject matter. This is basic forum etiquette, as explained in the "How to get the best out of this forum" guide. It contains a lot of other useful information. Please read it.

Thanks in advance for your cooperation.

Oh sorry. I thought the shield comes with 2-way headers and it is possible to connect capacitor using the front side of the shield. But from your description it sounds like it is not possible.