Expected unqualified-id before 'if' beginner in need of help

Hi everyone,
For a college project, I have written this code however on the if statements it is giving me an expected unqualified-id before 'if' error when compiling the code and i have read through other topic posts with this problem but I just can't seem to fix it. could anyone help me out?

int LED1 = 2;
int LED2 = 3;
int LED3 = 4;
int potValue = 0;
int dutyCycle = map(potValue, 0, 1023, 100, 255);
void setup() {
  pinMode(LED1, OUTPUT);
  pinMode(LED2, OUTPUT);
  pinMode(LED3, OUTPUT);
}

void loop() {
  potValue = analogRead(A0);
}

void Forward(int dutyCycle) {
  analogWrite(LED1, 10);
  analogWrite(LED2, 200);
  analogWrite(LED3, 10);
}
void left(int dutyCycle) {
  analogWrite(LED1, dutyCycle);
  analogWrite(LED2, 50);
  analogWrite(LED3, 10);
}
void right(int dutyCycle) {
  analogWrite(LED1, 10);
  analogWrite(LED2, 50);
  analogWrite(LED3, dutyCycle);
}
if (potValue == 512); {
  forward();}
else if (potValue > 512); {
  left();}
else (potValue < 512); {
  right();
  }

You have code outside of a function

Where does the right() function end ?

okay so i should place all my if statements inside another function?
and the right function end after the } before the if statement

You also want to lose a semicolon. What you wrote is the same as

  if (potValue == 512)
    ;

  forward();

A complete if statement that does nothing.

And unconditional execution of the forward() function.

a7

okay, so both semicolons should be deleted?
and what i am trying to achieve is that the code in "void forward" is executed when that value is reached.

No, just the one that inadvertently completes the if statement.

So like

  if (potValue == 512) {
    forward();
  }

I should point out that potValue will probably not be exactly 512 very dependably. Please put your finger on this does the same thing a bit differently:

  if (potValue > 544) {
    left();
  }
  else if (potValue < 480) {
     right();
  }
  else {
    forward();
  }

I used constants and made a little area around 512 for meaning forward. You could use a manifest constant, viz:

// up top for everyone to see and change
const int DEADBAND = 32;


// then later on

  if (potValue > 512 + DEADBAND) {
    left();
  }
  else if (potValue < 512 - DEADBAND) {
     right();
  }
  else {
    forward();
  }

HTH

a7

The basic rule is that you put all program statements that depend on a test returning true into a pair of braces. It is that simple.

White space, blank lines and tabs do not influence what code is executed, only the presence of the braces surrounding the code block

1 Like

yes i do get that potValue using an actual setup won't work like this but in this case we are asked to make it to be 512 so that is not something i can change, but other than removing the semicolons everything should be good

ah okay thanks

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.