mBot Light Sensor


Grade Level






Estimated duration
Longer description

Video: https://youtu.be/JwDHsSc0u7A

The light sensor on the mCore board measures light – the lighter it is, the higher the value, the darker it is, the lower the value. The range of the light sensor is 0-1023.

In this lesson, we are going to program the mBot to play a note if it senses there is a lot of light, and play a different not if it senses there is not a lot of light. For this, we will need the “IF” block. When we use an “IF” in programming, there are 3 parts to what we write:

  1. The “IF” itself
  2. The condition
  3. The code that is run, if the condition is met.

So we need to write something like this:

If (condition)

—- Do this code


The first thing I want to do in this lesson is to play some sound if it is dark. So the condition is “it is dark”, and the code is “play sound”:

If (it is dark)

—- Play sound.


Remember the light sensor returns a value between 0 and 1023, where high numbers represent a light environment. I would say a light sensor reading of less than 500 represents a dark environment. So we can write our code as:

If (the value on the light sensor IS LESS THAN 500)

—- Play sound.


Writing this in mBlock code, we need:

    1. An “if”


    1. A condition. The condition in this example is made up of 2 parts. We need the green “less than” block in the “Operators” Script:
      less-than-blockAnd we need the light sensor “block” from the “Robtots” scripts:
      light-sensor-blockThe condition is “the light sensor is less than 500”, so we can put the light sensor block in the left side of the “less than” block and write “500” in the right side. When putting the blue block inside the green block, make sure the left side of the blue block is aligned with the appropriate space of the green block. When the space in the green block has a white outline it is ready to receive the blue block:
      combine-blocksAnd when dropped in, it looks like this:
    2. Finally, we need some code that will be run if the condition is met:


When this code is put together, it looks like this:


When this code runs, it will test the condition once and then stop running. If we want it to continue to play music while dark we can add a forever loop. Also, remember to include a descriptive comment:


So, what if I wanted to play note C4 in the dark, but note D4 in the light. For this, we could use an “if/else” Control block:



  1. Develop a program where the robot runs forward in the light and stops in the dark.
  2. Develop a program where the robot dances in the dark (be creative with your dance moves) and rests in the light.
  3. Develop a program where the robot goes at different speeds depending on the light – the lighter it is, the faster it goes.
  4. Develop a program that plays lots of different notes – the more light sensed, the higher the note.

Construct Your Dreams!


Related resources