Code gives me error (else without a previos if) when uploading the code

Hello. I'm new to programming and for some time i have problem with "if" and "else" function. Sometimes when i write my code to practice and when i upload it it gives me error that there is no "if" before "else". I check my code a couple of times but i dont find any easy to find errors(missed bracets or semi colum). At the moment I'm trying to display information on an oled display from IR sensor ( if it detects something or not).

Here is the code:

#include <SPI.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>

#define SCREEN_WIDTH 128 
#define SCREEN_HEIGHT 64
#define OLED_RESET  -1 
#define SCREEN_ADDRESS 0x3C 
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);

 

const int sensor = 18;

void setup() {
   if (!display.begin(SSD1306_SWITCHCAPVCC, SCREEN_ADDRESS, OLED_RESET)) {
    Serial.println(F("SSD1306 allocation failed"));
    for (;;); 
  }
  // put your setup code here, to run once:
  Serial.begin(115200);
 
}

void loop()
{
   int data = digitalRead(sensor);
  if (data == LOW);
  {
    display.clearDisplay();
    display.setTextColor(WHITE);
    display.setTextSize(2);
    display.setCursor(0,0);
    display.println("Detected");
    display.display();
    
  }
  else
  {
     display.clearDisplay();
  display.setTextColor(WHITE);
  display.setTextSize(2);
  display.setCursor(0, 0);
  display.println("Not Detected");
  display.display();
  }
 
}

I try to use yt/github or my previous codes as reference for my current one.
Any tips for the code will be of big help.

Any tips for the code will be of big help.

Hello mrt190

Welcome to the worldbest Arduino forum ever :smiley:

Change

if (data == LOW);

to

if (data == LOW)

and try again.

2 Likes

The ';' is the culprit here. Remove the ;
Further, since the only difference is the println statement you might want to change it to:


void loop()
{
   int data = digitalRead(sensor);
   display.clearDisplay();
   display.setTextColor(WHITE);
   display.setTextSize(2);
   display.setCursor(0,0);
   if (data == LOW)  display.println("Detected");
  else display.println("Not Detected");
   display.display();

I omitted the curly brackets {}. When only one stament is used after if, you do not need them.

1 Like
void loop()
{
   bool data = digitalRead(sensor);
   display.clearDisplay();
   display.setTextColor(WHITE);
   display.setTextSize(2);
   if (data)display.println("Not ");
   display.println("Detected");
   display.display();
3 Likes

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