Odd sketch issue

I know i’m just missing something stupid but I cant see it.

When I load this code, one motor turns forward and one motor turns backwards, just as it should:


/* Copy and paste the code below into the Arduino software */ 
int E1 = 6; //M1 Speed Control 
int E2 = 5; //M2 Speed Control 
int M1 = 8; //M1 Direction Control 
int M2 = 7; //M2 Direction Control 
void setup() 
{ 
pinMode(13, OUTPUT);
int i; 
for(i=5;i<=8;i++) 
pinMode(i, OUTPUT); 
Serial.begin(9600); 
} 
void loop() 
{ 
digitalWrite(13, HIGH);
int leftspeed = 255; //255 is maximum speed 
int rightspeed = 255; 
analogWrite (E1,255); 
digitalWrite(M1,LOW); 
analogWrite (E2,255); 
digitalWrite(M2,HIGH); 
delay(100); 
}

However, when I load this code, at the point where it says “turn”, both motors go forward instead of one going forward and one going backwards. Any ideas why?


int E1 = 6; //M1 Speed Control 
int E2 = 5; //M2 Speed Control 
int M1 = 8; //M1 Direction Control 
int M2 = 7; //M2 Direction Control

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

void loop() {
int leftspeed = 240;
int rightspeed = 255;
int ultraSoundpin = 7;
unsigned long ultrasoundDuration; 
pinMode(ultraSoundpin, OUTPUT);

pinMode(E1, OUTPUT);
pinMode(E2, OUTPUT);
pinMode(M1, OUTPUT);
pinMode(M2, OUTPUT);

//analogWrite(E1,leftspeed);
//digitalWrite(M1,LOW);
//analogWrite(E2,rightspeed);
//digitalWrite(M2,LOW);
  // send a low, wait 2 microseconds, send a high then wait 10 microseconds
  digitalWrite(ultraSoundpin, LOW);
  delayMicroseconds(2);
  digitalWrite(ultraSoundpin, HIGH);
  delayMicroseconds(10);
  digitalWrite(ultraSoundpin, LOW);

   // switch pin to input
  pinMode(ultraSoundpin, INPUT);

  // wait for a pulse to come in as high
  ultrasoundDuration = pulseIn(ultraSoundpin, HIGH);

  if(ultrasoundDuration > 1200){
    analogWrite(E1,leftspeed);
    digitalWrite(M1,LOW);
    analogWrite(E2,rightspeed);
    digitalWrite(M2,LOW);
  }else{
    Serial.print("stop");
    Serial.println();
    analogWrite(E1,0);
    digitalWrite(M1,LOW);
    analogWrite(E2,0);
    digitalWrite(M2,LOW);
    delay(1000);
    
    Serial.print("turn");
    Serial.println();
    analogWrite (E1,255); 
    digitalWrite(M1,LOW); 
    analogWrite (E2,255); 
    digitalWrite(M2,HIGH); 
    delay(3000);
    
    Serial.print("stop");
    Serial.println();
    analogWrite(E1,0);
    digitalWrite(M1,LOW);
    analogWrite(E2,0);
    digitalWrite(M2,LOW);
  }
  // output
  //Serial.print(ultrasoundDuration);
  //Serial.print("\t");
  //Serial.print(ultrasoundDuration/58, DEC);
  //Serial.print(" cm");
  //Serial.println();

  delay(500);
}

Nevermind, was using pin 7 for the sensor AND the motor driver