Problem regarding Motor Driver Dual H Bridge L298N with Ultrasonic Sensor HC-SR0

Hi,

I would like to make a vehicle that will stop when the sensor detects that the distance is less than 10. However, I was unable to understand how to use the break command. Could any kind soul show me how to edit my code? Thank you very much!

"
//variable for motor
int INA = 2;
int INB = 4;
int INC = 7;
int IND = 6;
int ENA = 3;
int ENB = 5;
int SPEED = 120;

//variable for echo distance
int trigPin = 9;
int echoPin = 10;
long duration;
int distance;

void setup() {

//for motor
pinMode(INA,OUTPUT);
pinMode(INB,OUTPUT);
pinMode(INC,OUTPUT);
pinMode(IND,OUTPUT);
pinMode(ENA,OUTPUT);
pinMode(ENB,OUTPUT);

analogWrite(ENA,SPEED);
analogWrite(ENB,SPEED);

//for echo distance
pinMode(trigPin,OUTPUT);
pinMode(echoPin,INPUT);
Serial.begin(9600);

distance=999;
}

void loop() {

int x=0;

while(x<1)

{
digitalWrite(INA,HIGH);
digitalWrite(INB,LOW);
digitalWrite(INC,LOW);
digitalWrite(IND,HIGH);
delay(500);
digitalWrite(INA,LOW);
digitalWrite(INB,LOW);
digitalWrite(INC,LOW);
digitalWrite(IND,LOW);

digitalWrite(trigPin,LOW);
delayMicroseconds(2);
digitalWrite(trigPin,HIGH);
delayMicroseconds(10);
digitalWrite(trigPin,LOW);
duration = pulseIn(echoPin,HIGH);
distance = duration*0.017;

Serial.print("Distance: ");
Serial.println(distance);
delay(500);

if(distance < 10)
{
break;
}

}
}

AFAIK, you don’t need to use break

just tell the motors to stop turning !

IF (distance < 10) THEN do motors_stop

To make the motor BRAKE, make both the direction pins LOW and keep the enable pin HIGH.

void loop()
...
...
if(distance < 10)
{
brake;
}

void brake()
{
  digitalWrite(INA,LOW);
  digitalWrite(INB,LOW);
  digitalWrite(ENA,HIGH);
  delay(200);
}