Serial.read creates delay between PWM signals

Hello,

I am working on a simple project which requires stepper motor control and sensor readings. I would like to send desired PWM to stepper motor while sensors are reading data.

The simplified code I am working can be found below. MotorPulse() sends the PWM signal, loadcell() reads data. Because of the loadcell() function there exists an undesirable delay between digitalWrite commands of the MotorPulse() function which in turn affects the stepper motors speed. Is there any way I can overcome this problem ? I want to be able to drive the stepper motor at desired speeds while the sensor is reading. (Because of the delay created by loadcell(), it can't get fast, as the PWM signals are slow)

I am thinking about putting the digitalWrite commands inside the "serial.read" functon so that they are executed while the serial.read is working. I am also currently looking at some scheduler libraries which I hope can run these two lines simulatenously, eliminating the delay. I am open to suggestions. I hope I expressed myself clear enough.

Thanks in advance

void MotorPulse() {

   // SEND PWM SIGNAL
  digitalWrite(stepPin, HIGH);
  delay(1);
  digitalWrite(stepPin, LOW);
  
}


void loadcell() {
  
   //LOADCELL READ
   units = scale.read( );
}








void setup() {

  Serial.begin(9600);
  //Set motor pins
  pinMode(stepPin, OUTPUT); 
  pinMode(dirPin, OUTPUT);
  


  //Set HX711-Loadcell parameters
  scale.set_scale(calibration_factor);
  scale.tare();



  //Set motor direction
  digitalWrite(dirPin, Direction);  // Low for düz, HIGH for ters hareket
 


//Start main loop

  while (stopcon=true) {

      
      MotorPulse();
      loadcell();
        


      

      Serial.println(units);         // Loadcell Values print
     
      
      
            // STOP CONDITION
            if (units<maxloadcell*3/4){
              break;
        }
  
  
  }
  
}

  


void loop() {
}

The Arduino has hardware to provide PWM functionality which is not disturbed by interrupts occurring because of serial data transfers. If you emulate this by simple digitalWrite()s with delay()s in between you will always inhomogeneous results.

A stepper motor does not use PWM. It just requires a pulse whenever a step is required. The interval between pulses determines the speed.

If you use millis() for non-blocking timing of the pulses, and also use non-blocking code everywhere else it should be possible to run your motor and do other things - unless you need a very high step rate.

You have not posted a complete program or given details of all the other hardware you are using. Some of the libraries for reading weighing systems use blocking code.

...R
Stepper Motor Basics
Simple Stepper Code