BBC micro:bitSensing Light

Introduction

On the end of each of the fins is a tiny light sensor. With two of the three analog pins already in use for driving the motors, these two analog sensors are both connected to pin 2. There is a select pin, pin 16. You write a digital 0 to this pin to read the left light sensor, a 1 to read the right sensor.

Having two light sensors means that you can compare the two readings and use that difference in light levels to decide how to move the robot. You can also use average of the two readings to get a sense of the light level in a room.

The readings you get from light sensors vary a lot. You get a reading of 0 when it is completely dark to 1023 when there is bright light shining on the sensor. The background reading, when you are not shining a light on the sensor or covering it up, depends entirely on the lighting of the place where you are working.

Programming

This is a test program. You need to be using a PC with serial port drivers and something like Mu to view the REPL output. The function is used to get the readings for the left and right sensors, printing to the REPL window. Covering up the sensors and shining lights on them when running this program is useful.

```from microbit import *

# select: 0 = left 1 = right
# dark 0, light 1023
def SenseLight(select):
pin16.write_digital(select)

while True:
print(SenseLight(0), SenseLight(1))
sleep(50)
```

This is the simplest version of a light following program. It demonstrates the principle but needs a lot of optimisation. The function compares the two readings on the sensors and makes the robot head in the direction of the brighter light. You need to point a light source at the sensors to control the movement of the robot.

```from microbit import *

# select: 0 = left 1 = right
# dark 0, light 1023
def SenseLight(select):
pin16.write_digital(select)

def Drive(lft,rgt):
pin8.write_digital(0)
pin12.write_digital(0)
if lft<0:
pin8.write_digital(1)
lft = 1023 + lft
if rgt<0:
rgt = 1023 + rgt
pin12.write_digital(1)
pin0.write_analog(lft)
pin1.write_analog(rgt)

lft = SenseLight(0)
rgt = SenseLight(1)
if lft>rgt:
Drive(100,400)
elif rgt>lft:
Drive(400,100)
else:
#straight on
Drive(400,400)
sleep(20)

while True: