Digital read (boolean value) from phototransistor

I would like to build a photogate similar to the one seen in this youtube video.

Its code:

import RPi.GPIO as GPIO
import time

GPIO.setmode(GPIO.BOARD)
GPIO.setup(11,GPIO.IN)

start=time.time()
stop=time.time()
gateState=False

try:
     while True:
          if (GPIO.input(11) != gateState):
               gateState = not gateState
               
               if (gateState == True):
                    start=time.time()
               else:
                    stop = time.time()

                    if stop - start > 0.001:
                         print "Time: ", stop - start, "s"
                         print "Speed: ", 3.3/(stop-start),"cm/s"
                         print " "
except KeyboardInterrupt:
     GPIO.cleanup()

My question: how is the the reading not always detecting some ambient light?

To elaborate: I understand that an analog read of a phototransistor may give values between 0-1023, but for the value to be 0 there would have to be an undetectable amount of light. Surely this is not the case is his experiment setup.

I understand I could do an analog reading and just set a threshold value depending on the sensitivity I would like/ environment etc, but the convenience of TRUE/FALSE would be easier. How is it accomplished in this video? I would prefer to use esp32 rather than his route of raspberry pi

What is the maximum digital input pin voltage on your MCU that would result in a logical LOW?
What is the minimum digital input pin voltage on your MCU that would result in a logical HIGH?

1 Like

Most of phototransistors have peak at infrared region, if you intend to sense visible light look for something more suitable (like TEPT4400).
Emitter to GND, collector to digital input with pullup.

ps. I didn't watch any videos...

It's not clear that you do. Or you have a different idea about what is hard:

  int photoDetector = analogRead(thePin);
  bool isItDark = photoDetector < 512;

  if (itIsDark) turnOnTheLight();

You could have other values for bright, dim, dark, whatever. Turn them into true or false.

a7

Almost certain this is the solution I am looking for, but I am having trouble locating info on the esp32 datasheet. A link would be appreciated.

Located this stack exchange post, but would prefer an official source

page 53 of this datasheet?

I'm not familiar with RasPI, but datasheet for MCU AtMega328 says max voltage for logical LOW is 0.3 times Vcc, for 3.3V that would be 3.3 * 0.3 = 0.99V. So your "light blocked" voltage would have to be less than 0.99V.
For a logical HIGH, that's 0.6 times Vcc, so your "not blocked" voltage would have to be greater than 1.98V.

1 Like

Yea.

If you use an op amp you can set a threshold for the light level you wish to trigger from.

1 Like