"a function-definition is not allowed here before '{' token" error

I keep receiving the “a function-definition is not allowed here before ‘{’ token” error for one line of my code and the exit status 1

int pingPin = 3;
int echoPin = 2;

int fwdRightMotor = 5;
int revRightMotor = 4;
int fwdLeftMotor = 7;
int revLeftMotor = 6;

void setup() {
Serial.begin (9600); //Starting Serial Terminal
}
void loop() {
long duration, inches, cm;
pinMode(pingPin, OUTPUT);
digitalWrite(pingPin, LOW);
delayMicroseconds (20);
digitalWrite(pingPin, HIGH);
delayMicroseconds(100);
digitalWrite(pingPin, LOW);
pinMode (echoPin, INPUT);
duration = pulseIn(echoPin, HIGH);
long microsecondsToCentimeters(long microseconds) { //this is where the error message shows for
return microseconds / 29.387 / 2;
cm=microsecondsToCentimeters(duration);
}
Serial.print(cm);
Serial.print(“cm”);
Serial.println();
delay(100);

pinMode(fwdRightMotor, OUTPUT);
pinMode(revRightMotor, OUTPUT);
pinMode(fwdLeftMotor, OUTPUT);
pinMode(revLeftMotor, OUTPUT);

if (cm <= 5) {
digitalWrite(fwdRightMotor, HIGH);
digitalWrite(revRightMotor, LOW);
digitalWrite(fwdLeftMotor, HIGH);
digitalWrite(revLeftMotor, LOW);
delay(20);
}
else if (cm > 5 && cm < 9) {
digitalWrite(fwdRightMotor, HIGH);
digitalWrite(revRightMotor, LOW);
digitalWrite(fwdLeftMotor, LOW);
digitalWrite(revLeftMotor, HIGH);
delay(20);
}

else (cm > 9); {
digitalWrite(fwdRightMotor, HIGH);
digitalWrite(revRightMotor, LOW);
digitalWrite(fwdLeftMotor, LOW);
digitalWrite(revLeftMotor, HIGH);
delay(20);
digitalWrite(fwdRightMotor, HIGH);
digitalWrite(revRightMotor, LOW);
digitalWrite(fwdLeftMotor, HIGH);
digitalWrite(revLeftMotor, LOW);
}
}

I checked my brackets and they seem to be equal, (unless I am mistaken). Help would be appreciated, thank you.

When you compile, at the end you have

exit status 1
a function-definition is not allowed here before '{' token

which give you no real details.
But if you scroll a liitle you'll see the error:

/Users/Maison/Desktop/glob/glob.ino: In function 'void loop()':
glob:22:53: error: a function-definition is not allowed here before '{' token

  • long microsecondsToCentimeters(long microseconds) { //this is where the error message shows for*

In fact you have a definition of function (microsecondsToCentimeters) inside a function (loop) which is not allowed.

I checked my brackets and they seem to be equal, (unless I am mistaken).

Equal (balanced) and properly placed are two different things. You must satisfy BOTH criteria.

Tools + Auto Format will make it VERY clear that microsecondsToCentimeters() is INSIDE of loop, which is NOT allowed.

  else (cm > 9); {  //oops
    digitalWrite(fwdRightMotor, HIGH);
    digitalWrite(revRightMotor, LOW);
    digitalWrite(fwdLeftMotor, LOW);
    digitalWrite(revLeftMotor, HIGH);
    delay(20);
    digitalWrite(fwdRightMotor, HIGH);
    digitalWrite(revRightMotor, LOW);
    digitalWrite(fwdLeftMotor, HIGH);
    digitalWrite(revLeftMotor, LOW);
  }