Photo Interrupter Sensor Questions

Hi

I am new to this forum but I have searched here to find answers, while I could answer many questions I have a few I couldn’t.

My project is using a HY860N Photo Interrupter, see picture for drawing, it is wired up as per SparkFun drawing I found.

The code I am using is

int photoPin = 1; //A1
int val;
void setup()
{
Serial.begin(9600);
}

void loop()
{
val= analogRead(photoPin);
Serial.println(val);
delay(1000);
}

Results in serial window…

37 //Open
37 //Open
38 //Open
37 //Open
37 //Open
1019 //Blocked
1018 //Blocked
1017 //Blocked
1016 //Blocked
1017 //Blocked
30 //Open
30 //Open
30 //Open
30 //Open
30 //Open

When I put a multimeter across 1 and 2 where marked on picture. I get about 0.2V when open and about 5V when blocked.

Q1. My question is why doesn’t this work when I use a digital pin?
Q2. Newbie question might be answered in the first question, the numbers in the results how do I calculate into voltage?

What does the code look like for the failing digital version?

To calculate voltage from raw ADC counts you need to know the value of the analog reference voltage and the ADC resolution. On a Uno, using the default reference, the reference voltage is the supply voltage (around 5V) and resolution is 10 bits. So the formula to calculate voltage (for Uno) is ADC counts * (Vref/1024).
The numbers shown should work with a digital input.

Thank you for the answers, they are much appreciated.

Don't know what I was doing but the digitalRead is now working?

The code I am using is....

int photoPin = 7; //D7
int val;
void setup()
{
Serial.begin(9600);
pinMode(photoPin, INPUT); //works with or without this line?
}

void loop()
{
val= digitalRead(photoPin);
Serial.println(val);
delay(1000);
}