If-statements interrupts motor from working

Hello, I am working on a project with an automated robot which drives itself for a certain amount of seconds. It uses an ultrasonic sensor to read the distance and when the distance is smaller than 100 cm it stops the motor. Unfortunately particular this if-statement in the code stops the motor from working in the beginning, it only drives with a lot of shocks. When I didn't involve the if-statement in the final code the motor worked great while also measuring the distance but not doing anything with it. I don't know why this happens. I hope someone can help me. Thanks a lot. The code is in the attachment.

The code is in the attachment.

Nope.

Just POST the code.

TheMemberFormerlyKnownAsAWOL:
Nope.

Just POST the code.

Inside code tags.

#include <Servo.h>
//distance
int trigPin1 = 11;    
int echoPin1 = 12;    
long duration, cm;

//esc
Servo ESC;    

unsigned long previousMillis = 0;
const long interval = 1000; 
int RijTijd = 20;
int count = 0;

//servo
Servo myservo1;
int pos = 0;
int StuurTijd = 10;
int EindStuurTijd = 15;

void setup() {
// esc  
  ESC.attach(9,1000,2000);
 
  Serial.begin(9600);
  ESC.write(0);
  delay(10000);

//servo
myservo1.attach(6);
myservo1.write(90);

//distance
  pinMode(trigPin1, OUTPUT);
  pinMode(echoPin1, INPUT);
}

void loop() {
  // esc
  ESC.write(25);

  //time
  unsigned long currentMillis = millis();

  if (currentMillis - previousMillis >= interval) {
    
    count++;
    previousMillis = currentMillis;

     if(count >= RijTijd){
  ESC.write(0);
  }
Serial.println(count);

  }
  
// distance
  digitalWrite(trigPin1, LOW);
  delayMicroseconds(5);
  digitalWrite(trigPin1, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin1, LOW);
 
  pinMode(echoPin1, INPUT);
  duration = pulseIn(echoPin1, HIGH);
 
  cm = (duration/2) / 29.1;    

  Serial.print(cm);
  Serial.print("cm");
  Serial.println();

  delay(500);

  if(cm <= 100){
  ESC.write(0); 
  delay(5000);
  }
  
//servo

     if(count >= StuurTijd){
    myservo1.write(80);
     }
 
    if(count >= EindStuurTijd) {
    myservo1.write(90);   
           
                 
  }
  
  }

Every time through loop() you write a value of 25 to the ESC regardless of whether the robot is within 100 cm of anything. Did you mean to do this ?

UKHeliBob, I meaned to do that because else it won't drive I thought.

You need to test the distance ahead at the start of loop() then if it above 100cm write to the ESC to run the motor at the required speed else stop the motor. If you want the motor to run for a fixed period or need to know how long it has been running then save the value of millis() when you start it and compare that with the value of millis() now

Of course, once the motor has stopped you need to decide what you are going to do next