← Micro:bit

Chapter 5

Fun with Sensors

สนุกกับตัวตรวจจับ

  • A microcontroller becomes useful when it can sense the world around it.
  • The micro:bit V2 has 5 built-in sensors: microphone, compass, accelerometer, thermometer and light sensor.
  • In this chapter you build a hands-on project for every one of them.
Microphone 🎤 sound level 0 – 255 Compass 🧭 compass heading 0 – 359 ° Accelerometer 📐 acceleration x, y, z in mG Thermometer 🌡️ temperature in °C Light sensor ☀️ light level 0 – 255
The five onboard sensors, the block that reads each one, and the numbers it gives you.

5.1 Microphone & Sound Sensing ไมโครโฟนตรวจจับเสียง

  • The micro:bit V2 has a built-in speaker and also a microphone.
  • Three blocks use it. They are in the Input group.
👏 Sound clap, voice, music Microphone SPU0410 on the back 0 – 255 quiet → loud sound level
From a clap to a number: the microphone turns sound into a value from 0 to 255 that your program can read.
on [loud] sound event: runs when it gets loud (or quiet) set [loud] sound threshold to [128] setting: the dividing line (default 128) sound level value: the number 0 – 255 right now quiet side loud side 0 128 255 threshold sound above the threshold fires on loud sound
The three microphone blocks, and where the threshold sits on the 0–255 scale.
  • on [loud] sound comes in two kinds: on loud sound and on quiet sound. It fires when the sound goes above or below the threshold.
  • set [loud] sound threshold to [128] sets the dividing line. The default is 128, on a scale from 0 to 255.
  • sound level gives the current level: 0 is quiet, 255 is the loudest.

5.1.1 Show the sound on a bar graph แสดงค่าเสียงผ่าน plot bargraph

  • Test the microphone by drawing the level as a bar graph on the 5×5 LEDs with plot bar graph of.
  1. Step 1 — Drag plot bar graph: take plot bar graph of from the Led group and put it inside forever.
  2. Step 2 — Add sound level: take sound level from Input and drop it into the value slot.
  3. Step 3 — Set the maximum: type 255 as the "up to" value.
0 64 128 192 255
How many LEDs light up: level ÷ 255 × 25. Five sample levels are shown below.
level 0 → 0 LEDs
level 64 → 6 LEDs
level 128 → 13 LEDs
level 192 → 19 LEDs
level 255 → 25 LEDs
  • The LEDs fill from the bottom row upward as the sound gets louder.
  • Live telemetry: after you download the code, the LEDs rise and fall with the sound.
  • With the USB cable connected through WebUSB, press Show console Device in MakeCode.
  • You then see a live graph of the sound with the changing numbers.

💻 5.1.1 The microphone as a bar graph

forever
plot bar graph of sound level up to 255
See it in JavaScript
basic.forever(function () {
	led.plotBarGraph(input.soundLevel(), 255)
})

5.1.2 Clap counter with variable X ตรวจนับความดังเสียงแล้วเพิ่มค่า

  • Goal: each loud clap adds 1 to a counter and shows it on the LEDs.
  • Button A resets the counter to 0.
on button A pressed set X to 0 show number X forever sound level > 128 ? no: check again yes change X by 1 show number X ↻ X after each clap: 0 1 2 3 each arrow is one loud sound
The clap counter: variable X is a box that holds a number. Each loud sound adds 1 and shows it; button A puts it back to 0.

15-step assembly ขั้นตอนการต่อบล็อก

  1. Step 1 — Open Variables: open the Variables group.
  2. Step 2 — Make a variable: click Make a Variable... to create a new one.
  3. Step 3 — Name it X: type X and press Ok.
  4. Step 4 — Add on button A: drag on button A pressed from Input, so button A can reset the counter.
  5. Step 5 — Reset X to 0: put set X to 0 inside it.
  6. Step 6 — Add show number: put show number from Basic under it.
  7. Step 7 — Put X in it: drop the variable X into the show number slot.
  8. Step 8 — Add forever: drag forever from Basic.
  9. Step 9 — Add if then: put if then from Logic inside forever.
  10. Step 10 — Add a comparison: drop a 0 < 0 block from Logic into the if.
  11. Step 11 — Change to greater than: change the symbol to >.
  12. Step 12 — Set the threshold: change the number on the right to 128.
  13. Step 13 — Add sound level: drop sound level from Input on the left of the symbol.
  14. Step 14 — Increment X: put change X by 1 inside the if, so X goes up by 1 for each loud sound.
  15. Step 15 — Show the count: right-click show number X, choose Duplicate, and snap the copy under change X by 1.

