Help about stepper motor :( Noob question

I have used Arduino UNO R3 with stepper driver A4988 for a stepper motor, with a relay and here my code:

int pinDir = 8;
int pinStep = 9;
int pinRelay = 10;

void setup() {

  pinMode(pinRelay, OUTPUT);
  pinMode(pinDir, OUTPUT);
  pinMode(pinStep, OUTPUT);
  digitalWrite(pinRelay, HIGH);
  digitalWrite(pinDir, LOW);
  digitalWrite(pinStep, LOW);
}

void loop() {
  
  digitalWrite(pinStep, HIGH);
  delayMicroseconds(30000);
  digitalWrite(pinStep, LOW);
  delayMicroseconds(30000);

 
}

It works perfectly but when I put more code for the ultrasonic sensor, the motor seems to be struggling :frowning: however the ultrasonic work well

int pinDir = 8;
int pinStep = 9;
int pinRelay = 10;
const int trig = 7;
const int echo = 6;

void setup() {
  Serial.begin(9600);
  pinMode(trig, OUTPUT);
  pinMode(echo, INPUT);
  pinMode(pinRelay, OUTPUT);
  pinMode(pinDir, OUTPUT);
  pinMode(pinStep, OUTPUT);
  digitalWrite(pinRelay, HIGH);
  digitalWrite(pinDir, LOW);
  digitalWrite(pinStep, LOW);
}

void loop() {
  unsigned long duration;
  int distance;

  digitalWrite(trig, 0);
  delayMicroseconds(2);
  digitalWrite(trig, 1);
  delayMicroseconds(5);
  digitalWrite(trig, 0);



  duration = pulseIn(echo, HIGH);
  distance = int(duration / 2 / 29.412);

  digitalWrite(pinStep, HIGH);
  delayMicroseconds(30000);
  digitalWrite(pinStep, LOW);
  delayMicroseconds(30000);


  Serial.print(distance);
  Serial.println("cm");
  delay(200);
}

So my code make the stepper motor work badly or because of the power source? :frowning: please help, also I use 5V pin arduino for ultrasonic sensor, relay and driver motor A4988, is it ok?

when I put more code for the ultrasonic sensor, the motor seems to be struggling

Could the problem be

  delay(200);

which means that the motor will only step every 200 milliseconds ?
The shorter delayMicroseconds() will also contribute to the overall delay between motor steps

The functions delay() and delayMicroseconds() block the Arduino until they complete.
Have a look at how millis() is used to manage timing without blocking in Several Things at a Time.

And see Using millis() for timing. A beginners guide if you need more explanation.

...R

tks so much guys :slight_smile: :slight_smile: :slight_smile: :slight_smile: :slight_smile: