Help with Motor DC + Ultrassonic

Hello guys,

I´m trying to make a program with two DC motors and an ultrassonic sensor. in an arduino UNO. It´s really basic, if the sensor pick up a distance below 10cm, the motors must stop. But it doesn´t happen. The DC motors function normally and the sensor show the distance correctly, but the motors does´t stop when reach distance below 10cm. Follow the code:

 const int Trig = 7;
const int Echo = 8;

int cm;

int IN1 = 3;
int IN2 = 4;
int IN3 = 5;
int IN4 = 6;

void setup()
{
  Serial.begin(9600); 

  pinMode(IN1, OUTPUT);
  pinMode(IN2, OUTPUT);
  pinMode(IN3, OUTPUT);
  pinMode(IN4, OUTPUT);
  
  pinMode(Trig, OUTPUT);
  pinMode(Echo, INPUT);

}

void loop()
{
  //TURN ON THE MOTOR A
  digitalWrite(IN1, HIGH);
  digitalWrite(IN2, LOW);

  //TURN ON TH MOTOR B
  digitalWrite(IN3, HIGH);
  digitalWrite(IN4, LOW);
 
  //SENSOR ULTRASSONIC
  digitalWrite(Trig, LOW);       
  delayMicroseconds(2);
  digitalWrite(Trig, HIGH);
  delayMicroseconds(10);
  digitalWrite(Trig, LOW);
  cm = pulseIn(Echo, HIGH) / 58.0; //The echo time is converted into cm
  cm = (int(cm * 100.0)) / 100.0;     //Keep two decimal places
  Serial.println(cm);
 

  if(cm<10)
 { 
      
      //STOP THE MOTOR A
      digitalWrite(IN1, LOW);
      
      //STOP THE MOTOR B
      digitalWrite(IN3, LOW);

 }
}

Please, somebody could help me with this code? This is the components that I´m using:

Thanks in advance,
Henry

You are stopping the motor .... for about ten microseconds.

Hello @AWOL thank you for your reply!
How do you come to that conclusion? Do you what should I do to make it happen only when the sensor reach distance below to 10cm?

Thank you,
Henry

Because the loop function repeats, shortly after you stop the motors, you start them again.

Thank you. About this, how could I keep the comand "if" in function in order to stop the motors while the distance is below the distance of 10cm?

You could start the motors in setup(), and stop them in loop(), possibly restarting them in an else clause.