In this tutorial, I want to show you how to set up and use a small infrared light barrier, which gives a signal as soon as the light barrier is interrupted. By traversing both photocells one behind the other, the speed can be measured.
As soon as the light barrier is interrupted, a positive signal should be sent, otherwise a negative (0). I use a pull-up resistor with the IR receiver (black) instead of the switch.
Once you’ve set up the circuit, the LED should light up as soon as the light barrier is closed (for example, fingers in between).
So that the speed can now also be measured, the time is measured, which passes, until both light barriers are run through. If the distance is not exactly 10cm, you should adjust this.
sudo nano distance_test.py
And add the following code
import RPi.GPIO as GPIO
GPIO_BEGIN_PIN = 4
GPIO_END_PIN = 17
TIMEOUT = 5 # sek
if __name__ == '__main__':
start_time, end_time = 0, 0
while GPIO.input(GPIO_BEGIN_PIN) == GPIO.LOW:
start_time = time.time()
end_time = 0
while GPIO.input(GPIO_END_PIN) == GPIO.LOW and time.time()-start_time < TIMEOUT:
if time.time()-start_time >= TIMEOUT:
end_time = time.time()
speed = DISTANCE / (end_time - start_time)
print "Geschwindigkeit: %.2f cm/s" % speed
Save and exit with CTRL + O and CTRL + X. Now we can start it.
sudo python distance_test.py
If the script does not work properly, it is most likely due to the fact that the photocells do not point exactly to each other and so, some electricity can flow, but this is out of the accepted range and it is not determined whether 0 or 1
Concluding with another picture of my structure::