It's easy to read a break beam sensor from CircuitPython code using built-in digital input/output capabilities.
First wire up a break beam transmitter and receiver just like you would for an Arduino. Here's an example of wiring to a Feather M0:
- Board 3V (or 5V if your board has it) to both receiver and transmitter red wire.
- Board GND to both receiver and transmitter black wire.
- Board D5 (or any other digital input) to receiver yellow wire.
Next connect to the board's serial REPL so you are at the CircuitPython >>> prompt.
Now import the board and digitalio modules that allow you to create a digital input. Be sure you've read the CircuitPython digital I/O guide for more background too!
import board import digitalio
Create a digital input for the pin connected to the receiver, D5 in this case:
break_beam = digitalio.DigitalInOut(board.D5) break_beam.direction = digitalio.Direction.INPUT break_beam.pull = digitalio.Pull.UP
Notice you set the direction property to input, and the pull property to a pull-up (just like the digital I/O guide mentions). This is necessary to configure the digital input with an internal pull-up resistor so it always reads a good value from the break beam sensor.
Checking if the sensor detects a break is as easy as reading the value property of the digital input. When value is true it means the input is at a high logic level which occurs when the receiver can see the transmitter and the beam is not broken. However if you get a value of false the input is at a low logic level which means the receiver cannot see the transmitter and the beam is broken!
Try reading the value with nothing blocking the transmitter and receiver:
break_beam.value
Now put something large and opaque, like your hand, in front of the transmitter to block the light. Read the value again:
break_beam.value
Awesome! Notice the digital input value was true, or at a high logic level, when nothing was blocking the beam. As soon as your hand covered the beam the input value turned false, or low logic level, to indicate an obstruction.
You can put all of this together into a complete program that prints a message whenever the beam is blocked. Save this as main.py on your board and examine the serial monitor for output, a message is printed when the beam is blocked:
import time import board import digitalio # Create digital input with pull-up resistor on pin D5 # for break beam sensor. break_beam = digitalio.DigitalInOut(board.D5) break_beam.direction = digitalio.Direction.INPUT break_beam.pull = digitalio.Pull.UP # Main loop runs forever and prints a message once a second # while the sensor is blocked/broken. while True: if not break_beam.value: # Break beam input is at a low logic level, i.e. broken! print('Beam is broken!') time.sleep(1.0) # Delay for 1 second and repeat again.
That's all there is to reading a beam break sensor with CircuitPython!
Text editor powered by tinymce.