💻 5.1.2 Clap counter — polling the sound level in forever

on button A pressed
set X to 0
show number X
forever
if sound level > 128 then
change X by 1
show number X
See it in JavaScript
let X = 0
input.onButtonPressed(Button.A, function () {
	X = 0
	basic.showNumber(X)
})
basic.forever(function () {
	if (input.soundLevel() > 128) {
		X += 1
		basic.showNumber(X)
	}
})

5.1.3 Counting fast claps: event vs polling ตรวจนับความดังเสียงแบบต่อเนื่อง

  • In 5.1.2 the program checks the sound, then waits for show number to finish before it checks again.
  • This is called polling: the code keeps asking "is it loud?".
  • If claps come quickly one after another, some fall in the gaps and are missed.
  • Fix: use an event. The on loud sound block is triggered by the hardware.
Polling (forever + if) check busy: show number check busy: show number clap 1: counted clap 2: missed clap 3: counted Event (on loud sound) X+1 show X+1 show X+1 all three claps are handled
Polling can miss a clap that arrives while the program is busy showing a number. The event version keeps every trigger from the hardware.
Microphone hardware notices a loud sound on loud sound change X by 1 show number X
The event version: the hardware notices the loud sound, and the handler runs by itself.

💻 5.1.3 The same counter as an event — on loud sound

on button A pressed
set X to 0
show number X
on loud sound
change X by 1
show number X
See it in JavaScript
let X = 0
input.onButtonPressed(Button.A, function () {
	X = 0
	basic.showNumber(X)
})
input.onSound(DetectedSound.Loud, function () {
	X += 1
	basic.showNumber(X)
})

💡 The technical difference

  • With fast claps, a program using on loud sound keeps every trigger from the hardware.
  • It handles them straight away, without waiting for an earlier command in a loop to finish.

Next: 5.2 Electronic Compass →

5.2 Electronic Compass ใช้งานเข็มทิศอิเล็กทรอนิกส์

  • Every micro:bit, from the first version to today, has a sensor for magnetic fields. It measures the Earth's magnetic field.
  • Read it with show number plus the compass heading block from Input.
  • The heading is from 0 to 359 degrees. North is 0.
NESW 0°45°90°135°180°225°270°315°
Compass heading: 0° is north and the angle grows clockwise, so east is 90°, south 180° and west 270°. The colours show the ranges the program in 5.2.2 uses.

5.2.1 Read the heading in degrees ทดลองอ่านค่าองศา

  1. Step 1 — Place show number: drag show number from Basic into forever.
  2. Step 2 — Add compass heading: drop compass heading (°) from Input into it.

Tilt calibration (first run):

  • After the download, the LEDs scroll "TILT".
  • Tilt the board in every direction until every LED is lit. This calibrates the compass.
  • When it is done, a smiley face appears for a moment.
  • Then the number shows the direction the top of the board is pointing.
scrolls "TILT" tilt to fill every LED smiley = done heading shows
Calibration: tilt the board so the lit LED rolls around. Each pass fills more LEDs, until the whole screen is lit and the smiley appears.
start: one LED
tilting: it fills
almost full
all lit
smiley: done

💻 5.2.1 Reading the heading in degrees

forever
show number compass heading (°)
See it in JavaScript
basic.forever(function () {
	basic.showNumber(input.compassHeading())
})

5.2.2 Turn degrees into N, E, S and W แปลงค่าองศาเป็นตัวอักษรย่อประจำทิศ

  • A letter is easier to read than a number.
  • The program picks a letter by checking which range the heading falls in.
N E S W N 0 45 135 225 315 359
The same ranges laid out flat from 0 to 359. North appears at both ends because it wraps around.
degree < 45 ? yes show string "N" no degree < 135 ? yes show string "E" no degree < 225 ? yes show string "S" no degree < 315 ? yes show string "W" no else show string "N"
The if-ladder: the heading is tested from the top down and the first test that is true picks the letter.

