A simple digitalRead in code makes the stepper go slower

Hello,
I'm driving a small stepper with a sufficient supply via Nano and a A4988 driver.
Today I was looking how to implement driving of the motor with the other parts of the system in the loop part of the code. In the first code, I'm simply driving the motor like this:

int del=1000;

void setup() {                
  pinMode(8, OUTPUT);     
  pinMode(9, OUTPUT);
  digitalWrite(8, LOW);
  digitalWrite(9, LOW);
  pinMode(4,INPUT);
  Serial.begin(9600);
}

void loop() {
  
  
    turn(del);
  
  //Serial.println(digitalRead(4));
}

void turn(int k){
  digitalWrite(9,HIGH);
  delayMicroseconds(k);
  digitalWrite(9,LOW);
  delayMicroseconds(k);
}

And the motor runs fine, since its a 200 step motor, this runs it at 2.5rps.

BUT, as soon as I uncomment the Serial.println part, in which I simply read the state of a switch connected to pin 4, the motor runs considerably slower and makes more noise.

If its just a problem with the coding, please point it out. Maybe the continuous driving of the stepper should be implemented in a different way within the loop? Maybe the Serial print takes too much time so the motor loses step?

I do all this because in the future system there would be readings from atleast 2 sensors within the loop, a control algorithm and so on....
Thank you for your help!

It is the Serial.print() that is slow.

Have a look at the second example in this Simple Stepper Code. It uses millis() and micros() to manage the timing without blocking.

If you don't block the Arduino with delayMicroseconds() there should be plenty of time for the printing.

Note that you almost certainly don't want to print something for every single step. Once or twice per second is probably enough.

...R
Stepper Motor Basics

Thank you for the response and the helpful links :slight_smile:

First, use 115200 baud or higher, not 9600, that's a 1980's baud rate!

Second look at the AccelStepper library, non-blocking stepper driving with
speed ramping - just put a call to stepper.run() in loop().