After watching Citizen Engineer, I wanted to play with a slotted optical sensor, well that and a payphone, a sim card reader, a little vice and other cool electronics things. So I ordered a few from All Electronics.
As usual, I had no idea how these things work, so I started plugging in wires and using a standard analog input sketch. That did not work at all, after I heard something pop I knew I was not on the right track. Then I started looking for some help. I still have not found a datasheet, but I found a graphic that made things work for me. My exact model is the OPB3902.

There are four pins on the bottom of these things, two to work the emitter (E) (pins 1 and 3) and two for the detector (D) (pins 2 and 4). Two resistors are needed, a 330 Ohm (orange orange red) and 2.2 K (red red orange).
I mounted the Optical Sensor on a proto board, having carefully cut off the plastic bump on the bottom of the sensor. I also used a led with a 1K (brown black red) for signaling when something was activating the switch. According to the drawing 5 volts would work, so that’s what I used, along with analog pin 2 for input and digital pin 12 for the signaling led.
After running my sketch and dumping the sensor reading to serial I found that it idled at ~929 and when the sensor was activated it was ~1020. This is great, no problem to see a change of state, so I wrote a bit more code to activate the led. I did not include a delay as I wanted the led to react quickly.

Here is my code, feel free to do with it as you will!
/*
Demo for a slotted optical sensor.
I am sure that someone elses code is in here somewhere
*/
int inputPin = 2; // select the input pin for the potentiometer
int ledPin = 12; // select the pin for the LED
int val = 0; // variable to store the value coming from the sensor
void setup() {
pinMode(inputPin, OUTPUT); // declare the ledPin as an OUTPUT
pinMode(ledPin, OUTPUT);
Serial.begin(9600);
}
void loop() {
val = analogRead(inputPin); // read the value from the sensor
Serial.println(val);
if(val > 950){
digitalWrite(ledPin, HIGH); // turn the ledPin on
} else {
digitalWrite(ledPin, LOW); // turn the ledPin off
}
}
I am very excited to know how to set up this sensor. Next time I am going to find some with the hook up wires already soldered and heatshrinked on. For those that are curious, that is a Freeduino from NKC under there.