12-step cardinal-direction ladder

  1. Step 1 — Make a variable: open Variables and click Make a Variable...
  2. Step 2 — Name it degree: call it degree.
  3. Step 3 — Meet its blocks: the editor adds degree, set degree to and change degree by.
  4. Step 4 — Place set degree: drag set degree to into forever.
  5. Step 5 — Read the heading: drop compass heading (°) from Input into it.
  6. Step 6 — Add if then else: drag if then else from Logic underneath.
  7. Step 7 — Add a comparison: put a 0 < 0 block from Logic in the if.
  8. Step 8 — Add degree: drop the variable degree on the left side.
  9. Step 9 — Set 45: type 45 on the right.
  10. Step 10 — Show "N": put show string "N" in the then part (under 45° is north).
  11. Step 11 — Click the plus: press + on the if block to add another test.
  12. Step 12 — Finish the ladder: add the other tests, as in the full program below.

Complete compass program

💻 5.2.2 Degrees turned into N, E, S and W

forever
set degree to compass heading (°)
if degree < 45 then
show string N
else if [degree < 135] then
show string E
else if [degree < 225] then
show string S
else if [degree < 315] then
show string W
else
show string N
See it in JavaScript
let degree = 0
basic.forever(function () {
	degree = input.compassHeading()
	if (degree < 45) {
		basic.showString("N")
	} else if (degree < 135) {
		basic.showString("E")
	} else if (degree < 225) {
		basic.showString("S")
	} else if (degree < 315) {
		basic.showString("W")
	} else {
		basic.showString("N")
	}
})

Next: 5.3 3-Axis Accelerometer & 2D Spirit Level →

5.3 3-Axis Accelerometer & Tilt Sensing ตรวจจับความเอียง

  • The accelerometer (ตัวตรวจจับความเร่ง) is another very popular sensor. It lets you build things like a tilt meter.
  • It has 3 axes: x, y and z. It senses acceleration, tilt and movement.
  • Range: ±2G. It reports in milli-G (mG).
  • 1000 mG = 1 G, and 1 G is about 9.81 m/s².
x left ↔ right y top ↔ bottom z through the screen
The three axes of the board. The sensor reports how much of gravity (or of a push) lies along each one.
negative: tilted left positive: tilted right -2000 -1023 0 +1023 +2000 x acceleration in mG (about ±1 G for a 90° tilt)
Gravity is the yardstick: lying flat, the board reads about (0, 0, −1023). Tilting it moves the weight onto x or y.

5.3.1 Test the accelerometer: 11 gestures ทดสอบตัวตรวจจับความเร่งอย่างง่าย

  • MakeCode's on [gesture] block knows 11 movements.
  • In this test, each gesture shows its own number.
shake shows 0 logo up shows 1 logo down shows 2 screen up shows 3 floor screen down shows 4 tilt left shows 5 tilt right shows 6 free fall shows 7
The gestures used in the test program, with the number each one shows.
Gesture option What you do with the board Number shown
shake Shake the micro:bit. 0
logo up Stand the board up with the logo on top. 1
logo down Turn the board over so the logo is at the bottom. 2
screen up Lay the board flat, screen facing the sky. 3
screen down Lay the board face down, screen toward the floor. 4
tilt left Tilt the board to the left. 5
tilt right Tilt the board to the right. 6
free fall Let the board drop straight down (free fall). 7
3g, 6g, 8g Three kinds of hard knock. They complete the 11 gestures but are not used in this test. none

💻 5.3.1 Gesture test — every movement shows its own number

on shake
show number 0
on logo up
show number 1
on tilt left
show number 5
on tilt right
show number 6
on free fall
show number 7
See it in JavaScript
input.onGesture(Gesture.Shake, function () {
	basic.showNumber(0)
})
input.onGesture(Gesture.LogoUp, function () {
	basic.showNumber(1)
})
input.onGesture(Gesture.TiltLeft, function () {
	basic.showNumber(5)
})
input.onGesture(Gesture.TiltRight, function () {
	basic.showNumber(6)
})
input.onGesture(Gesture.FreeFall, function () {
	basic.showNumber(7)
})

5.3.2 Show x and y on the LEDs: a 2D spirit level แสดงผลแนวแกน X และ Y ด้วย LED 5x5

  • Use acceleration (mg) to read the tilt along x and y.
  • Keep the readings in variables X and Y, then light one LED with plot x y.
  • Tilt the board and the lit LED slides like the bubble in a carpenter's level.

