Optical sensor and arduino code

Hello experts!

I am trying to get an optical sensor to work, I'll use them as limit switches but for now am just trying to get them to work properly. I understand they have 3 connections - 5 V, GND and SIGnal. I've connected one up to the Arduino Uno to 5 V, GND and the SIG to pin 8. I have used the following code:

int ENDSTOP_PIN = 8;
void setup()
{
pinMode(ENDSTOP_PIN, INPUT);
Serial.begin(9600);
Serial.println("Starting Optical sketch");

}

void loop()
{
if (!digitalRead(ENDSTOP_PIN))
{
if (1)
Serial.println("closed");
else
Serial.println("open");

}
delay(500);
}

The little LED on the optical switch is lit up all the time and the serial monitor displays 'closed' every 1/2 second but it doesn't seem to work. If I block the sensor with something, it has no effect. Can anyone assist with this? It would be immensely appreciated.

tks

What's the if(1) for?

I think you want this:

if (!digitalRead(ENDSTOP_PIN))
{
Serial.println("closed");
}
else
{
Serial.println("open");
}

Thanks Jimboza, you don't know how much I appreciate your assistance!

I changed the code to what you said:

int ENDSTOP_PIN = 8;
void setup()
{
pinMode(ENDSTOP_PIN, INPUT);
Serial.begin(9600);
Serial.println("Starting Optical sketch");
}
void loop()
{
if (!digitalRead(ENDSTOP_PIN))
{
Serial.println("closed");
}
else
{
Serial.println("open");
}
delay(500);
}

Now the serial monitor just displays 'closed'. It's as if it only every returns what is immediately after the IF statement. Have tried many different permutations and it all seems to be the same.

For a test, see if the sensor is actually working, with this:

void loop()
{
Serial.println(digitalRead(ENDSTOP_PIN))
}

You could just power the sensor and with a voltmeter check the voltage across sig and gnd to see if it actually changes.

Thanks again Jimboza!. I connected my voltmeter to the two pins and got no change in voltage from open to closed…voila! faulty optical switch right out of the packet. Have since been able to get another and code works fine. Thanks a million, your assistance was very much appreciated