Week 29 · Unit 12: Be a problem solver · 3 lessons
3
Measuring the light
Computing 5: Unit 12, pp. 159–170
GoalRead the light level, show it as a bar graph and use a rule with a less-than test.
New words
light level · a number from 0 (dark) to 255 (bright) that the board’s light sensor givesbar graph · a picture in which more lights show a bigger valueless than · the test < is true when the left value is smaller than the right valuesimulator · a screen that shows what a board would do
Explanation
The micro:bit has a light sensor. The block ‘light level’ gives a whole number from 0 to 255. A reading of 0 means dark and a reading of 255 means very bright. We store the reading in a variable. The block ‘plot bar graph of reading up to 255’ then lights more lights for a bigger number. 255 lights all 25 lights and 0 lights none. A rule can use the less-than test, such as ‘if reading < 100 then show Dim’. In a simulator we can move a slider to change the light level and test each case.
Worked examples
This rule shows ‘Dim’ when the reading is below 100 and ‘Bright’ in all other cases. The reading 100 is not less than 100, so it gives Bright.
reading
reading < 100?
Board shows
255
false
Bright
130
false
Bright
100
false
Bright
99
true
Dim
0
true
Dim
Trace five readings through the rule. Test the numbers around the limit, 99 and 100, as well as the biggest and smallest.
Reading
Lights that are on
0
none
about 128
about half
255
all 25
The bar graph gives a quick picture of the light. These readings show how the number of lights on changes.
Class activity
Light detective (groups of 3, a torch or lamp with an adult, paper). Draw a scale from 0 to 255 on a long strip of paper. Mark where you think each of these places would be: a dark cupboard, a classroom, a bright sunny window. Then write a rule such as ‘if the reading is less than 100, show Dim’. Which of your three places would show Dim? Check what changes if you move the limit to 50 or to 150. (If you have a micro:bit simulator, test your rule with the light slider.)
Practice
1
The rule is: if the reading is less than 50, show Night. Which of these readings show Night? 12, 50, 49, 200, 0
Reading
12
50
49
200
0
Night?
?
?
?
?
?
12, 49 and 0 show Night. 50 is not less than 50, and 200 is bigger.
2
What does the bar graph show when the light level is 255, and what when it is 0?
At 255 all 25 lights are on. At 0 none of the lights are on.
3
Ravi wants the board to show Dim when it is dark. He wrote this program. A dark cupboard gives the reading 20. What does the board show, and how should he fix it?
20 is not more than 100, so the condition is false and the board shows Bright, which is wrong. Change > to <, so that readings below 100 show Dim.
4
Why do we store the light level in a variable and not ask for it again in every test?
The light can change between two asks. If we store the reading once, every test uses the same number, and the program is also shorter.