This tutorial will show you how to use a light sensor to tell an automatic pet feeder that the food bowl needs to be refilled. Basically, the light sensor is at the bottom of the food bowl and when the light sensor detects light that means there is not enough food on top of it -- thus triggering a refill.
Step 1: Complete the Building an Automated Pet Feeder tutorial
The Building an Automated Pet Feeder tutorial will guide you through the process of building the food dispenser itself (not using a light sensor yet). This tutorial can then be extended to be used in several different pet feeder projects. Once you have completed that tutorial, you can come back here to learn how to use the micro:bit's light sensor and connect it with the basic pet dispensing code.
Step 2: Learning to use the micro:bit light sensor
The micro:bit's 5x5 LED board doubles as a light sensor and its value can be accessed by the light level block found in the Input block category. Its value can range from 0 (darkest) to 255 (brightest).
If you'd like to do some testing to see what value the light sensor has when you expose it to different amounts of light you can have the micro:bit constantly print out its light value to the screen using the below code:
You'll also want to test it out by putting it in the bottom of a food bowl and seeing what its light level is when the bowl is full compared to when it is running out of food.
I decided that 10 was a good threshold for my light sensor. When the bowl was full enough the light sensor's value was around 5-7, and when it started to get exposed to the light and it felt like an appropriate time for a refill the sensor would get above 10. You might decide you want a higher value to use as your threshold if you want less frequent refills than I did.
Step 3: Connect the automated pet feeder code to the light sensor code
As I mentioned in step 2 I decided to use 10 as my threshold to decide whether or not to refill the bowl. If the light sensor value was getting a reading below 10 then that means there is enough food (because the food is blocking the LEDs from the light), and when the light sensor was over 10 that the bowl needed a refill. So I wrote a program that constantly checks the light levels and if it is >= 10 to move the servo to 90 degrees and dispense more food. Otherwise, it would keep the food bottle shut.