2WD robot - logic error in my code?

Hi all
I am making a basic 2WD robot using UNO with motor shield.
I am getting no compile errors - but something in my logic flow is not working as expected.

Expected Operation:

  1. Ping sensor does distance check
  2. If distance is less than 5cm
  3. Turn both Channel A & B motors half-speed for 1 second
  4. Stop motors
  5. Take new distance reading ping, start again.

What however is happening, is that Channel A works as expected, but channel B motor keeps running??
Where is my code / logic mistake?

Later date I will add to ELSE statement to turn one wheel to change direction

/*
 HC-SR04 Ping distance sensor:
 VCC to arduino 5v 
 GND to arduino GND
 Echo to Arduino pin 7 
 Trig to Arduino pin 8
 */

#define echoPin 7 // Echo Pin
#define trigPin 8 // Trigger Pin
#define LEDPin 13 // Onboard LED

int maximumRange = 1000; // Maximum range needed
int minimumRange = 1; // Minimum range needed
long duration, distance; // Duration used to calculate distance

void setup() {
  // put your setup code here, to run once:

Serial.begin (9600);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  pinMode(LEDPin, OUTPUT); // Use LED indicator (if required)

  
  pinMode(12, OUTPUT); /* Motor Channel A RIGHT SIDE*/
  pinMode(9, OUTPUT); /* Motor Channel A */

  pinMode(13, OUTPUT); /* Motor Channel B LEFT SIDE */
  pinMode(8, OUTPUT);

  }

void loop() {
 
  /* Distance check begins */
 
  digitalWrite(trigPin, LOW); 
  delayMicroseconds(2); 

  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10); 
 
  digitalWrite(trigPin, LOW);
 
  duration = pulseIn(echoPin, HIGH);
 
 //Calculate the distance (in cm) based on the speed of sound.
 distance = duration/58.2;

 /* End distance check */
 
 if (distance >= 5){
 /* Distance great enough to provide room to move */
  Serial.println("Move!");
 
  digitalWrite(LEDPin, HIGH); /* LED show movement */
 
  digitalWrite(12, LOW); /*move channel A motor half-speed */
  digitalWrite(9, LOW);
  analogWrite(3, 123);

  digitalWrite(13, HIGH); /*move channel B motor half-speed */
  digitalWrite(8, LOW);
  analogWrite(11, 123); 

  delay(1000);

  digitalWrite(9, HIGH); 
  digitalWrite(8, HIGH);
 }
 
 else {
 /* Send the distance to the computer using Serial protocol, and
 turn LED OFF to indicate successful reading. */
 Serial.println(distance);
 digitalWrite(LEDPin, LOW); 
 }
 
 //Delay 50ms before next reading.
 delay(500); 

}

thanks

You can't use the same pin for motor control and the LED. :confused:

#define LEDPin 13 // Onboard LED

  pinMode(LEDPin, OUTPUT); // Use LED indicator (if required)
  pinMode(13, OUTPUT); /* Motor Channel B LEFT SIDE */

thanks for the help - oversight on my part!