Sensors send numbers
A sensor measures the world around a device and sends the result to the program as data. The newer micro:bit has a touch logo, a temperature sensor, a microphone, an accelerometer and a light sensor. The temperature is given in degrees Celsius. The light level is a number from 0 (dark) to 255 (very bright). The program uses a question about the number to decide what to do. Because the world keeps changing, the sensor must be checked again and again, so the question sits inside while True. Everyday devices work the same way: an automatic tap checks for a hand, and a car’s parking sensor checks the distance.
| Sensor | What it measures | MicroPython |
|---|---|---|
| touch logo | touch | pin_logo.is_touched() |
| temperature | degrees Celsius | temperature() |
| microphone | loud sound | microphone.current_event() == SoundEvent.LOUD |
| accelerometer | movement | accelerometer.was_gesture("shake") |
| light sensor | light level 0–255 | display.read_light_level() |
1from microbit import * 2while True: 3 if temperature() > 30: 4 display.scroll("Hot")
scrolls Hot while the temperature is above 30
1from microbit import * 2while True: 3 if display.read_light_level() > 100: 4 display.show(Image.YES)
a tick appears when the light level is above 100
1from microbit import * 2while True: 3 if pin_logo.is_touched(): 4 display.scroll("Welcome")
scrolls Welcome while the logo is touched
Sensor hunt (no computer). With an adult, find five everyday devices that use a sensor, such as an automatic door, a phone that turns its screen, a hand dryer or a toy that reacts to a clap. For each one write what the sensor measures, what question the program might ask and what the output is. Then choose your favourite and write its question as “if … then …”. If you have a micro:bit and an adult to help, run the light-level program and cover the display with your hand.
| MicroPython | Sensor |
|---|---|
| temperature() | ? |
| display.read_light_level() | ? |
| pin_logo.is_touched() | ? |
1from microbit import * 2while True: 3 if temperature() > 25: 4 display.scroll("Warm")