Simple Program not working

So I made this very basic program for an obstacle avoiding robot with one motor for each wheel, it's just supposed to turn one of them off if it detects something so it goes left, but I can't seem to be able to make the else part of the program work, either the motors stay off or they both keep going, the ultrasonic sensor is working just fine, as the console does show the correct values

const int pingPin = 7;
const int MotorA = 8;
const int MotorB = 9;

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

void loop()
{
  long duration, cm;
  
  pinMode(pingPin, OUTPUT);
  digitalWrite(pingPin, LOW);
  delayMicroseconds(2);
  digitalWrite(pingPin, HIGH);
  delayMicroseconds(5);
  digitalWrite(pingPin, LOW);

  pinMode(pingPin, INPUT);
  duration = pulseIn(pingPin, HIGH);
  cm = microsecondsToCentimeters(duration);
  
  pinMode(MotorA, OUTPUT);
  pinMode(MotorB, OUTPUT);
  if (cm > 40){
    digitalWrite(MotorB, HIGH);
    digitalWrite(MotorA, HIGH);
  }else{
    digitalWrite(MotorB, LOW);
    digitalWrite(MotorA, LOW);
    delay(100);
    digitalWrite(MotorB, HIGH);
  }
  Serial.print(cm);
  Serial.println();
  
}



long microsecondsToCentimeters(long microseconds)
{

  return microseconds / 29 / 2;
}

That code does something. You haven't said what.

The code drives some hardware. You haven't said what.

There is no reason to set the motor pins as output on every pass through loop.

When the Serial.print() of cm shows up on your console, is it ever less than 40?

Hi, I agree with PaulS reguarding the pin setup.
Try this with your else statement

}
else   // else is on a line of its own
{

I'm sure I had a similar problem and that was why it didn't work because the else was not on a line of its own.

Tom... :slight_smile:

I think the following part of your code is causing the problem:

pinMode(MotorA, OUTPUT);
  pinMode(MotorB, OUTPUT);
  if (cm > 40){
    digitalWrite(MotorB, HIGH);
    digitalWrite(MotorA, HIGH);
  }else{
    digitalWrite(MotorB, LOW);
    digitalWrite(MotorA, LOW);
    delay(100);
    digitalWrite(MotorB, HIGH);
  }

and here are some improvements that I would suggest:

  • As suggested by PaulS put the pinMode() function calls in the setup function
  • Add a short delay after you switch on MotorB in the else block, the strange behavior shown by your robo is caused by the fact that MotorB s not getting enough time to move itself.

I'm sure I had a similar problem and that was why it didn't work because the else was not on a line of its own.

Not an issue in this case: the compiler doesn't care about such things. It's good practice all the same - people do :wink:

Hi Bill, no worries, I'd say a single tutorial could be conducted on program layout and ease of reading.
The auto format is great but still with experience, layout and commenting does eventually improve code reading and debugging.

Tom.... :slight_smile: