Struggling with Opto-Reflective IR Proximity Sensor

So I'm trying to use a short range IR Proximity Sensor as part of a feedback loop for a robotic hand project I'm working on.

I've used google to the point where I have a code, I believe its wired correctly, and I have an output printing in the serial monitor. My problem is that regardless of placing an object infront of the sensor, the output is always 1.

The code I'm using is as follows;

int IRSensor = 1;
int IREmitter = 2;
int ProxReading = 0;

void setup() {
pinMode(IRSensor, INPUT);
pinMode(IREmitter, OUTPUT);
Serial.begin(9600);
}

void loop() {
digitalWrite(IREmitter, HIGH);
ProxReading = digitalRead(IRSensor);

Serial.println("Proximity Reading = ");
Serial.println(ProxReading);
delay(50);
}

My sensor has 4 pins, which the datasheet says are collector, emitter, anode and cathode from 1 to 4. I'm sure there's an obvious error in my code, but this is all quite new to me and google has if anything left me more confused.

Thanks in advance for any help :slight_smile:

Maybe you should be doing an analog read on the sensor. Can you post a clickable link to the sensor?

https://uk.rs-online.com

UPDATE: Analog reading is working, but values are fluctuating from 1023 back to 0 and back again?

Need a wiring diagram ..

cjrobson:
UPDATE: Analog reading is working, but values are fluctuating from 1023 back to 0 and back again?

That indicates the sensor is switching. Go back to digitalRead and change the pinMode of the sensor to INPUT_PULLUP.

It is very rare to use INPUT_PULLUP with analogRead.

That sensor looks to be equivalent to the QRE1113 sold by Sparkfun. You could steal their examples.

So the digitalRead just goes back to an output of 1 regardless, so must be an analog sensor? The QRE1113 codes I've found seem to have the same problems only with a higher frequency of readings...

You haven't said how it's wired though. I'd go collector to digital pin with input pullup, emitter to ground. Transistor will conduct when there's a reflection, and take pin low. Look for a low to indicate presence of object.