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:
So we need to write something like this:
---- 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:
And we need the light sensor “block” from the “Robtots” scripts:
The 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:
And when dropped in, it looks like this:
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:
Construct Your Dreams!