Cutebot - Light Sensor Image by Freepik

Cutebot - Light Sensor

In this series of tutorials we will be using the Python programming language to instruct an Elecfreaks Smart CuteBot robot car to perform a range of tasks including basic movements, line tracking, and light & object detection. In the previous tutorial, we instructed the Smart CuteBot robot car to perform basic movements including moving forwards, reversing and stopping. In this tutorial, we will instruct the Smart CuteBot to detect and react to different levels of light intensity.

Requirements

Please ensure that you have read and followed the instructions described in our CuteBot - Getting Started tutorial in order to prepare your Micro:bit, and hence your Smart CuteBot, for programming.

Light Sensor

A light sensor is integrated into the front of the Micro:bit V2 board. In this tutorial, we will instruct the Smart CuteBot to detect different levels of light intensity and move towards a light source when a specified light intensity threshold has been passed, as demonstrated in the animation below.

Follow the Light

In this section, we will develop a Python program that instructs the Smart CuteBot to move towards a light source when a specified light intensity threshold has been passed.

def on_forever():

    # If the light level is greater than a certain number e.g. 200.
    # 0 = pitch black <---> 255 = bright white.
    if input.light_level() > 200:

        # Move forwards.
        cuteBot.motors(20, 20)

    else:

        # Otherwise stop the car.
        cuteBot.stopcar()

# Keep running the 'on_forever' function in the background in a forever loop.
basic.forever(on_forever)

We begin the Python code above by defining a custom function called on_forever. This custom Python function instructs the Smart CuteBot to move forwards when the intensity level of the light detected by the Micro:bit's light sensors passes a specified threshold (200 in our example), where the detected light level can range from 0 (pitch black) to 255 (bright white light). This is achieved by testing the value returned by the input.light_level() method within a conditional if statement. If the light level does not pass the specified threshold, then our custom Python function instructs the Smart CuteBot to stop.

Finally, we specify that our custom on_forever function should run continuously in the background. This is achieved by calling the basic.forever(body: ()) method, with the first and only parameter set as the name of our custom Python function i.e. on_forever that will be executed continuously in the background within a forever event-based loop.

To learn more about the basic functions and actions integrated with the Micro:bit, please refer to the Micro:bit Basic API documentation.

Jillur Quddus
Written by

Jillur Quddus

Computational Mathematician @ HyperLearning AI