This reflectance sensor cost a couple of pounds from an online electronics store. It fits nicely into a breadboard and turned out to be quite easy to use. The sensor looks like this,
There is not a lot of documentation around for working with this component. There are some dodgy labels on one side of the package. If you hold it so you are looking at that side and number the pins from the left, you connect them up as follows,
1 - Connect to GND.
2 - Connect to 3V using a 470 Ohm resistor.
3 - Connect to GND.
4 - Connect to 3V using a 47K Ohm resistor. Connect to pin 0.
Notice that the two resistors are different. The high value resistor is needed to make sure we get a clear difference in the readings we get from the sensor.
Here is the simple code to get you going and test that you can make the sensor work.
from microbit import * while True: x = pin0.read_analog() print(x) sleep(50)
You need to open the REPL window or use a terminal emulator to view the readings. For me, when the sensor is not being obstructed, I get a very low reading, about 130 or so. When I put my hand over the sensor, I get a higher number, over 900.
This is more than enough of a difference to get a clear sense of whether or not there is an object over the sensor.
- Add some statements to work out whether or not the sensor has detected an object. Start by making something simple happen on the matrix and then consider the possibility of some other components.
- This is a nice component to use for an input in a game. Line up a couple of these and you can work out whether or not a hand is moving left or right over the sensors. This could be an interesting way to control a game. Perhaps you could use the gestures for on/off with an LED or pattern on the matrix.
- Lined up well, you could work out when someone opened a door or a drawer and sound an alarm.