The maths, in three steps

  1. Step 1 — Shift the range: the raw reading runs from -1023 to +1023. Add 1023 and it runs from 0 to 2046.
  2. Step 2 — Divide by 420: 2046 ÷ 420 ≈ 4.87, so the result runs from 0 to about 4.87.
  3. Step 3 — Drop the decimals: that leaves the whole numbers 0, 1, 2, 3, 4, which are exactly the 5 LED columns.
raw: acceleration (mg) x -1023-603-183+237+657+1023 column 0 column 1 column 2 column 3 column 4 0420840126016802046 after adding 1023 ÷ 420 → 0.00 … 4.87, then drop the decimals → 0, 1, 2, 3, 4
Each slice of 420 mG is one LED column: the raw reading is shifted by 1023, divided by 420, and the decimals are dropped.
  • Tilt the board left: the LED moves to the far left. Tilt it right: it moves right, like the bubble in a spirit level.
tilted left
flat: middle
tilted right

9-step build

  1. Step 1 — Open Variables: open Variables and click Make a Variable...
  2. Step 2 — Create X and Y: make X for the x reading and Y for the y reading.
  3. Step 3 — Add clear screen: put clear screen from Basic in forever.
  4. Step 4 — Add set X to: snap set X to underneath.
  5. Step 5 — Nest the maths: put a 0 + 0 block inside a 0 / 0 block from Math.
  6. Step 6 — Attach it: drop that calculation into the value slot of set to.
  7. Step 7 — Formula for X: add acceleration (mg) x from Input to make (acceleration (mg) x + 1023) / 420.
  8. Step 8 — Formula for Y: repeat step 7 for Y, using acceleration (mg) y.
  9. Step 9 — Add plot x y: snap plot x [X] y [Y] from Led at the end to light that LED.

💻 5.3.2 Spirit level — the bubble follows the tilt

forever
clear screen
set X to (acceleration (mg) x + 1023) / 420
set Y to (acceleration (mg) y + 1023) / 420
plot x X y Y
See it in JavaScript
let X = 0
let Y = 0
basic.forever(function () {
	basic.clearScreen()
	X = (input.acceleration(Dimension.X) + 1023) / 420
	Y = (input.acceleration(Dimension.Y) + 1023) / 420
	led.plot(X, Y)
})

Next: 5.4 Temperature Sensor →

5.4 Temperature Sensing การตรวจจับอุณหภูมิ

  • The micro:bit has no separate thermometer. It uses a temperature sensor inside the microcontroller chip.
  • The chip's heat is equal to or close to room temperature.
  • Warmer air heats the chip's case, and the heat passes on to the sensor inside.
  • The chip warms itself a little while it runs, so the reading can be a bit warm.
Room air warm or cool heat nRF52833 chip 🌡️ sensor inside temperature (°C)
The reading is the chip's own temperature: room heat plus a little heat from the chip working.

5.4.1 Show the temperature แสดงค่าอุณหภูมิอย่างง่าย

  1. Step 1 — Place show number: drag show number into forever.
  2. Step 2 — Add temperature: drop temperature (°C) from Input into it.

5.4.2 An overheat siren สร้างเงื่อนไขจากค่าอุณหภูมิที่กำหนด

  • Goal: when the temperature goes above a set value, play music from the speaker.
normal: just show the number above 30: alarm plays 0 °C 10 °C 20 °C 30 °C 40 °C 50 °C
Where 30 °C sits: above it, the alarm plays.
forever show number temperature (°C) temperature > 30 ? yes play sound giggle no: back to the top ↻
The program runs this loop forever: show the temperature, then test it against 30.
  1. Step 1 — Show the temperature: show number (temperature (°C)) displays it on the LEDs.
  2. Step 2 — Add a condition: add an if block and a comparison from Logic set to >.
  3. Step 3 — Set the 30 °C threshold: put temperature (°C) in the comparison and type 30.
  4. Step 4 — Add the sound: put play sound giggle until done inside the if.
  • Testing the alarm: after the download, the LEDs show the temperature.
  • When it goes above 30 °C, music plays from the speaker straight away.
  • To test it, warm the chip gently with your hand or a warm (not hot) object.

💻 5.4 Thermometer with an alarm above 30 °C

