Expected '}' before 'else'

Hi,

I'm having a bit of trouble with this code - I am trying to make lights on pins 2 and 3 light up when the Arduino is tilted beyond flat.

There is apparently supposed to be a '}' before the 'else' on line 30 (within voidLoop()), although I am very new to C++ and I'm not sure what to do.

Thanks for any help! :slight_smile:

#include <Arduino_LSM9DS1.h>
int light_one = 2;
int light_two = 3;

void setup()
{
  pinMode(light_one, OUTPUT);
  pinMode(light_two, OUTPUT);

  if (!IMU.begin())
  {
    Serial.println("Failed to initialize IMU!");
    exit(1);
  }
}

void loop()
{
  float x, y, z, delta = 0.05;

  if (IMU.accelerationAvailable())
  {
    IMU.readAcceleration(x, y, z);

    if (y <= delta && y >= -delta)
      Serial.println("flat");
    pinMode(light_one, LOW);
    pinMode(light_two, LOW);

    else if (y > delta && y < 1 - delta)
      Serial.println("tilted to the left");
    pinMode(light_one, HIGH);
    pinMode(light_two, HIGH);

    else if (y >= 1 - delta)
      Serial.println("left");
    pinMode(light_one, HIGH);
    pinMode(light_two, HIGH);

    else if (y < -delta && y > delta - 1)
      Serial.println("tilted to the right");
    pinMode(light_one, HIGH);
    pinMode(light_two, HIGH);

    else
      Serial.println("right");
    pinMode(light_one, HIGH);
    pinMode(light_two, HIGH);
  }

  delay(150);
}

Perhaps read up on the if-statement syntax and all will become clear?

if ( ) else
or
if ( )

where a statement is a single statement.

A block statement counts as a single statement.

Or simply put you need braces round the then or else statements unless they are single statements.

There is apparently supposed to be a '}' before the 'else' on line 30 (within voidLoop()), although I am very new to C++ and I'm not sure what to do.

do what the compiler tells you: add a } before the else.

Press CTRL-T in the Arduino IDE - you might see the problem better then...

if (y <= delta && y >= -delta)

Are you missing a { there?

Thank you for the responses - it's my first time with Arduino so I'm not yet clued up on the statement syntax!

I hadn't added '{}' around the if, else if and else statements.

Thanks!