'else' without a previous 'if' error on arduino Ide

I was trying to write code for a lightning effect for Halloween. I got an"'else' without a previous 'if'" error message even though "if" is above. My code is below:

int TriggerValue = 0;


void setup() {
  // put your setup code here, to run once:
pinMode(A0, INPUT);//Botton trigger
pinMode(1, OUTPUT);// light
pinMode(2, OUTPUT); //sfx
Serial.begin(9600);
}

void loop() {
  // put your main code here, to run repeatedly:
TriggerValue = digitalRead(A0);
if (TriggerValue != 0)
Serial.println("Triggered");
  digitalWrite(1, HIGH);
  delay(200);
  digitalWrite(1, LOW);
  digitalWrite(2, HIGH);
  delay(200);
  Serial.println("Gottom! You should have seen the look on your face!");
  digitalWrite(2, LOW);
else
(TriggerValue != 1);
    digitalWrite(1, LOW);
  
 
}

`
Thank you for helping!

You're missing { and } for the statements that depend on the if condition.

If you use tools->autoformat in the IDE, your code looks like

  if (TriggerValue != 0)
    Serial.println("Triggered");
  digitalWrite(1, HIGH);

indicating that only the Serial.println is depending on the condition and the digitalWrite is not.

Note the indentations after the autoformat was applied.

Always use braces

if (TriggerValue != 0)

{

}

else

{

}

The syntax you are looking for is probably

if( )
{
    ...
}
else
{
  ...
}

In your case the if statement ends with the first semicolon.

if (TriggerValue != 0)
Serial.println("Triggered");

All next lines are outside of this "if" so the "else" statement causes an error. Same problem is behind the "else".

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