forever
show number temperature (°C)
if temperature (°C) > 30 then
play sound giggle until done
See it in JavaScript
basic.forever(function () {
	basic.showNumber(input.temperature())
	if (input.temperature() > 30) {
		music.play(music.builtinPlayableSoundEffect(soundExpression.giggle), music.PlaybackMode.UntilDone)
	}
})

Next: 5.5 Ambient Light Sensor →

5.5 Light Sensing via 5x5 LEDs การตรวจจับแสง

  • The micro:bit has no separate light sensor.
  • Instead, 9 of the LEDs do the job of a light sensor.
  • This is clever but not very sensitive, so treat the numbers as a rough guide.
☀️ Light white light LED (reverse-bias) light reaches the semiconductor junction volts Microcontroller pin reads it light level
An LED normally makes light. Run backwards (reverse-biased), it works the other way: light in, a small voltage out.

How it works physically:

  • The LEDs are reverse-biased (ไบแอสกลับ) while sensing.
  • White light passing through the LED's case reaches the semiconductor junction inside, and a small current flows.
  • That makes a voltage on a pin of the main microcontroller.
  • The result is a number from 0 (completely dark) to 255 (very bright).

5.5.1 Show the light level แสดงค่าแสงด้วย LED 5x5

  • Use the light level block from Input to read the brightness.
dark side bright side 0 128 255
Light level runs from 0 (dark) to 255 (bright). The alarm program below uses 128 as its dividing line.

💻 5.5.1 Reading the light level, 0 to 255

forever
show number light level
See it in JavaScript
basic.forever(function () {
	basic.showNumber(input.lightLevel())
})

5.5.2 Switch a sound with light: a light alarm เปิดปิดไฟด้วยการตรวจจับแสง

  • 5.5.1 only reads the light. Here we use the reading in a condition.
  • When the light level goes above a set value, a sound plays.
forever light level > 128 ? yes set volume 255 play sound giggle no ↻
The light alarm: if the light level is above 128, set the volume to full and play the sound.
  1. Step 1 — Add the test: use if then and a comparison from Logic.
  2. Step 2 — Compare with 128: drop light level from Input into the comparison and compare it with 128.
  3. Step 3 — Set the volume: add set volume 255 to fix how loud the sound is.
  4. Step 4 — Play the sound: add play sound giggle until done, or pick another tune.

💻 5.5.2 Light alarm — it sounds when the light goes above 128

forever
if light level > 128 then
set volume 255
play sound giggle until done
See it in JavaScript
basic.forever(function () {
	if (input.lightLevel() > 128) {
		music.setVolume(255)
		music.play(music.builtinPlayableSoundEffect(soundExpression.giggle), music.PlaybackMode.UntilDone)
	}
})
  • Testing the light alarm: point the board at a light, or shine a torch on the LEDs.
  • The light level rises above 128 and the music plays from the speaker.
  • Cover the LEDs with your hand and the music stops.
light level < 50 ? yes: dark LEDs on (night light) no: bright → LEDs off
Try it yourself: flip the test to light level < 50 and the same idea makes a night light that switches on in the dark.

Next: Sensor Hardware Map Explorer →

Interactive micro:bit V2 Sensor Architecture

Hover over or tap any sensor on the real photograph of the back of the micro:bit V2.

🔍

micro:bit V2 Onboard Environmental Sensors Suite

Interactive Map
micro:bit V2 Back View - Sensors and Audio
👉

Hover or tap the SPU0410 Mic, LSM303AGR Compass/Motion chip, nRF52833 Core Thermometer, or Speaker.

Next: Test Your Knowledge with the Quiz →

Chapter 5 Review & Self-Check

sound 128
spirit level flat
compass calibrated
night light
  • Check what you know about sound thresholds, the clap-counter variable, compass calibration, the accelerometer formula, the chip thermometer and light sensing with LEDs.
1. What is the numeric reading range of the micro:bit V2 MEMS microphone `sound level` block?
2. Before using the electronic compass for the first time, why does micro:bit ask you to tilt the board in a circle?
3. What degree range does the `compass heading` block return?
4. How does the spirit level map acceleration (-1023 to +1023 mg) onto LED coordinates 0 to 4?
5. Where does the `temperature (°C)` block measure heat from?
6. How does the micro:bit detect light levels when there is no dedicated photo-resistor on the front?
7. What does `plot bar graph of ... up to 255` draw on the display?
8. Which block fires on its own the moment a clap is heard?