Expected unqualified-id before 'if"

I'm a big time noob, and this is pretty much my first project. The goal of this code is to sense blinks and move a servo 180 degrees each blink. The code I am using is from this project but heavily modified. I am trying to run the code in the tinkercad circuits arduino simulator, but I get two of the same error message each time. "error: expected unqualified-id before 'if' " The sim is currently just an arduino, with no sensors or anything connected. I am just trying to get the code to run before I move onto that.

This is the code:

#include <Servo.h>

int irSensorL = 4;
int potpin5 = 4;

void loop() {

	int readingSensor = digitalRead(irSensorL);
	Serial.println(readingSensor);
	delay(1000);

	Servo eyeL;

}
boolean closeEyes = false;

void setup() {
	Servo eyeL;
	Serial.begin(9600);
	eyeL.attach(3);
	eyeL.write(30);  

}

int readingSensor = digitalRead(irSensorL);
Servo eyeL;

if (readingSensor == 0 ) {
	closeEyes =! closeEyes;
	delay(1000);
	Serial.println(closeEyes);
}
if(closeEyes == true) {
	eyeL.write(180);
	if(closeEyes == true);
		delay(100);
	else {
		eyeL.write(0);
		delay(100);
	}
}

I am getting the error on lines 30 and 35, on "delay(1000);" and "if(closeEyes == true);" I've read that this error can happen due to a missing ";" somewhere in the code, but I don't know where that would be.

I don't know if this matters, but once it's functional I'm going to copy-paste this code and modify it to be "closeEyeR" and "closeEyeL", so if that's going to screw something up feel free to let me know.

Thank you for your help.

Welcome

You can't have code (except variables declarations) outside of a function.

All your "if" code should be inside the loop() function. But there are some other problems with your code so here I fixed some of it

#include <Servo.h>

int irSensorL = 4;
int potpin5 = 4;

Servo eyeL;
boolean closeEyes = false;

void setup() {
	Serial.begin(9600);
	eyeL.attach(3);
	eyeL.write(30); 
}

void loop() {
	int readingSensor = digitalRead(irSensorL);
	Serial.println(readingSensor);
	delay(1000);
	
	if (readingSensor == 0 ) {
		closeEyes = !closeEyes;
		delay(1000);
		Serial.println(closeEyes);
	}
	if(closeEyes == true) {
		eyeL.write(180);
		if(closeEyes == true) {
			delay(100);
		} else {
			eyeL.write(0);
			delay(100);
		}
	}
}

Compare every lines to your original code to see what changed so you can learn something...

You also have logic problems

	if(closeEyes == true) {
		eyeL.write(180);
		if(closeEyes == true) {
			delay(100);
		} else {
			eyeL.write(0);
			delay(100);
		}
	}

The "else" will never execute because closeEyes didn't change

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