Skip to content
Cart
Invisible World

Invisible World Limited Edition micro:bit Kit

Invisible World — Limited Edition micro:bit Kit. Discover magnetism, light, sound, moisture, infrared, and gravity.

Discover the Invisible World Around You

Magnetic fields, infrared signals, temperature, gravity, and other invisible phenomena are all around us. What if you could see them?

Build a portable instrument using a micro:bit, sensors, and a colorful TFT display. Keep the display and power circuit connected while you switch sensors for each discovery. You'll turn real measurements into moving graphics, numbers, and experiments of your own.

Make It Your Own with AI. Every Invisible World program is a starting point for your own invention! Copy its MicroPython code into an AI tool like ChatGPT or Claude, describe what you want to change, then test the results on your micro:bit. Try new graphics, combine sensors, or invent something entirely new.

Start Here — Build Your Portable Instrument

First, open the micro:bit Python Editor in another tab. You'll use it to load the ready-to-run MicroPython programs from the chapters.

Build the micro:bit and TFT display circuit once. For each later chapter, keep this base in place and change only the experiment sensor.

Wiring & Breadboard Layout — Open While Building

Use the printed pin labels on your TFT. Power off before connecting or moving wires. Connect VCC and BL only to the regulated 3V supply, never to battery Vin.

Invisible World breadboard setup: blue highlights show the permanent TFT display and power rail connections; yellow highlights show the experiment circuit area.
TFT label micro:bit I/O Edge
GND GND
VCC 3V
SCL P13 (SPI clock)
SDA P15 (SPI MOSI)
RES P12
DC P8
CS P16
BL Regulated 3V (BL, always-on backlight; do not use battery Vin)

The TFT labels SCL and SDA refer to SPI clock and data, not I²C connections. This same wiring reference remains available in Chapter 1.

What's in Your Kit? — Bill of Materials

Expand to check the supplied parts, quantities, and Parallax SKU links.

Component SKU Qty
micro:bit GO 10th Anniversary 32718 1
Parallax Edge I/O Adapter 32710 1
1.8-inch ST7735 TFT Display 26973 1
Vishay TSOP38438 38 kHz IR receiver 350-00064 1
Phototransistor through-hole 350-00029 1
Moisture / conductivity probe 28092 1
400-point Breadboard 700-32023 1
12mm x 3mm magnets None 1
10mm x 2mm magnets None 1
6mm x 2mm magnets None 1
10K Temperature Sensor Probe, 1m Waterproof Stainless Steel 3950 NTC 28093 1
10k resistor 150-01030 8
1k resistor 150-01020 4
220 Ω resistor 150-02210 2
100nF ceramic capacitor None 1
3-inch jumper wires (bags of 10) 800-00016 2
Complete Engineering Schematic — Revision D

This is the full electrical reference. It shows all sensor options; build only the sensor circuit for the chapter you're using. Infrared, temperature, and moisture circuits share P2, so use them one at a time.

Invisible World master engineering schematic, Revision D, showing micro:bit, TFT display, IR receiver, phototransistor, thermistor, and moisture probe

Useful Words — Quick Student Glossary (Optional)

You can complete every experiment without memorizing these terms. Return here if a new word appears.

TFT
A small color display that turns the micro:bit's data into pictures and numbers.
Sensor
A component that responds to something happening around it, such as light, temperature, or movement.
Analog signal
An electrical value that can vary gradually, like the voltage from a temperature sensor.
ADC (analog-to-digital converter)
The micro:bit's way of turning an analog voltage into a number. Our examples use readings from 0 to 1023.
SPI (Serial Peripheral Interface)
The fast connection used by the micro:bit to send drawing commands and pixels to the TFT display.
RGB565
A way of storing a display color using groups of bits for red, green, and blue.
Infrared (IR)
Light just beyond the red end of what our eyes normally see. Some remote controls send information with it.
SIRC
A method used by some Sony infrared remotes to encode button messages.
RAW reading
A sensor's unconverted number; it is not automatically a percentage or a scientific unit.
Thermistor / NTC
A temperature-sensitive resistor. An NTC thermistor's resistance decreases as it gets warmer.
Calibration
Saving reference readings so later measurements can be compared with something known.
Beta value
A number describing how a particular thermistor's resistance changes with temperature. Python handles its calculation.
Getting Started — Five Steps
  1. Install the micro:bit. Insert it into the Parallax Edge I/O Adapter in the correct orientation. Leave power disconnected while wiring.
  2. Prepare the breadboard. Position the adapter and identify the 3V and GND rails. Confirm they are not shorted together.
  3. Wire the permanent TFT. Open the “Wiring & Breadboard Layout” drop-down near the top of this page and connect every display pin as shown. Check labels carefully.
  4. Run your first program. Connect USB. Open Chapter 1 → Experiment 1.1, use Copy Code, paste it into the Python Editor, and flash your micro:bit. If the TFT is dark, check VCC, GND, and BL with power disconnected before rewiring.
  5. Go portable. Once the program works, disconnect USB and power the micro:bit from the supplied battery pack. Keep the electronics and battery pack dry.

For later chapters: Turn power off before swapping sensors. Keep the TFT circuit in place, and connect only one circuit at a time to the shared P2 pin.

1. Magnetism — The Invisible Field 
Invisible World engineering schematic Rev D, section A: SPI TFT display
Engineering schematic · Section A · Rev D

Five adventures. One circuit. Turn magnetic fields into bold TFT graphics, compare magnets, discover three-dimensional direction, and invent an instrument of your own. There is no worksheet to finish: try what interests you.

Start here: micro:bit, Parallax I/O Edge Adapter, the 128 × 160 TFT display, USB connection, battery power, and the magnets provided with the kit. Keep magnets away from magnetic storage media and sensitive devices, and never allow small magnets near young children.

One-time TFT wiring and setup
TFT label micro:bit I/O Edge
GND GND
VCC 3V
SCL P13 (SPI clock)
SDA P15 (SPI MOSI)
RES P12
DC P8
CS P16
BL Regulated 3V (BL, always-on backlight; do not use battery Vin)

Turn power off while connecting wires. The labels SCL and SDA on this TFT indicate SPI clock and data. This chapter uses the exact wiring from the working prototype.

Open the micro:bit Python Editor. Copy a complete program into the editor and flash it to your micro:bit.

1.1 Can You See a Magnetic Field?
TFT showing simulated magnetic field rings
Illustrative TFT simulation using the tested rendering logic.

Make It Happen

Run our tested Magnetic Field & Change Meter program. Move a magnet near the stationary micro:bit and watch the red-and-white rings tighten and speed up. Press A to switch between FIELD nT and CHANGE uT. Press B to freeze; A+B resets the baseline.

💻  View & Copy MicroPython Program — 1.1 Magnetic Field Meter  ▾ Expand / collapse

from microbit import *
import math

# Invisible World 1.1 - Magnetic Field Meter
# Selectable Magnetic Field and Change Meter
# Parallax Inc. - SKU 32890
# micro:bit / 128x160 ST7735 TFT
# FIELD = total magnetic strength in nT
# CHANGE = change from baseline in uT
# No explicit compass calibration

W = 128
H = 160
RING_H = 120

# TFT: GND=GND, VCC=3V, SCL=P13, SDA=P15
# RES=P12, DC=P8, CS=P16
# BL: as established in tested hardware setup

cs = pin16
dc = pin8
rst = pin12
cs.write_digital(1)
dc.write_digital(1)
rst.write_digital(1)

spi.init(baudrate=8000000, bits=8, mode=0,
         sclk=pin13, mosi=pin15, miso=pin14)

def command(c):
    cs.write_digital(0)
    dc.write_digital(0)
    spi.write(bytes([c]))
    cs.write_digital(1)

def data(b):
    cs.write_digital(0)
    dc.write_digital(1)
    spi.write(b)
    cs.write_digital(1)

def init_tft():
    rst.write_digital(0)
    sleep(100)
    rst.write_digital(1)
    sleep(150)
    command(0x01)
    sleep(150)
    command(0x11)
    sleep(150)
    command(0x3A)
    data(bytes([0x05]))
    command(0x36)
    data(bytes([0x00]))
    command(0x13)
    sleep(10)
    command(0x29)
    sleep(100)

def window(x0, y0, x1, y1):
    command(0x2A)
    data(bytes([0, x0, 0, x1]))
    command(0x2B)
    data(bytes([0, y0, 0, y1]))
    command(0x2C)

BLACK = (0x00, 0x00)
RED = (0xF8, 0x00)
WHITE = (0xFF, 0xFF)
palette = [BLACK, RED, BLACK, WHITE]

distance = bytearray(W * RING_H)
for y in range(RING_H):
    dy = y - RING_H // 2
    for x in range(W):
        dx = x - W // 2
        distance[y * W + x] = int(math.sqrt(dx * dx + dy * dy))

BLOCK_ROWS = 8
block = bytearray(W * BLOCK_ROWS * 2)

def draw_rings(phase, width):
    window(0, 0, W - 1, RING_H - 1)
    cs.write_digital(0)
    dc.write_digital(1)
    for y0 in range(0, RING_H, BLOCK_ROWS):
        j = 0
        end_y = min(y0 + BLOCK_ROWS, RING_H)
        for y in range(y0, end_y):
            offset = y * W
            for x in range(W):
                d = distance[offset + x]
                band = ((d - phase) // width) & 3
                hi, lo = palette[band]
                block[j] = hi
                block[j + 1] = lo
                j += 2
        spi.write(block[:j])
    cs.write_digital(1)

FONT = {
    ' ': (0,0,0,0,0,0,0),
    '.': (0,0,0,0,0,12,12),
    '0': (14,17,19,21,25,17,14),
    '1': (4,12,4,4,4,4,14),
    '2': (14,17,1,2,4,8,31),
    '3': (30,1,1,14,1,1,30),
    '4': (2,6,10,18,31,2,2),
    '5': (31,16,30,1,1,17,14),
    '6': (6,8,16,30,17,17,14),
    '7': (31,1,2,4,8,8,8),
    '8': (14,17,17,14,17,17,14),
    '9': (14,17,17,15,1,2,12),
    'A': (14,17,17,31,17,17,17),
    'C': (14,17,16,16,16,17,14),
    'D': (30,17,17,17,17,17,30),
    'E': (31,16,16,30,16,16,31),
    'F': (31,16,16,30,16,16,16),
    'G': (14,17,16,23,17,17,14),
    'H': (17,17,17,31,17,17,17),
    'I': (14,4,4,4,4,4,14),
    'L': (16,16,16,16,16,16,31),
    'N': (17,25,21,19,17,17,17),
    'T': (31,4,4,4,4,4,4),
    'n': (0,0,30,17,17,17,17),
    'u': (0,0,17,17,17,19,13)
}

row = bytearray(W * 2)

def clear_row():
    for i in range(len(row)):
        row[i] = 0

def draw_text_line(text, x0, yy, scale):
    gy = yy // scale
    if gy < 0 or gy >= 7:
        return
    for ci, ch in enumerate(text):
        bits = FONT.get(ch, FONT[' '])[gy]
        for gx in range(5):
            if bits & (1 << (4 - gx)):
                for sx in range(scale):
                    px = x0 + ci * 6 * scale + gx * scale + sx
                    if 0 <= px < W:
                        k = px * 2
                        row[k] = 0xFF
                        row[k + 1] = 0xFF

def draw_meter(field_nt, change_tenths, mode):
    if mode == 0:
        label = "FIELD nT"
        value = str(field_nt)
    else:
        label = "CHANGE uT"
        value = "%d.%d" % (change_tenths // 10,
                            change_tenths % 10)
    label_scale = 1
    value_scale = 2
    if len(value) * 12 > W:
        value_scale = 1
    label_x = (W - len(label) * 6) // 2
    value_x = (W - len(value) * 6 * value_scale) // 2
    window(0, RING_H, W - 1, H - 1)
    cs.write_digital(0)
    dc.write_digital(1)
    for y in range(H - RING_H):
        clear_row()
        if 2 <= y < 9:
            draw_text_line(label, label_x, y - 2, label_scale)
        if 17 <= y < 17 + 7 * value_scale:
            draw_text_line(value, value_x, y - 17, value_scale)
        spi.write(row)
    cs.write_digital(1)

def read_xyz():
    return (compass.get_x(), compass.get_y(), compass.get_z())

def read_baseline():
    sx = 0
    sy = 0
    sz = 0
    for i in range(8):
        x, y, z = read_xyz()
        sx += x
        sy += y
        sz += z
        sleep(40)
    return (sx // 8, sy // 8, sz // 8)

def magnetic_change_squared(base):
    x, y, z = read_xyz()
    dx = x - base[0]
    dy = y - base[1]
    dz = z - base[2]
    return dx * dx + dy * dy + dz * dz

thresholds = [4000 * 4000, 9000 * 9000,
              16000 * 16000, 28000 * 28000]
widths = [16, 13, 10, 7, 5]

init_tft()
display.show(Image.YES)
# Keep magnet away during baseline measurement
baseline = read_baseline()
phase = 0
paused = False
mode = 0
last_meter_time = -500
previous_a = False
previous_b = False

while True:
    a = button_a.is_pressed()
    b = button_b.is_pressed()
    if a and b:
        baseline = read_baseline()
        last_meter_time = -500
        while button_a.is_pressed() or button_b.is_pressed():
            sleep(20)
        previous_a = False
        previous_b = False
        continue

    if a and not previous_a:
        mode = 1 - mode
        last_meter_time = -500

    if b and not previous_b:
        paused = not paused
        last_meter_time = -500

    previous_a = a
    previous_b = b

    if not paused:
        change_sq = magnetic_change_squared(baseline)
        level = 0
        for threshold in thresholds:
            if change_sq >= threshold:
                level += 1
        width = widths[level]
        speed = 2 + level * 2
        draw_rings(phase, width)
        phase = (phase + speed) & 255
        now = running_time()
        if now - last_meter_time >= 500:
            field_nt = compass.get_field_strength()
            change_nt = int(math.sqrt(change_sq))
            change_tenths = (change_nt + 50) // 100
            draw_meter(field_nt, change_tenths, mode)
            last_meter_time = now
    else:
        sleep(30)

 

Open the code panel, select the entire program in the gray box, then copy and paste it into the micro:bit Python Editor. Alternatively use the download link.

Paste into the micro:bit Python Editor. This code is supplied as a known reference; keep a backup before experimenting.

What's Going On?

The micro:bit measures magnetic flux density on three axes. Earth's field is present even when no magnet is nearby. FIELD is the measured magnitude in nanoteslas (nT); CHANGE is the magnitude of the vector difference from the starting baseline, converted to microteslas (µT). 1 µT = 1,000 nT. The rings are a visualization of readings, not literal field lines.

Things to Try

Move a magnet closer and farther away. Flip it. Hide it behind paper and see whether you can detect its location. Keep the micro:bit still when comparing readings; rotating the board also changes its three-axis measurements.

Make It Your Own

Try changing only the RED/WHITE/BLACK palette, or the ring-width thresholds. Predict what the display will do before flashing the change.

Optional: Invent with AI

Ask: “My micro:bit program displays red-and-white rings on an ST7735 TFT and reports magnetic FIELD/CHANGE. Help me change only the ring colors to cyan and purple without changing the wiring, measurements, or button actions. Show the few edited lines.”

Prompting tip: Tell the AI to preserve your working pin assignments, tested TFT driver, and controls. Ask for the smallest change needed, then test it.

Why does CHANGE start near zero?

At startup the program averages several readings of the magnetometer’s X, Y, and Z axes to create a baseline vector. It displays the magnitude of the difference between the present and baseline vectors. That is why CHANGE begins near zero even though Earth's magnetic field is present.

Without calibration, absolute readings may have offsets; strong magnets can saturate the sensor.

1.2 Does Magnet Size Matter?
Same tested ring meter used for magnet comparisons
Simulated TFT output based on the actual drawing code; example sensor readings, not live measurements.

Make It Happen

Use the very same Section 1.1 Magnetic Field Meter program from 1.1. Try the different magnet sizes in your kit and watch the numerical reading change immediately. No new code or wiring needed.

Shared tested program: This lesson intentionally reuses the complete MicroPython program from experiment 1.1. The full listing is repeated here for easy copying; use the same program while changing what you investigate.

💻  View & Copy MicroPython Program — 1.2 (same tested program as 1.1)  ▾ Expand / collapse

from microbit import *
import math

# Invisible World 1.1 - Magnetic Field Meter
# Selectable Magnetic Field and Change Meter
# Parallax Inc. - SKU 32890
# micro:bit / 128x160 ST7735 TFT
# FIELD = total magnetic strength in nT
# CHANGE = change from baseline in uT
# No explicit compass calibration

W = 128
H = 160
RING_H = 120

# TFT: GND=GND, VCC=3V, SCL=P13, SDA=P15
# RES=P12, DC=P8, CS=P16
# BL: as established in tested hardware setup

cs = pin16
dc = pin8
rst = pin12
cs.write_digital(1)
dc.write_digital(1)
rst.write_digital(1)

spi.init(baudrate=8000000, bits=8, mode=0,
         sclk=pin13, mosi=pin15, miso=pin14)

def command(c):
    cs.write_digital(0)
    dc.write_digital(0)
    spi.write(bytes([c]))
    cs.write_digital(1)

def data(b):
    cs.write_digital(0)
    dc.write_digital(1)
    spi.write(b)
    cs.write_digital(1)

def init_tft():
    rst.write_digital(0)
    sleep(100)
    rst.write_digital(1)
    sleep(150)
    command(0x01)
    sleep(150)
    command(0x11)
    sleep(150)
    command(0x3A)
    data(bytes([0x05]))
    command(0x36)
    data(bytes([0x00]))
    command(0x13)
    sleep(10)
    command(0x29)
    sleep(100)

def window(x0, y0, x1, y1):
    command(0x2A)
    data(bytes([0, x0, 0, x1]))
    command(0x2B)
    data(bytes([0, y0, 0, y1]))
    command(0x2C)

BLACK = (0x00, 0x00)
RED = (0xF8, 0x00)
WHITE = (0xFF, 0xFF)
palette = [BLACK, RED, BLACK, WHITE]

distance = bytearray(W * RING_H)
for y in range(RING_H):
    dy = y - RING_H // 2
    for x in range(W):
        dx = x - W // 2
        distance[y * W + x] = int(math.sqrt(dx * dx + dy * dy))

BLOCK_ROWS = 8
block = bytearray(W * BLOCK_ROWS * 2)

def draw_rings(phase, width):
    window(0, 0, W - 1, RING_H - 1)
    cs.write_digital(0)
    dc.write_digital(1)
    for y0 in range(0, RING_H, BLOCK_ROWS):
        j = 0
        end_y = min(y0 + BLOCK_ROWS, RING_H)
        for y in range(y0, end_y):
            offset = y * W
            for x in range(W):
                d = distance[offset + x]
                band = ((d - phase) // width) & 3
                hi, lo = palette[band]
                block[j] = hi
                block[j + 1] = lo
                j += 2
        spi.write(block[:j])
    cs.write_digital(1)

FONT = {
    ' ': (0,0,0,0,0,0,0),
    '.': (0,0,0,0,0,12,12),
    '0': (14,17,19,21,25,17,14),
    '1': (4,12,4,4,4,4,14),
    '2': (14,17,1,2,4,8,31),
    '3': (30,1,1,14,1,1,30),
    '4': (2,6,10,18,31,2,2),
    '5': (31,16,30,1,1,17,14),
    '6': (6,8,16,30,17,17,14),
    '7': (31,1,2,4,8,8,8),
    '8': (14,17,17,14,17,17,14),
    '9': (14,17,17,15,1,2,12),
    'A': (14,17,17,31,17,17,17),
    'C': (14,17,16,16,16,17,14),
    'D': (30,17,17,17,17,17,30),
    'E': (31,16,16,30,16,16,31),
    'F': (31,16,16,30,16,16,16),
    'G': (14,17,16,23,17,17,14),
    'H': (17,17,17,31,17,17,17),
    'I': (14,4,4,4,4,4,14),
    'L': (16,16,16,16,16,16,31),
    'N': (17,25,21,19,17,17,17),
    'T': (31,4,4,4,4,4,4),
    'n': (0,0,30,17,17,17,17),
    'u': (0,0,17,17,17,19,13)
}

row = bytearray(W * 2)

def clear_row():
    for i in range(len(row)):
        row[i] = 0

def draw_text_line(text, x0, yy, scale):
    gy = yy // scale
    if gy < 0 or gy >= 7:
        return
    for ci, ch in enumerate(text):
        bits = FONT.get(ch, FONT[' '])[gy]
        for gx in range(5):
            if bits & (1 << (4 - gx)):
                for sx in range(scale):
                    px = x0 + ci * 6 * scale + gx * scale + sx
                    if 0 <= px < W:
                        k = px * 2
                        row[k] = 0xFF
                        row[k + 1] = 0xFF

def draw_meter(field_nt, change_tenths, mode):
    if mode == 0:
        label = "FIELD nT"
        value = str(field_nt)
    else:
        label = "CHANGE uT"
        value = "%d.%d" % (change_tenths // 10,
                            change_tenths % 10)
    label_scale = 1
    value_scale = 2
    if len(value) * 12 > W:
        value_scale = 1
    label_x = (W - len(label) * 6) // 2
    value_x = (W - len(value) * 6 * value_scale) // 2
    window(0, RING_H, W - 1, H - 1)
    cs.write_digital(0)
    dc.write_digital(1)
    for y in range(H - RING_H):
        clear_row()
        if 2 <= y < 9:
            draw_text_line(label, label_x, y - 2, label_scale)
        if 17 <= y < 17 + 7 * value_scale:
            draw_text_line(value, value_x, y - 17, value_scale)
        spi.write(row)
    cs.write_digital(1)

def read_xyz():
    return (compass.get_x(), compass.get_y(), compass.get_z())

def read_baseline():
    sx = 0
    sy = 0
    sz = 0
    for i in range(8):
        x, y, z = read_xyz()
        sx += x
        sy += y
        sz += z
        sleep(40)
    return (sx // 8, sy // 8, sz // 8)

def magnetic_change_squared(base):
    x, y, z = read_xyz()
    dx = x - base[0]
    dy = y - base[1]
    dz = z - base[2]
    return dx * dx + dy * dy + dz * dz

thresholds = [4000 * 4000, 9000 * 9000,
              16000 * 16000, 28000 * 28000]
widths = [16, 13, 10, 7, 5]

init_tft()
display.show(Image.YES)
# Keep magnet away during baseline measurement
baseline = read_baseline()
phase = 0
paused = False
mode = 0
last_meter_time = -500
previous_a = False
previous_b = False

while True:
    a = button_a.is_pressed()
    b = button_b.is_pressed()
    if a and b:
        baseline = read_baseline()
        last_meter_time = -500
        while button_a.is_pressed() or button_b.is_pressed():
            sleep(20)
        previous_a = False
        previous_b = False
        continue

    if a and not previous_a:
        mode = 1 - mode
        last_meter_time = -500

    if b and not previous_b:
        paused = not paused
        last_meter_time = -500

    previous_a = a
    previous_b = b

    if not paused:
        change_sq = magnetic_change_squared(baseline)
        level = 0
        for threshold in thresholds:
            if change_sq >= threshold:
                level += 1
        width = widths[level]
        speed = 2 + level * 2
        draw_rings(phase, width)
        phase = (phase + speed) & 255
        now = running_time()
        if now - last_meter_time >= 500:
            field_nt = compass.get_field_strength()
            change_nt = int(math.sqrt(change_sq))
            change_tenths = (change_nt + 50) // 100
            draw_meter(field_nt, change_tenths, mode)
            last_meter_time = now
    else:
        sleep(30)

 

What's Going On?

A larger magnet is not necessarily stronger at a given distance. Material, shape, magnetization, orientation, and distance all matter. For fair comparisons, use the CHANGE uT reading and a consistent distance and orientation.

Things to Try

Place one magnet at a fixed distance from the micro:bit, such as 5 cm, record the CHANGE reading, then replace it with another magnet in the same position and orientation. Repeat at 10 cm. Can you predict which magnet will have the greatest effect?

Optional: record your results
Magnet 5 cm: ΔB (µT) 10 cm: ΔB (µT)
A — smallest _____ _____
B — medium _____ _____
C — largest _____ _____

Optional rather than a required worksheet. Keep the magnets clear of one another and away from ferromagnetic objects during tests.

Make It Your Own

Add an optional peak-hold feature or a “best result” indicator to make comparisons easier. The simulation above shows the same single live meter as the code; it does not invent a multi-magnet comparison chart.

Optional: Invent with AI

Ask: “Modify my working magnetic CHANGE meter so pressing B records the highest CHANGE value seen since the last reset. Preserve the proven TFT driver. Explain which variable holds the peak and how I can clear it.”

Prompting tip: Tell the AI to preserve your working pin assignments, tested TFT driver, and controls. Ask for the smallest change needed, then test it.

1.3 Which Direction Is the Field Pointing?
Three signed X Y Z bars with one numerical total field measurement
Simulated TFT output based on the actual drawing code; example sensor readings, not live measurements.

Make It Happen

Open the 1.3 Magnetic Visualization Lab program below, copy it into the micro:bit Python Editor, and download it to your micro:bit. Press A once to reach XYZ FIELD. Three colorful bars show the X, Y, and Z magnetic components.

💻  View & Copy MicroPython Program — 1.3 Magnetic Visualization Lab  ▾ Expand / collapse

from microbit import *
import math

# Invisible World 1.3 - Magnetic Visualization Lab
# Magnetic Visualization Lab
# Parallax Inc. - SKU 32890
# A: next view, B: freeze, A+B: reset baseline
# 0: rings, 1: XYZ bars, 2: field history

W = 128
H = 160
GRAPH_H = 120
cs = pin16
dc = pin8
rst = pin12
cs.write_digital(1)
dc.write_digital(1)
rst.write_digital(1)

spi.init(baudrate=8000000, bits=8, mode=0,
         sclk=pin13, mosi=pin15, miso=pin14)

def command(c):
    cs.write_digital(0)
    dc.write_digital(0)
    spi.write(bytes([c]))
    cs.write_digital(1)

def data(b):
    cs.write_digital(0)
    dc.write_digital(1)
    spi.write(b)
    cs.write_digital(1)

def init_tft():
    rst.write_digital(0)
    sleep(100)
    rst.write_digital(1)
    sleep(150)
    command(0x01)
    sleep(150)
    command(0x11)
    sleep(150)
    command(0x3A)
    data(bytes([0x05]))
    command(0x36)
    data(bytes([0x00]))
    command(0x13)
    sleep(10)
    command(0x29)
    sleep(100)

def window(x0, y0, x1, y1):
    command(0x2A)
    data(bytes([0, x0, 0, x1]))
    command(0x2B)
    data(bytes([0, y0, 0, y1]))
    command(0x2C)

BLACK = (0, 0)
WHITE = (255, 255)
RED = (248, 0)
CYAN = (7, 255)
GREEN = (7, 224)
GRAY = (49, 134)
ring_palette = [BLACK, RED, BLACK, WHITE]

FONT = {
    ' ': (0,0,0,0,0,0,0),
    '.': (0,0,0,0,0,12,12),
    '0': (14,17,19,21,25,17,14),
    '1': (4,12,4,4,4,4,14),
    '2': (14,17,1,2,4,8,31),
    '3': (30,1,1,14,1,1,30),
    '4': (2,6,10,18,31,2,2),
    '5': (31,16,30,1,1,17,14),
    '6': (6,8,16,30,17,17,14),
    '7': (31,1,2,4,8,8,8),
    '8': (14,17,17,14,17,17,14),
    '9': (14,17,17,15,1,2,12),
    'A': (14,17,17,31,17,17,17),
    'C': (14,17,16,16,16,17,14),
    'D': (30,17,17,17,17,17,30),
    'E': (31,16,16,30,16,16,31),
    'F': (31,16,16,30,16,16,16),
    'G': (14,17,16,23,17,17,14),
    'H': (17,17,17,31,17,17,17),
    'I': (14,4,4,4,4,4,14),
    'L': (16,16,16,16,16,16,31),
    'N': (17,25,21,19,17,17,17),
    'O': (14,17,17,17,17,17,14),
    'R': (30,17,17,30,20,18,17),
    'S': (15,16,16,14,1,1,30),
    'T': (31,4,4,4,4,4,4),
    'U': (17,17,17,17,17,17,14),
    'X': (17,17,10,4,10,17,17),
    'Y': (17,17,10,4,4,4,4),
    'Z': (31,1,2,4,8,16,31),
    'n': (0,0,30,17,17,17,17),
    'u': (0,0,17,17,17,19,13)
}
row = bytearray(W * 2)

def clear_row():
    for i in range(W * 2):
        row[i] = 0

def pixel(x, color):
    if 0 <= x < W:
        k = x * 2
        row[k] = color[0]
        row[k + 1] = color[1]

def text_row(text, x0, yy, scale=1, color=WHITE):
    gy = yy // scale
    if gy < 0 or gy >= 7:
        return
    for ci, ch in enumerate(text):
        bits = FONT.get(ch, FONT[' '])[gy]
        for gx in range(5):
            if bits & (1 << (4-gx)):
                for sx in range(scale):
                    px = x0 + ci*6*scale + gx*scale + sx
                    pixel(px, color)

def centered(text, yy, scale=1, color=WHITE):
    x = (W - len(text)*6*scale)//2
    text_row(text, x, yy, scale, color)

distance = bytearray(W * GRAPH_H)
for y in range(GRAPH_H):
    dy = y - GRAPH_H//2
    for x in range(W):
        dx = x - W//2
        distance[y*W+x] = int(math.sqrt(dx*dx + dy*dy))

BLOCK_ROWS = 8
block = bytearray(W * BLOCK_ROWS * 2)

def draw_rings(phase, width):
    window(0, 0, W-1, GRAPH_H-1)
    cs.write_digital(0)
    dc.write_digital(1)
    for y0 in range(0, GRAPH_H, BLOCK_ROWS):
        j = 0
        for y in range(y0, min(y0+BLOCK_ROWS, GRAPH_H)):
            offset = y*W
            for x in range(W):
                d = distance[offset+x]
                band = ((d-phase)//width) & 3
                hi, lo = ring_palette[band]
                block[j] = hi
                block[j+1] = lo
                j += 2
        spi.write(block[:j])
    cs.write_digital(1)

def read_xyz():
    return (compass.get_x(), compass.get_y(), compass.get_z())

def read_baseline():
    sx = sy = sz = 0
    for i in range(8):
        x, y, z = read_xyz()
        sx += x
        sy += y
        sz += z
        sleep(40)
    return (sx//8, sy//8, sz//8)

def measure(base):
    x, y, z = read_xyz()
    dx = x-base[0]
    dy = y-base[1]
    dz = z-base[2]
    change_sq = dx*dx + dy*dy + dz*dz
    total = int(math.sqrt(x*x + y*y + z*z))
    return x, y, z, total, change_sq

thresholds = [4000*4000, 9000*9000,
              16000*16000, 28000*28000]
widths = [16, 13, 10, 7, 5]

def draw_bars(xv, yv, zv):
    values = [xv, yv, zv]
    colors = [RED, CYAN, GREEN]
    largest = 50000
    for v in values:
        if abs(v) > largest:
            largest = abs(v)
    lengths = []
    for v in values:
        length = (abs(v)*48)//largest
        if v < 0:
            length = -length
        lengths.append(length)

    window(0, 0, W-1, GRAPH_H-1)
    cs.write_digital(0)
    dc.write_digital(1)
    for y in range(GRAPH_H):
        clear_row()
        if 3 <= y < 10:
            centered("XYZ FIELD", y-3)
        if 19 <= y <= 109:
            pixel(64, WHITE)
        for i in range(3):
            top = 26 + i*29
            if top <= y < top+13:
                v = lengths[i]
                if v >= 0:
                    for px in range(65, 65+v):
                        pixel(px, colors[i])
                else:
                    for px in range(64+v, 64):
                        pixel(px, colors[i])
            if top <= y < top+7:
                text_row("XYZ"[i], 7, y-top, 1, WHITE)
        spi.write(row)
    cs.write_digital(1)

history = [0] * 104
samples = 0

def add_sample(value):
    global samples
    for i in range(103):
        history[i] = history[i+1]
    history[103] = value
    if samples < 104:
        samples += 1

def draw_history():
    maximum = 100000
    for v in history:
        if v > maximum:
            maximum = v
    if maximum > 100000:
        maximum = maximum + maximum//5
    points = [0] * 104
    for i in range(104):
        value = history[i]
        if value > maximum:
            value = maximum
        points[i] = 108 - (value*85)//maximum

    window(0, 0, W-1, GRAPH_H-1)
    cs.write_digital(0)
    dc.write_digital(1)
    for y in range(GRAPH_H):
        clear_row()
        if 3 <= y < 10:
            centered("FIELD HISTORY", y-3)
        if y in (23, 44, 65, 86, 108):
            for x in range(12, 120, 3):
                pixel(x, GRAY)
        if 23 <= y <= 108:
            for i in range(104):
                if i >= 104-samples:
                    x = i+12
                    py = points[i]
                    if i > 104-samples:
                        prev = points[i-1]
                        low = min(py, prev)
                        high = max(py, prev)
                        if low <= y <= high:
                            pixel(x, GREEN)
                    elif y == py:
                        pixel(x, GREEN)
        spi.write(row)
    cs.write_digital(1)

def draw_meter(field_nt, change_sq, mode):
    label = "FIELD nT"
    value = str(field_nt)
    scale = 2
    if len(value)*12 > W:
        scale = 1
    window(0, GRAPH_H, W-1, H-1)
    cs.write_digital(0)
    dc.write_digital(1)
    for y in range(40):
        clear_row()
        if 2 <= y < 9:
            centered(label, y-2)
        if 17 <= y < 17+7*scale:
            centered(value, y-17, scale)
        spi.write(row)
    cs.write_digital(1)

init_tft()
display.show(Image.YES)
baseline = read_baseline()
mode = 0
phase = 0
paused = False
previous_a = False
previous_b = False
last_update = -500

while True:
    a = button_a.is_pressed()
    b = button_b.is_pressed()

    if a and b:
        baseline = read_baseline()
        history = [0] * 104
        samples = 0
        last_update = -500
        while button_a.is_pressed() or button_b.is_pressed():
            sleep(20)
        previous_a = False
        previous_b = False
        continue

    if a and not previous_a:
        mode = (mode+1) % 3
        last_update = -500

    if b and not previous_b:
        paused = not paused
        last_update = -500

    previous_a = a
    previous_b = b

    if paused:
        sleep(30)
        continue

    x, y, z, field_nt, change_sq = measure(baseline)
    now = running_time()

    if mode == 0:
        level = 0
        for t in thresholds:
            if change_sq >= t:
                level += 1
        draw_rings(phase, widths[level])
        phase = (phase+2+level*2) & 255
        if now-last_update >= 500:
            draw_meter(field_nt, change_sq, mode)
            last_update = now

    elif mode == 1:
        if now-last_update >= 300:
            draw_bars(x, y, z)
            draw_meter(field_nt, change_sq, mode)
            last_update = now

    else:
        if now-last_update >= 350:
            add_sample(field_nt)
            draw_history()
            draw_meter(field_nt, change_sq, mode)
            last_update = now

 

Open the code panel, select the entire program in the gray box, then copy and paste it into the micro:bit Python Editor. Alternatively use the download link.

What's Going On?

Magnetic flux density is a vector. The red X, cyan Y, and green Z bars represent signed readings in nT. Left of the centerline means negative and right means positive. The bar graph automatically scales so it fits; it is not a fixed numerical scale.

Things to Try

Hold the board still and rotate a magnet slowly. Which axis changes most? Turn the magnet end-for-end. Can you make one bar switch from positive to negative?

Make It Your Own

Try displaying signed numerical values beside each bar, or add a fixed scale so you can compare values without autoscaling.

Optional: Invent with AI

Ask: “My working Magnetic Visualization Lab X/Y/Z view has a center zero line and signed colored bars. Add a fixed ±50,000 nT scale, keeping the original bar colors, SPI driver and button controls. Tell me which few functions change.”

Prompting tip: Tell the AI to preserve your working pin assignments, tested TFT driver, and controls. Ask for the smallest change needed, then test it.

1.4 What Happens When a Magnet Moves?
Green scrolling magnetic field history on black with total field readout
Simulated TFT output based on the actual drawing code; example sensor readings, not live measurements.

Make It Happen

With the 1.3 Magnetic Visualization Lab program running, press A until the screen reads FIELD HISTORY. Move a magnet toward and away from the micro:bit and watch the green trace change.

Shared tested program: This lesson intentionally reuses the complete MicroPython program from experiment 1.3. The full listing is repeated here for easy copying; use the same program while changing what you investigate.

💻  View & Copy MicroPython Program — 1.4 (same tested program as 1.3)  ▾ Expand / collapse

from microbit import *
import math

# Invisible World 1.3 - Magnetic Visualization Lab
# Magnetic Visualization Lab
# Parallax Inc. - SKU 32890
# A: next view, B: freeze, A+B: reset baseline
# 0: rings, 1: XYZ bars, 2: field history

W = 128
H = 160
GRAPH_H = 120
cs = pin16
dc = pin8
rst = pin12
cs.write_digital(1)
dc.write_digital(1)
rst.write_digital(1)

spi.init(baudrate=8000000, bits=8, mode=0,
         sclk=pin13, mosi=pin15, miso=pin14)

def command(c):
    cs.write_digital(0)
    dc.write_digital(0)
    spi.write(bytes([c]))
    cs.write_digital(1)

def data(b):
    cs.write_digital(0)
    dc.write_digital(1)
    spi.write(b)
    cs.write_digital(1)

def init_tft():
    rst.write_digital(0)
    sleep(100)
    rst.write_digital(1)
    sleep(150)
    command(0x01)
    sleep(150)
    command(0x11)
    sleep(150)
    command(0x3A)
    data(bytes([0x05]))
    command(0x36)
    data(bytes([0x00]))
    command(0x13)
    sleep(10)
    command(0x29)
    sleep(100)

def window(x0, y0, x1, y1):
    command(0x2A)
    data(bytes([0, x0, 0, x1]))
    command(0x2B)
    data(bytes([0, y0, 0, y1]))
    command(0x2C)

BLACK = (0, 0)
WHITE = (255, 255)
RED = (248, 0)
CYAN = (7, 255)
GREEN = (7, 224)
GRAY = (49, 134)
ring_palette = [BLACK, RED, BLACK, WHITE]

FONT = {
    ' ': (0,0,0,0,0,0,0),
    '.': (0,0,0,0,0,12,12),
    '0': (14,17,19,21,25,17,14),
    '1': (4,12,4,4,4,4,14),
    '2': (14,17,1,2,4,8,31),
    '3': (30,1,1,14,1,1,30),
    '4': (2,6,10,18,31,2,2),
    '5': (31,16,30,1,1,17,14),
    '6': (6,8,16,30,17,17,14),
    '7': (31,1,2,4,8,8,8),
    '8': (14,17,17,14,17,17,14),
    '9': (14,17,17,15,1,2,12),
    'A': (14,17,17,31,17,17,17),
    'C': (14,17,16,16,16,17,14),
    'D': (30,17,17,17,17,17,30),
    'E': (31,16,16,30,16,16,31),
    'F': (31,16,16,30,16,16,16),
    'G': (14,17,16,23,17,17,14),
    'H': (17,17,17,31,17,17,17),
    'I': (14,4,4,4,4,4,14),
    'L': (16,16,16,16,16,16,31),
    'N': (17,25,21,19,17,17,17),
    'O': (14,17,17,17,17,17,14),
    'R': (30,17,17,30,20,18,17),
    'S': (15,16,16,14,1,1,30),
    'T': (31,4,4,4,4,4,4),
    'U': (17,17,17,17,17,17,14),
    'X': (17,17,10,4,10,17,17),
    'Y': (17,17,10,4,4,4,4),
    'Z': (31,1,2,4,8,16,31),
    'n': (0,0,30,17,17,17,17),
    'u': (0,0,17,17,17,19,13)
}
row = bytearray(W * 2)

def clear_row():
    for i in range(W * 2):
        row[i] = 0

def pixel(x, color):
    if 0 <= x < W:
        k = x * 2
        row[k] = color[0]
        row[k + 1] = color[1]

def text_row(text, x0, yy, scale=1, color=WHITE):
    gy = yy // scale
    if gy < 0 or gy >= 7:
        return
    for ci, ch in enumerate(text):
        bits = FONT.get(ch, FONT[' '])[gy]
        for gx in range(5):
            if bits & (1 << (4-gx)):
                for sx in range(scale):
                    px = x0 + ci*6*scale + gx*scale + sx
                    pixel(px, color)

def centered(text, yy, scale=1, color=WHITE):
    x = (W - len(text)*6*scale)//2
    text_row(text, x, yy, scale, color)

distance = bytearray(W * GRAPH_H)
for y in range(GRAPH_H):
    dy = y - GRAPH_H//2
    for x in range(W):
        dx = x - W//2
        distance[y*W+x] = int(math.sqrt(dx*dx + dy*dy))

BLOCK_ROWS = 8
block = bytearray(W * BLOCK_ROWS * 2)

def draw_rings(phase, width):
    window(0, 0, W-1, GRAPH_H-1)
    cs.write_digital(0)
    dc.write_digital(1)
    for y0 in range(0, GRAPH_H, BLOCK_ROWS):
        j = 0
        for y in range(y0, min(y0+BLOCK_ROWS, GRAPH_H)):
            offset = y*W
            for x in range(W):
                d = distance[offset+x]
                band = ((d-phase)//width) & 3
                hi, lo = ring_palette[band]
                block[j] = hi
                block[j+1] = lo
                j += 2
        spi.write(block[:j])
    cs.write_digital(1)

def read_xyz():
    return (compass.get_x(), compass.get_y(), compass.get_z())

def read_baseline():
    sx = sy = sz = 0
    for i in range(8):
        x, y, z = read_xyz()
        sx += x
        sy += y
        sz += z
        sleep(40)
    return (sx//8, sy//8, sz//8)

def measure(base):
    x, y, z = read_xyz()
    dx = x-base[0]
    dy = y-base[1]
    dz = z-base[2]
    change_sq = dx*dx + dy*dy + dz*dz
    total = int(math.sqrt(x*x + y*y + z*z))
    return x, y, z, total, change_sq

thresholds = [4000*4000, 9000*9000,
              16000*16000, 28000*28000]
widths = [16, 13, 10, 7, 5]

def draw_bars(xv, yv, zv):
    values = [xv, yv, zv]
    colors = [RED, CYAN, GREEN]
    largest = 50000
    for v in values:
        if abs(v) > largest:
            largest = abs(v)
    lengths = []
    for v in values:
        length = (abs(v)*48)//largest
        if v < 0:
            length = -length
        lengths.append(length)

    window(0, 0, W-1, GRAPH_H-1)
    cs.write_digital(0)
    dc.write_digital(1)
    for y in range(GRAPH_H):
        clear_row()
        if 3 <= y < 10:
            centered("XYZ FIELD", y-3)
        if 19 <= y <= 109:
            pixel(64, WHITE)
        for i in range(3):
            top = 26 + i*29
            if top <= y < top+13:
                v = lengths[i]
                if v >= 0:
                    for px in range(65, 65+v):
                        pixel(px, colors[i])
                else:
                    for px in range(64+v, 64):
                        pixel(px, colors[i])
            if top <= y < top+7:
                text_row("XYZ"[i], 7, y-top, 1, WHITE)
        spi.write(row)
    cs.write_digital(1)

history = [0] * 104
samples = 0

def add_sample(value):
    global samples
    for i in range(103):
        history[i] = history[i+1]
    history[103] = value
    if samples < 104:
        samples += 1

def draw_history():
    maximum = 100000
    for v in history:
        if v > maximum:
            maximum = v
    if maximum > 100000:
        maximum = maximum + maximum//5
    points = [0] * 104
    for i in range(104):
        value = history[i]
        if value > maximum:
            value = maximum
        points[i] = 108 - (value*85)//maximum

    window(0, 0, W-1, GRAPH_H-1)
    cs.write_digital(0)
    dc.write_digital(1)
    for y in range(GRAPH_H):
        clear_row()
        if 3 <= y < 10:
            centered("FIELD HISTORY", y-3)
        if y in (23, 44, 65, 86, 108):
            for x in range(12, 120, 3):
                pixel(x, GRAY)
        if 23 <= y <= 108:
            for i in range(104):
                if i >= 104-samples:
                    x = i+12
                    py = points[i]
                    if i > 104-samples:
                        prev = points[i-1]
                        low = min(py, prev)
                        high = max(py, prev)
                        if low <= y <= high:
                            pixel(x, GREEN)
                    elif y == py:
                        pixel(x, GREEN)
        spi.write(row)
    cs.write_digital(1)

def draw_meter(field_nt, change_sq, mode):
    label = "FIELD nT"
    value = str(field_nt)
    scale = 2
    if len(value)*12 > W:
        scale = 1
    window(0, GRAPH_H, W-1, H-1)
    cs.write_digital(0)
    dc.write_digital(1)
    for y in range(40):
        clear_row()
        if 2 <= y < 9:
            centered(label, y-2)
        if 17 <= y < 17+7*scale:
            centered(value, y-17, scale)
        spi.write(row)
    cs.write_digital(1)

init_tft()
display.show(Image.YES)
baseline = read_baseline()
mode = 0
phase = 0
paused = False
previous_a = False
previous_b = False
last_update = -500

while True:
    a = button_a.is_pressed()
    b = button_b.is_pressed()

    if a and b:
        baseline = read_baseline()
        history = [0] * 104
        samples = 0
        last_update = -500
        while button_a.is_pressed() or button_b.is_pressed():
            sleep(20)
        previous_a = False
        previous_b = False
        continue

    if a and not previous_a:
        mode = (mode+1) % 3
        last_update = -500

    if b and not previous_b:
        paused = not paused
        last_update = -500

    previous_a = a
    previous_b = b

    if paused:
        sleep(30)
        continue

    x, y, z, field_nt, change_sq = measure(baseline)
    now = running_time()

    if mode == 0:
        level = 0
        for t in thresholds:
            if change_sq >= t:
                level += 1
        draw_rings(phase, widths[level])
        phase = (phase+2+level*2) & 255
        if now-last_update >= 500:
            draw_meter(field_nt, change_sq, mode)
            last_update = now

    elif mode == 1:
        if now-last_update >= 300:
            draw_bars(x, y, z)
            draw_meter(field_nt, change_sq, mode)
            last_update = now

    else:
        if now-last_update >= 350:
            add_sample(field_nt)
            draw_history()
            draw_meter(field_nt, change_sq, mode)
            last_update = now

 

What's Going On?

A time-series graph reveals patterns a single number cannot. The horizontal direction shows successive samples, not calibrated seconds. The graph uses a 0–100,000 nT vertical range unless stronger readings require expansion.

Things to Try

Move the magnet slowly, then quickly; compare the traces. Pause with Button B and see whether the peak remains. Can you produce two similar peaks by repeating the same motion?

Make It Your Own

The tested Field History drawing works but its full-screen redraw is relatively slow. Try improving speed, or add clearly labeled axis marks and timestamps, as a separate experimental revision.

Optional: Invent with AI

Ask: “In my micro:bit Magnetic Visualization Lab FIELD HISTORY view, I redraw all 120 rows for every new reading. Suggest a faster approach that preserves the plotted values and my tested SPI pins. First explain how to benchmark refresh speed, then propose one small change.”

Prompting tip: Tell the AI to preserve your working pin assignments, tested TFT driver, and controls. Ask for the smallest change needed, then test it.

1.5 Build Your Own Magnetic Instrument
One selectable Test 9 view on TFT, not a fictional dashboard
Simulated TFT output based on the actual drawing code; example sensor readings, not live measurements.

Make It Happen

Your micro:bit is already a three-mode instrument! With the program from 1.3, Button A cycles through red/white rings → X/Y/Z bars → Field History. Button B freezes the picture; A+B resets the magnetic baseline. The preview shows the X/Y/Z mode, one of the real selectable screens.

Shared tested program: This lesson intentionally reuses the complete MicroPython program from experiment 1.3. The full listing is repeated here for easy copying; use the same program while changing what you investigate.

💻  View & Copy MicroPython Program — 1.5 (same tested program as 1.3)  ▾ Expand / collapse

from microbit import *
import math

# Invisible World 1.3 - Magnetic Visualization Lab
# Magnetic Visualization Lab
# Parallax Inc. - SKU 32890
# A: next view, B: freeze, A+B: reset baseline
# 0: rings, 1: XYZ bars, 2: field history

W = 128
H = 160
GRAPH_H = 120
cs = pin16
dc = pin8
rst = pin12
cs.write_digital(1)
dc.write_digital(1)
rst.write_digital(1)

spi.init(baudrate=8000000, bits=8, mode=0,
         sclk=pin13, mosi=pin15, miso=pin14)

def command(c):
    cs.write_digital(0)
    dc.write_digital(0)
    spi.write(bytes([c]))
    cs.write_digital(1)

def data(b):
    cs.write_digital(0)
    dc.write_digital(1)
    spi.write(b)
    cs.write_digital(1)

def init_tft():
    rst.write_digital(0)
    sleep(100)
    rst.write_digital(1)
    sleep(150)
    command(0x01)
    sleep(150)
    command(0x11)
    sleep(150)
    command(0x3A)
    data(bytes([0x05]))
    command(0x36)
    data(bytes([0x00]))
    command(0x13)
    sleep(10)
    command(0x29)
    sleep(100)

def window(x0, y0, x1, y1):
    command(0x2A)
    data(bytes([0, x0, 0, x1]))
    command(0x2B)
    data(bytes([0, y0, 0, y1]))
    command(0x2C)

BLACK = (0, 0)
WHITE = (255, 255)
RED = (248, 0)
CYAN = (7, 255)
GREEN = (7, 224)
GRAY = (49, 134)
ring_palette = [BLACK, RED, BLACK, WHITE]

FONT = {
    ' ': (0,0,0,0,0,0,0),
    '.': (0,0,0,0,0,12,12),
    '0': (14,17,19,21,25,17,14),
    '1': (4,12,4,4,4,4,14),
    '2': (14,17,1,2,4,8,31),
    '3': (30,1,1,14,1,1,30),
    '4': (2,6,10,18,31,2,2),
    '5': (31,16,30,1,1,17,14),
    '6': (6,8,16,30,17,17,14),
    '7': (31,1,2,4,8,8,8),
    '8': (14,17,17,14,17,17,14),
    '9': (14,17,17,15,1,2,12),
    'A': (14,17,17,31,17,17,17),
    'C': (14,17,16,16,16,17,14),
    'D': (30,17,17,17,17,17,30),
    'E': (31,16,16,30,16,16,31),
    'F': (31,16,16,30,16,16,16),
    'G': (14,17,16,23,17,17,14),
    'H': (17,17,17,31,17,17,17),
    'I': (14,4,4,4,4,4,14),
    'L': (16,16,16,16,16,16,31),
    'N': (17,25,21,19,17,17,17),
    'O': (14,17,17,17,17,17,14),
    'R': (30,17,17,30,20,18,17),
    'S': (15,16,16,14,1,1,30),
    'T': (31,4,4,4,4,4,4),
    'U': (17,17,17,17,17,17,14),
    'X': (17,17,10,4,10,17,17),
    'Y': (17,17,10,4,4,4,4),
    'Z': (31,1,2,4,8,16,31),
    'n': (0,0,30,17,17,17,17),
    'u': (0,0,17,17,17,19,13)
}
row = bytearray(W * 2)

def clear_row():
    for i in range(W * 2):
        row[i] = 0

def pixel(x, color):
    if 0 <= x < W:
        k = x * 2
        row[k] = color[0]
        row[k + 1] = color[1]

def text_row(text, x0, yy, scale=1, color=WHITE):
    gy = yy // scale
    if gy < 0 or gy >= 7:
        return
    for ci, ch in enumerate(text):
        bits = FONT.get(ch, FONT[' '])[gy]
        for gx in range(5):
            if bits & (1 << (4-gx)):
                for sx in range(scale):
                    px = x0 + ci*6*scale + gx*scale + sx
                    pixel(px, color)

def centered(text, yy, scale=1, color=WHITE):
    x = (W - len(text)*6*scale)//2
    text_row(text, x, yy, scale, color)

distance = bytearray(W * GRAPH_H)
for y in range(GRAPH_H):
    dy = y - GRAPH_H//2
    for x in range(W):
        dx = x - W//2
        distance[y*W+x] = int(math.sqrt(dx*dx + dy*dy))

BLOCK_ROWS = 8
block = bytearray(W * BLOCK_ROWS * 2)

def draw_rings(phase, width):
    window(0, 0, W-1, GRAPH_H-1)
    cs.write_digital(0)
    dc.write_digital(1)
    for y0 in range(0, GRAPH_H, BLOCK_ROWS):
        j = 0
        for y in range(y0, min(y0+BLOCK_ROWS, GRAPH_H)):
            offset = y*W
            for x in range(W):
                d = distance[offset+x]
                band = ((d-phase)//width) & 3
                hi, lo = ring_palette[band]
                block[j] = hi
                block[j+1] = lo
                j += 2
        spi.write(block[:j])
    cs.write_digital(1)

def read_xyz():
    return (compass.get_x(), compass.get_y(), compass.get_z())

def read_baseline():
    sx = sy = sz = 0
    for i in range(8):
        x, y, z = read_xyz()
        sx += x
        sy += y
        sz += z
        sleep(40)
    return (sx//8, sy//8, sz//8)

def measure(base):
    x, y, z = read_xyz()
    dx = x-base[0]
    dy = y-base[1]
    dz = z-base[2]
    change_sq = dx*dx + dy*dy + dz*dz
    total = int(math.sqrt(x*x + y*y + z*z))
    return x, y, z, total, change_sq

thresholds = [4000*4000, 9000*9000,
              16000*16000, 28000*28000]
widths = [16, 13, 10, 7, 5]

def draw_bars(xv, yv, zv):
    values = [xv, yv, zv]
    colors = [RED, CYAN, GREEN]
    largest = 50000
    for v in values:
        if abs(v) > largest:
            largest = abs(v)
    lengths = []
    for v in values:
        length = (abs(v)*48)//largest
        if v < 0:
            length = -length
        lengths.append(length)

    window(0, 0, W-1, GRAPH_H-1)
    cs.write_digital(0)
    dc.write_digital(1)
    for y in range(GRAPH_H):
        clear_row()
        if 3 <= y < 10:
            centered("XYZ FIELD", y-3)
        if 19 <= y <= 109:
            pixel(64, WHITE)
        for i in range(3):
            top = 26 + i*29
            if top <= y < top+13:
                v = lengths[i]
                if v >= 0:
                    for px in range(65, 65+v):
                        pixel(px, colors[i])
                else:
                    for px in range(64+v, 64):
                        pixel(px, colors[i])
            if top <= y < top+7:
                text_row("XYZ"[i], 7, y-top, 1, WHITE)
        spi.write(row)
    cs.write_digital(1)

history = [0] * 104
samples = 0

def add_sample(value):
    global samples
    for i in range(103):
        history[i] = history[i+1]
    history[103] = value
    if samples < 104:
        samples += 1

def draw_history():
    maximum = 100000
    for v in history:
        if v > maximum:
            maximum = v
    if maximum > 100000:
        maximum = maximum + maximum//5
    points = [0] * 104
    for i in range(104):
        value = history[i]
        if value > maximum:
            value = maximum
        points[i] = 108 - (value*85)//maximum

    window(0, 0, W-1, GRAPH_H-1)
    cs.write_digital(0)
    dc.write_digital(1)
    for y in range(GRAPH_H):
        clear_row()
        if 3 <= y < 10:
            centered("FIELD HISTORY", y-3)
        if y in (23, 44, 65, 86, 108):
            for x in range(12, 120, 3):
                pixel(x, GRAY)
        if 23 <= y <= 108:
            for i in range(104):
                if i >= 104-samples:
                    x = i+12
                    py = points[i]
                    if i > 104-samples:
                        prev = points[i-1]
                        low = min(py, prev)
                        high = max(py, prev)
                        if low <= y <= high:
                            pixel(x, GREEN)
                    elif y == py:
                        pixel(x, GREEN)
        spi.write(row)
    cs.write_digital(1)

def draw_meter(field_nt, change_sq, mode):
    label = "FIELD nT"
    value = str(field_nt)
    scale = 2
    if len(value)*12 > W:
        scale = 1
    window(0, GRAPH_H, W-1, H-1)
    cs.write_digital(0)
    dc.write_digital(1)
    for y in range(40):
        clear_row()
        if 2 <= y < 9:
            centered(label, y-2)
        if 17 <= y < 17+7*scale:
            centered(value, y-17, scale)
        spi.write(row)
    cs.write_digital(1)

init_tft()
display.show(Image.YES)
baseline = read_baseline()
mode = 0
phase = 0
paused = False
previous_a = False
previous_b = False
last_update = -500

while True:
    a = button_a.is_pressed()
    b = button_b.is_pressed()

    if a and b:
        baseline = read_baseline()
        history = [0] * 104
        samples = 0
        last_update = -500
        while button_a.is_pressed() or button_b.is_pressed():
            sleep(20)
        previous_a = False
        previous_b = False
        continue

    if a and not previous_a:
        mode = (mode+1) % 3
        last_update = -500

    if b and not previous_b:
        paused = not paused
        last_update = -500

    previous_a = a
    previous_b = b

    if paused:
        sleep(30)
        continue

    x, y, z, field_nt, change_sq = measure(baseline)
    now = running_time()

    if mode == 0:
        level = 0
        for t in thresholds:
            if change_sq >= t:
                level += 1
        draw_rings(phase, widths[level])
        phase = (phase+2+level*2) & 255
        if now-last_update >= 500:
            draw_meter(field_nt, change_sq, mode)
            last_update = now

    elif mode == 1:
        if now-last_update >= 300:
            draw_bars(x, y, z)
            draw_meter(field_nt, change_sq, mode)
            last_update = now

    else:
        if now-last_update >= 350:
            add_sample(field_nt)
            draw_history()
            draw_meter(field_nt, change_sq, mode)
            last_update = now

 

What's Going On?

Three displays reveal different information from the same magnetometer: change strength, signed components, and total-field history. A good scientific instrument communicates its measurement clearly, including units and limitations.

Things to Try

Which screen is best for finding a concealed magnet? For checking its polarity? For recording how it moves? Try all three and decide which you would keep on a pocket-sized meter.

Make It Your Own

Design your own version: customize the colors, add a peak indicator, choose a fixed scale, or optimize Field History. Start with a copy of the working program and change one feature at a time.

Optional: Invent with AI

Ask: “Help me invent a fourth view for my already-working micro:bit Magnetic Visualization Lab. I want a compact peak-hold indicator in nT. Keep the first three modes unchanged; plan the new feature before writing code, then show only the changed functions.”

Prompting tip: Tell the AI to preserve your working pin assignments, tested TFT driver, and controls. Ask for the smallest change needed, then test it.

Troubleshooting and science notes

Blank screen: check that the TFT has the same tested 3 V supply, ground, SPI wiring, and backlight arrangement. Turn off power before reconnecting.

Unexpected values: keep the board still, move metal objects away, and reset the magnetic baseline with A+B. The printed nT values are approximate without calibration, and strong magnets may saturate the sensor.

GRAPH and units: field magnitude and change from baseline measure different things. A magnet can make total FIELD increase or decrease depending on direction; CHANGE is always nonnegative.

What the images mean: the five previews simulate software-rendered screens. Their numbers are examples, not actual stored experimental data.

2. Infrared — The Light We Cannot See
Section B cropped directly from the Invisible World Revision D master engineering schematic: infrared receiver OUT to P2, VCC to 3V3, ground, and 0.1 microfarad decoupling capacitor
Engineering schematic · Section B · Rev D

One invisible conversation, one circuit. A remote control sends timed pulses of infrared light that your eyes cannot see. Use the micro:bit and TFT to discover those signals, teach two buttons to the instrument, and turn them into controls for a moving level display. You do not need to know the remote's brand or button codes in advance.

What you'll need: the permanent micro:bit and TFT circuit, a Vishay TSOP38438 38 kHz infrared receiver, one 0.1 µF ceramic capacitor, jumper wires, and a conventional infrared remote. Some smart remotes use Bluetooth instead; they will not necessarily work with this infrared-only experiment.

Before connecting the infrared receiver: Switch off USB and battery power. If a thermistor divider or moisture-probe signal is already connected to P2, disconnect that P2 signal first. Connect only the infrared receiver OUT to P2; keep the TFT's permanent wiring unchanged.

Confirmed infrared connection: Receiver OUT is connected to P2 (digital input), not P0. Follow the corrected diagram above and the pin table below.

TSOP38438 — front view, receiving face toward you; leads downward Connection
Pin 1, left — OUT P2
Pin 2, middle — GND GND
Pin 3, right — Vs 3 V
0.1 µF ceramic capacitor (nonpolarized) Between Vs and GND, close to receiver

Turn power off before changing the circuit. Keep all existing TFT connections in place: SCL P13, SDA P15, CS P16, DC P8, RES P12, 3 V, and GND. The capacitor reduces noise on the receiver's power supply. Do not reverse the receiver: the pin order above applies only with the receiving face toward you.

Testing status: Sony SIRC 20-bit decoding, learning, Control mode and fast TFT refresh have been hardware-tested. NEC and RAW learning are included as experimental compatibility features, not yet validated with another conventional IR remote.

2.1 See the Invisible Message
Infrared DISCOVER TFT display with example Sony remote signal
IR DISCOVER — infrared signal fingerprint · Simulated from the approved MicroPython display routines; example readings, not measured data.

Make It Happen

Build the infrared receiver circuit above. In the Python Editor, use the complete program immediately below. Flash it to the micro:bit. The TFT starts in IR DISCOVER. Point a household IR remote at the receiver and briefly hold a button. When enough matching signals are received, the display shows its hexadecimal fingerprint and, if decoded, its protocol and command. The program handles its own measurements: no serial-console copying is required.

💻 View & Copy MicroPython Program — Infrared TFT v1.2

# Invisible World - Infrared TFT v1.2
# Parallax Limited Edition micro:bit Kit
# micro:bit / ST7735 128x160 TFT
# Sony SIRC 20-bit, NEC, RAW pattern learning
# IR: OUT P2 / GND GND / Vs 3V
# 0.1uF ceramic capacitor across Vs and GND
# TFT: SCL P13 / SDA P15 / CS P16
# DC P8 / RES P12 / VCC 3V / GND GND
# A = Discover / Control; B = Learn next button
from microbit import *
from utime import ticks_us, ticks_diff

CS = pin16
DC = pin8
RST = pin12
IR = pin2
IR.set_pull(IR.NO_PULL)
BLACK = 0x0000
NAVY = 0x0844
BLUE = 0x159F
CYAN = 0x7DFF
WHITE = 0xFFFF
GREY = 0x9CD3
GREEN = 0x47E8

FONT = {
' ':('00000',)*7,
'A':('01110','10001','10001','11111','10001','10001','10001'),
'B':('11110','10001','10001','11110','10001','10001','11110'),
'C':('01111','10000','10000','10000','10000','10000','01111'),
'D':('11110','10001','10001','10001','10001','10001','11110'),
'E':('11111','10000','10000','11110','10000','10000','11111'),
'F':('11111','10000','10000','11110','10000','10000','10000'),
'G':('01111','10000','10000','10111','10001','10001','01111'),
'H':('10001','10001','10001','11111','10001','10001','10001'),
'I':('11111','00100','00100','00100','00100','00100','11111'),
'J':('00111','00010','00010','00010','10010','10010','01100'),
'K':('10001','10010','10100','11000','10100','10010','10001'),
'L':('10000','10000','10000','10000','10000','10000','11111'),
'M':('10001','11011','10101','10101','10001','10001','10001'),
'N':('10001','11001','10101','10011','10001','10001','10001'),
'O':('01110','10001','10001','10001','10001','10001','01110'),
'P':('11110','10001','10001','11110','10000','10000','10000'),
'Q':('01110','10001','10001','10001','10101','10010','01101'),
'R':('11110','10001','10001','11110','10100','10010','10001'),
'S':('01111','10000','10000','01110','00001','00001','11110'),
'T':('11111','00100','00100','00100','00100','00100','00100'),
'U':('10001','10001','10001','10001','10001','10001','01110'),
'V':('10001','10001','10001','10001','10001','01010','00100'),
'W':('10001','10001','10001','10101','10101','10101','01010'),
'X':('10001','10001','01010','00100','01010','10001','10001'),
'Y':('10001','10001','01010','00100','00100','00100','00100'),
'Z':('11111','00001','00010','00100','01000','10000','11111'),
'0':('01110','10001','10011','10101','11001','10001','01110'),
'1':('00100','01100','00100','00100','00100','00100','01110'),
'2':('01110','10001','00001','00010','00100','01000','11111'),
'3':('11110','00001','00001','01110','00001','00001','11110'),
'4':('00010','00110','01010','10010','11111','00010','00010'),
'5':('11111','10000','10000','11110','00001','00001','11110'),
'6':('01110','10000','10000','11110','10001','10001','01110'),
'7':('11111','00001','00010','00100','01000','01000','01000'),
'8':('01110','10001','10001','01110','10001','10001','01110'),
'9':('01110','10001','10001','01111','00001','00001','01110'),
':':('00000','00100','00100','00000','00100','00100','00000'),
'/':('00001','00001','00010','00100','01000','10000','10000'),
'-':('00000','00000','00000','11111','00000','00000','00000'),
'?':('01110','10001','00001','00010','00100','00000','00100'),
'.':('00000','00000','00000','00000','00000','01100','01100'),
}

def command(c, payload=None):
    CS.write_digital(0)
    DC.write_digital(0)
    spi.write(bytes([c]))
    if payload is not None:
        DC.write_digital(1)
        spi.write(payload)
    CS.write_digital(1)

def window(x, y, w, h):
    command(0x2A, bytes([0,x,0,x+w-1]))
    command(0x2B, bytes([0,y,0,y+h-1]))
    command(0x2C)

def rect(x, y, w, h, color):
    if w <= 0 or h <= 0:
        return
    window(x,y,w,h)
    hi,lo = color >> 8, color & 255
    chunk = bytes([hi,lo]) * min(w*8,256)
    remaining = w*h
    CS.write_digital(0)
    DC.write_digital(1)
    while remaining:
        n = min(remaining,len(chunk)//2)
        spi.write(chunk[:n*2])
        remaining -= n
    CS.write_digital(1)

def text(x, y, message, color=WHITE, scale=1):
    for ch in message.upper():
        glyph = FONT.get(ch,FONT['?'])
        for row in range(7):
            bits = glyph[row]
            for col in range(5):
                if bits[col] == '1':
                    rect(x+col*scale,
                         y+row*scale,
                         scale,scale,color)
        x += 6*scale

def init_tft():
    spi.init(baudrate=4000000,
             bits=8,mode=0,
             sclk=pin13,
             mosi=pin15,
             miso=pin14)
    CS.write_digital(1)
    RST.write_digital(0)
    sleep(40)
    RST.write_digital(1)
    sleep(100)
    command(0x01)
    sleep(150)
    command(0x11)
    sleep(150)
    command(0x3A,b'\x05')
    command(0x36,b'\x00')
    command(0x13)
    command(0x29)
    sleep(40)

mode = 0
slots = [None,None]
next_slot = 0
level = 58
last_drawn_level = None
last_code = None
streak = 0
last_frame_time = 0
recognized_code = None
last_seen = None

def raw_match(a,b):
    if len(a) != len(b) or len(a) < 12:
        return False
    for x,y in zip(a,b):
        tolerance = max(170, max(x,y)//5)
        if abs(x-y) > tolerance:
            return False
    return True

def same_key(a,b):
    if a is None or b is None or a[0] != b[0]:
        return False
    if a[0] == 'RAW':
        return raw_match(a[1],b[1])
    return a[1] == b[1]

def raw_hash(d):
    h = 2166136261
    for duration in d:
        q = (duration+100)//200
        h = ((h ^ q)*16777619) & 0xFFFFFFFF
    return h

def code_text(key):
    if key is None:
        return '-----'
    protocol,value = key
    if protocol == 'SONY':
        return '{:05X}'.format(value)
    if protocol == 'NEC':
        return '{:08X}'.format(value)
    return '{:08X}'.format(raw_hash(value))

def slot_text(key):
    if key is None:
        return '-----'
    p = key[0]
    if p == 'SONY':
        prefix = 'S'
    elif p == 'NEC':
        prefix = 'N'
    else:
        prefix = 'R'
    return prefix + code_text(key)[-4:]

def draw_slots():
    rect(0,140,128,20,NAVY)
    a = slot_text(slots[0])
    b = slot_text(slots[1])
    text(4,146,'1:'+a+' 2:'+b,WHITE)

def draw_level(force=False):
    global last_drawn_level
    if not force and last_drawn_level == level:
        return
    rect(6,70,116,9,BLACK)
    text(6,70,'LEVEL: '+str(level),WHITE)
    if force or last_drawn_level is None:
        rect(6,91,116,15,NAVY)
        rect(6,91,level,15,GREEN)
    elif level > last_drawn_level:
        rect(6+last_drawn_level,91,
             level-last_drawn_level,15,GREEN)
    elif level < last_drawn_level:
        rect(6+level,91,
             last_drawn_level-level,15,NAVY)
    last_drawn_level = level

def draw_page():
    global last_drawn_level
    last_drawn_level = None
    rect(0,0,128,160,BLACK)
    rect(0,0,128,23,NAVY)
    text(6,5,'INVISIBLE WORLD',WHITE)
    if mode == 0:
        text(6,29,'IR DISCOVER',CYAN)
    else:
        text(6,29,'IR CONTROL',CYAN)
    rect(0,42,128,1,BLUE)
    if mode == 0:
        text(6,51,'LAST SIGNAL',GREY)
        text(6,67,'NONE',WHITE,2)
        text(6,104,'CMD: --',WHITE)
    else:
        text(6,51,'REMOTE CONTROL',GREY)
        draw_level(True)
    text(6,120,'A: MODE B: LEARN',CYAN)
    draw_slots()

def show_signal(key):
    if mode == 1:
        draw_level()
        return
    protocol,value = key
    rect(0,63,128,53,BLACK)
    text(6,66,code_text(key),WHITE,2)
    text(6,86,protocol,CYAN)
    if protocol == 'SONY':
        message = 'CMD: '+str(value & 127)
    elif protocol == 'NEC':
        message = 'CMD: '+str((value >> 16) & 255)
    else:
        message = 'RAW PATTERN'
    text(6,104,message,GREEN)

def near(v,target,tolerance):
    return abs(v-target) <= tolerance

def capture():
    idle_start = ticks_us()
    deadline = ticks_us()
    while ticks_diff(ticks_us(),deadline) < 150000:
        now = ticks_us()
        if IR.read_digital() == 0:
            idle_start = now
        elif ticks_diff(now,idle_start) >= 4000:
            break
    else:
        return None
    start_wait = ticks_us()
    while ticks_diff(ticks_us(),start_wait) < 120000:
        if IR.read_digital() == 0:
            previous = 0
            last_edge = ticks_us()
            break
    else:
        return None
    durations = []
    gap_limit = 6000
    while True:
        signal_level = IR.read_digital()
        now = ticks_us()
        elapsed = ticks_diff(now,last_edge)
        if signal_level != previous:
            if previous == 1 and elapsed > gap_limit:
                return durations
            durations.append(elapsed)
            last_edge = now
            previous = signal_level
            if len(durations) == 1:
                if near(durations[0],2400,550):
                    gap_limit = 3500
            if len(durations) >= 72:
                return durations
        elif previous == 1 and elapsed > gap_limit:
            return durations
        elif elapsed > 15000:
            return durations

def decode_sony(d):
    if len(d) != 41:
        return None
    if not near(d[0],2400,550):
        return None
    value = 0
    for i in range(20):
        space = d[1+2*i]
        pulse = d[2+2*i]
        if not near(space,600,250):
            return None
        if near(pulse,600,250):
            bit = 0
        elif near(pulse,1200,300):
            bit = 1
        else:
            return None
        value |= bit << i
    return ('SONY',value)

def decode_nec(d):
    if len(d) < 2:
        return None
    if not near(d[0],9000,1800):
        return None
    if (len(d) == 3 and
        near(d[1],2250,650) and
        near(d[2],560,300)):
        return ('REPEAT',0)
    if not near(d[1],4500,1100):
        return None
    if len(d) not in (66,67):
        return None
    if len(d) == 67:
        if not near(d[66],560,300):
            return None
    value = 0
    for i in range(32):
        low = d[2+2*i]
        high = d[3+2*i]
        if not near(low,560,300):
            return None
        if near(high,560,300):
            bit = 0
        elif near(high,1690,550):
            bit = 1
        else:
            return None
        value |= bit << i
    cmd = (value >> 16) & 255
    check = (value >> 24) & 255
    if (cmd ^ check) != 255:
        return None
    return ('NEC',value)

def decode(d):
    if d is None or len(d) < 3:
        return None
    if near(d[0],2400,550):
        result = decode_sony(d)
        if result is not None:
            return result
    if near(d[0],9000,1800):
        result = decode_nec(d)
        if result is not None:
            return result
        if (len(d) == 3 and
            near(d[1],2250,650)):
            return None
    if len(d) >= 12 and len(d) <= 71:
        return ('RAW',d)
    return None

def recognize(key):
    global last_code,streak,last_frame_time
    global recognized_code,last_seen,level
    now = running_time()
    if now-last_frame_time > 600:
        last_code = None
        streak = 0
        recognized_code = None
    last_frame_time = now
    if same_key(key,last_code):
        streak += 1
    else:
        last_code = key
        streak = 1
    if key[0] == 'NEC':
        required = 1
    else:
        required = 3
    if streak < required:
        return
    if same_key(key,recognized_code):
        return
    recognized_code = last_code
    last_seen = last_code
    print('')
    print('IR BUTTON RECOGNIZED')
    print('Protocol:',key[0])
    print('Fingerprint:',code_text(last_code))
    print('Matching frames:',streak)
    if key[0] == 'SONY':
        print('Command:',key[1] & 127)
    elif key[0] == 'NEC':
        print('Command:',(key[1] >> 16) & 255)
    else:
        print('RAW pattern recognized')
        print('Pulse intervals:',len(key[1]))
    if mode == 1:
        if same_key(key,slots[0]):
            level = min(116,level+12)
        elif same_key(key,slots[1]):
            level = max(0,level-12)
    show_signal(last_code)

init_tft()
draw_page()
print('')
print('INVISIBLE WORLD - IR TFT v1.2')
print('Sony / NEC / RAW learning')
print('A: Discover / Control')
print('B: Learn last recognized signal')
print('')
while True:
    if button_a.was_pressed():
        mode = 1-mode
        draw_page()
    if button_b.was_pressed():
        if last_seen is not None:
            slots[next_slot] = last_seen
            print('LEARNED SLOT',
                  next_slot+1,
                  last_seen[0],
                  code_text(last_seen))
            next_slot = (next_slot+1)%2
            draw_slots()
        else:
            print('Recognize a signal first')
    durations = capture()
    key = decode(durations)
    if key is None:
        continue
    if key[0] == 'REPEAT':
        continue
    recognize(key)

What's Going On?

The remote sends infrared light in rapidly timed bursts. The 38 kHz receiver detects compatible modulated bursts and outputs digital LOW and HIGH intervals. MicroPython measures the changes in this signal, interprets supported message patterns, and displays the result on the TFT. A hexadecimal fingerprint is an identifier for a signal, not a universal name for POWER, UP or DOWN.

Things to Try

Press the same button several times. Is its fingerprint repeatable? Try another button and compare. Vary the distance and angle. If nothing appears, test another conventional IR remote; some television smart remotes use Bluetooth, while some infrared protocols may not yet be supported.

Make It Your Own

Predict which button will have a different fingerprint before you test it. Record the two fingerprints and their decoded command values, when available. Do not assume a command number means the same physical button on every remote.

2.2 Teach the micro:bit Two Buttons
Infrared DISCOVER TFT display with two learned remote slots
IR DISCOVER — two learned button identifiers · Simulated from the approved MicroPython display routines; example readings, not measured data.

Make It Happen

Remain in IR DISCOVER. Hold the first remote button until its fingerprint appears. Press micro:bit B to save it as slot 1. Hold a different remote button until its fingerprint appears, then press B again to save it as slot 2. The bottom of the TFT shows both learned slots. These assignments are stored in RAM and disappear when power is removed or the program restarts.

What's Going On?

A button's physical label is not transmitted as text. The program learns a signal and associates it with a function. Sony SIRC uses three matching frames for recognition; NEC full frames are checked using the command-complement field. Unknown RAW signals require three similarly timed captures, but this remains experimental.

Things to Try

Teach two unexpected buttons, such as MENU and MUTE, and see whether they can serve as your controls. If the same fingerprint is learned in both slots, choose a different second button. Repeat after restarting the micro:bit to observe what happens to the unsaved assignments.

Make It Your Own

Explain why learning a remote is more flexible than hard-coding one manufacturer's command list. Design labels for your two learned functions.

2.3 Control an Invisible World Instrument
Infrared CONTROL TFT display showing example level 70
IR CONTROL — level meter · Simulated from the approved MicroPython display routines; example readings, not measured data.

Make It Happen

Press micro:bit A to switch from IR DISCOVER to IR CONTROL. Press your first learned button to raise LEVEL, and your second learned button to lower it. The TFT updates only the number and changed portion of the colored bar so its headings remain steady. Press A to return to Discover mode.

What's Going On?

Infrared light carries an instruction, the micro:bit recognizes its learned fingerprint, and the program changes a variable called level. The TFT transforms that number into a graphic. This is the same input → processing → output pattern used in everyday electronic products.

Things to Try

Make the level reach its minimum and maximum. How many successful button recognitions are needed? Try short presses and holds. Compare the behavior with another IR remote, if available.

Make It Your Own

With AI or by editing the program yourself, try changing the level step from 12 to 6, or changing the GREEN bar color. Ask for the smallest possible code change and preserve all working pin assignments and capture timing. Imagine using learned buttons to select screens or control an alarm.

Optional: Invent with AI

Prompt: “My Invisible World micro:bit program uses an ST7735 TFT and a tested Sony infrared decoder. Change only the Control mode bar graph's color when the level exceeds 80. Preserve the P2 receiver, SPI pins, remote learning, and fast partial redraw. Show only the edited lines.”

Troubleshooting and compatibility

Blank TFT: verify the permanent display circuit and its power/backlight connections. No IR signal: check receiver orientation, 3 V/GND, OUT on P2, capacitor position, remote batteries, and that the remote actually uses infrared. Signal appears but does not learn: try holding a button long enough for matching transmissions. Not all protocols are supported; RAW fallback is experimental. Buttons learned but LEVEL does not change: switch to Control mode with A, and learn two different fingerprints.

Compatibility note: Sony SIRC 20-bit has passed physical testing. NEC, Extended NEC and RAW pattern recognition require additional real-remote testing. This chapter does not promise universal remote support.

3. Light — Explore Light
Is light invisible—or not?

Visible light is what your eyes detect. We see a flashlight’s glowing source because light from it enters our eyes. We see a book because light reflects from its surface into our eyes. Your eyes also detect sunlight, but never look directly at the Sun.

A beam passing across a room may be difficult to see from the side: most of its light is traveling somewhere else. Dust, mist, or other particles can scatter some of that light toward your eyes, revealing the beam’s path. You are detecting light that reaches you—not watching every part of its journey.

Infrared and ultraviolet are outside normal human vision. In these experiments, “Invisible World” means revealing light levels, changes, and patterns that our eyes alone do not quantify. We are not claiming that visible light itself is invisible.

Explore further: NASA: Visible Light · NASA: Wave Behaviors

One circuit, three experiments

Use the assembled Invisible World circuit. The phototransistor signal connects to P1, with a 10 kΩ resistor to GND (brown–black–orange). Keep the phototransistor orientation and TFT power/backlight wiring from the working setup. Resistor orientation does not matter.

Approved engineering schematic excerpt C showing phototransistor light sensor and 10 kiloohm resistor to ground, signal to micro:bit P1.
You will need a micro:bit, the kit’s TFT and phototransistor circuit, a computer and USB data cable, a phone flashlight, and a few materials such as tissue, a leaf, fabric, or sunglasses.
What do the numbers mean?

RAW is the analog input reading, from 0 to 1023. It measures the circuit’s voltage response. A percentage compares that response with your saved references; it is not lux. Calibration is lost when you reset or replace the program. The programs average 16 readings to reduce small fluctuations.

Before 3.1 — Check the Phototransistor (Serial Test)

Load this short program in the micro:bit Python Editor, flash it, and open the serial console. The TFT is not initialized by this test; a blank, white, or previous screen is not a test result.

  1. Cover the sensor completely and press A to save the dark reference.
  2. Uncover it, illuminate it, and press B to save the bright reference.
  3. Move your hand over the sensor. RAW should decrease as you shade it and increase as you illuminate it.

In the development test, RAW ranged roughly from 1 to 150. Your range may differ. The bright reference must be at least 50 counts above dark. Once this works, replace the entire program with Light Explorer below.

💻  View & Copy MicroPython Program  ▾ Expand / collapse

from microbit import *

display.off()
dark = None
bright = None

def read_light():
    total = 0
    for _ in range(16):
        total += pin1.read_analog()
        sleep(2)
    return total // 16

while True:
    raw = read_light()
    if button_a.was_pressed():
        dark = raw
        print("Dark reference saved:", dark)
    if button_b.was_pressed():
        bright = raw
        print("Bright reference saved:", bright)
    if dark is None or bright is None:
        print("RAW:", raw, "| Cover: A | Illuminate: B")
    elif bright - dark < 50:
        print("Increase light contrast, then recalibrate.")
    else:
        percent = (raw - dark) * 100 // (bright - dark)
        percent = max(0, min(100, percent))
        print("RAW:", raw, "| LIGHT:", percent, "%")
    sleep(150)

If the copy button is unavailable, select the entire program in the gray box and copy it into the micro:bit Python Editor.

3.1 Light Explorer

See light change as you move and shade the sensor.

Simulated TFT screen: Light Explorer v1.1 · 68% relative light
Simulated screen · illustrative readings
Light Explorer v1.1 · 68% relative light

Make It Happen

Try it

  1. Load and flash the complete program below.
  2. Cover the sensor; press A. Illuminate it; press B.
  3. Move a hand over the sensor. Watch the sun grow or shrink and the percentage change.
  4. Try to hold the reading at 50% for five seconds.

What's Going On?

The sun’s size follows relative light level. RAW shows the averaged sensor reading. The yellow history trace sweeps from left to right, then wraps; it does not scroll. Its horizontal spacing represents successive updates, not a calibrated time scale.

With dark = 1 and bright = 150, RAW = 103 displays 68%. The value is rounded down and limited to 0–100%. A reading of 100% means at or above your bright reference; it does not automatically mean the sensor is saturated.

Things to Try

Can you produce a gradual ramp, a sudden drop, and a repeating pattern? Predict the shape before moving your hand. Outdoors, compare shade with an open area while keeping the sensor pointed in the same direction. Recalibrate for the new conditions.

Make It Your Own

Design a new low-light warning color. What single display change would make the light meter clearer? Keep the P1 circuit and calibration intact.

Try It with AI! Ask AI to give the Light Explorer a nighttime color scheme. Share the working code and ask it to keep the P1 sensor, calibration, and buttons unchanged. Then test your new look on the TFT!

Troubleshooting

SET A THEN B: save both references. MORE CONTRAST: cover more fully or increase illumination, then recalibrate. ADC LIMIT: reduce the light; the input is near its maximum reading.

💻  View & Copy MicroPython Program  ▾ Expand / collapse

# Invisible World - Light Explorer v1.1
# micro:bit, ST7735 128x160. No external driver required.
# TFT: SCL P13, SDA P15, CS P16, DC P8, RES P12.
# Keep the same TFT power/backlight wiring as your working display test.
# Phototransistor signal P1; 10k resistor from signal to GND.
# A saves dark; B saves bright. References reset on restart.
# Reconstructed using the initialization settings from the earlier TFT test.
# Hardware-tested and approved by Ken Gracey, 2026-11-15.
from microbit import *
from math import sin, cos, sqrt, pi

display.off()
W, H = 128, 160
BLACK, WHITE, BLUE, YELLOW = 0, 65535, 0x041F, 0xFFE0
CS, DC, RESET = pin16, pin8, pin12
spi.init(baudrate=1000000, bits=8, mode=0,
         sclk=pin13, mosi=pin15, miso=pin14)

def command(value, payload=None):
    CS.write_digital(0)
    DC.write_digital(0)
    spi.write(bytes([value]))
    if payload is not None:
        DC.write_digital(1)
        spi.write(payload)
    CS.write_digital(1)

def window(x, y, w, h):
    command(0x2A, bytes([0, x, 0, x+w-1]))
    command(0x2B, bytes([0, y, 0, y+h-1]))
    command(0x2C)

def rect(x, y, w, h, color):
    x, y, w, h = int(x), int(y), int(w), int(h)
    if x < 0 or y < 0 or x+w > W or y+h > H or w < 1 or h < 1:
        return
    window(x, y, w, h)
    row = bytes([color >> 8, color & 255]) * w
    CS.write_digital(0)
    DC.write_digital(1)
    for _ in range(h):
        spi.write(row)
    CS.write_digital(1)

# Compact 3x5 font. Rows stored as three-bit numbers.
FONT = {
 '0':(7,5,5,5,7), '1':(2,6,2,2,7), '2':(7,1,7,4,7),
 '3':(7,1,7,1,7), '4':(5,5,7,1,1), '5':(7,4,7,1,7),
 '6':(7,4,7,5,7), '7':(7,1,2,2,2), '8':(7,5,7,5,7),
 '9':(7,5,7,1,7), 'A':(2,5,7,5,5), 'B':(6,5,6,5,6),
 'C':(7,4,4,4,7), 'D':(6,5,5,5,6), 'E':(7,4,6,4,7),
 'F':(7,4,6,4,4), 'G':(7,4,5,5,7), 'H':(5,5,7,5,5),
 'K':(5,5,6,5,5), 'I':(7,2,2,2,7), 'L':(4,4,4,4,7), 'N':(5,7,7,7,5),
 'M':(5,7,7,5,5), 'X':(5,5,2,5,5), 'O':(7,5,5,5,7), 'P':(7,5,7,4,4), 'R':(6,5,6,5,5),
 'S':(7,4,7,1,7), 'T':(7,2,2,2,2), 'U':(5,5,5,5,7),
 'V':(5,5,5,5,2), 'W':(5,5,7,7,5), 'Y':(5,5,2,2,2),
 '%':(5,1,2,4,5), ':':(0,2,0,2,0), '-':(0,0,7,0,0),
 ' ':(0,0,0,0,0)
}

def text(value, x, y, scale=1, color=WHITE):
    # Render one text strip with one SPI transfer to avoid per-pixel traffic.
    value = str(value)
    width = len(value)*4*scale
    height = 5*scale
    if x+width > W or y+height > H:
        return
    buf = bytearray(width*height*2)
    hi, lo = color >> 8, color & 255
    for i, ch in enumerate(value):
        glyph = FONT.get(ch, FONT[' '])
        for gy in range(5):
            for gx in range(3):
                if glyph[gy] & (4 >> gx):
                    for sy in range(scale):
                        for sx in range(scale):
                            p = 2*((gy*scale+sy)*width+i*4*scale+gx*scale+sx)
                            buf[p], buf[p+1] = hi, lo
    window(x, y, width, height)
    CS.write_digital(0)
    DC.write_digital(1)
    spi.write(buf)
    CS.write_digital(1)

CS.write_digital(1)
RESET.write_digital(1)
sleep(10)
RESET.write_digital(0)
sleep(20)
RESET.write_digital(1)
sleep(120)
command(0x01)
sleep(150)
command(0x11)
sleep(150)
command(0x3A, b'\x05')
command(0x36, b'\x00')
command(0x13)
command(0x29)
sleep(100)
rect(0, 0, W, H, BLACK)
text('LIGHT EXPLORER', 8, 4, 2)
text('A:DARK B:BRIGHT', 8, 150, 2)

# Small animation buffer avoids allocating a full RGB565 screen.
def sun(level):
    size = 56
    buf = bytearray(size*size*2)
    radius = 5 + level*12//100
    outer = radius+7
    def pixel(x, y):
        if 0 <= x < size and 0 <= y < size:
            p = (y*size+x)*2
            buf[p], buf[p+1] = 255, 224
    for y in range(-radius, radius+1):
        half = int(sqrt(radius*radius-y*y))
        for x in range(-half, half+1):
            pixel(28+x, 28+y)
    for ray in range(12):
        angle = ray*pi/6
        for r in range(radius+3, outer+1):
            pixel(28+int(cos(angle)*r), 28+int(sin(angle)*r))
    window(36, 19, size, size)
    CS.write_digital(0)
    DC.write_digital(1)
    spi.write(buf)
    CS.write_digital(1)

def read_light():
    total = 0
    for _ in range(16):
        total += pin1.read_analog()
        sleep(2)
    return total//16

dark = None
bright = None
graph_x = 0
previous_y = None
last_sun = -1
rect(3, 116, 122, 1, BLUE)
rect(3, 145, 122, 1, BLUE)
print('LIGHT EXPLORER')
print('Cover sensor and press A to save dark.')
print('Illuminate sensor and press B to save bright.')
print('Percentage is relative sensor response, not lux.')
while True:
    raw = read_light()
    changed = False
    if button_a.was_pressed():
        dark = raw
        changed = True
        print('Dark reference saved:', dark)
    if button_b.was_pressed():
        bright = raw
        changed = True
        print('Bright reference saved:', bright)
    valid = dark is not None and bright is not None and bright-dark >= 50
    percent = 0
    if valid:
        percent = max(0, min(100, (raw-dark)*100//(bright-dark)))
        status = 'RELATIVE LIGHT'
        print('RAW:', raw, '| LIGHT:', percent, '%')
    elif dark is None or bright is None:
        status = 'SET A THEN B'
        print('RAW:', raw, '| Cover: A | Illuminate: B')
    else:
        status = 'MORE CONTRAST'
        print('RAW:', raw, '| Increase light contrast, then recalibrate.')
    # Rail detection does not detect every form of transistor saturation.
    if raw >= 1020:
        status = 'ADC LIMIT'
    level = percent if valid else 0
    if level != last_sun:
        sun(level)
        last_sun = level
    text(('%3d%%' % percent) if valid else ' --%', 32, 79, 4)
    text(('RAW:%4d' % raw), 32, 100, 2)
    padded_status = (status + '               ')[:15]
    text(padded_status, 34, 111)
    if changed:
        rect(4, 117, 120, 28, BLACK)
        graph_x = 0
        previous_y = None
    if valid:
        # Sweep history: newest column advances right, then wraps.
        # Horizontal spacing is one completed update, not a calibrated timebase.
        x = 4+graph_x
        rect(x, 117, 1, 28, BLACK)
        y = 144-percent*27//100
        if previous_y is None or graph_x == 0:
            rect(x, y, 1, 1, YELLOW)
        else:
            rect(x, min(y, previous_y), 1, abs(y-previous_y)+1, YELLOW)
        previous_y = y
        graph_x = (graph_x+1)%120
    sleep(150)

If the copy button is unavailable, select the entire program in the gray box and copy it into the micro:bit Python Editor.

3.2 Shadow Detective

Turn a passing shadow into a trace and a counted event.

Simulated TFT screen: Shadow Detective v1.1 · three illustrative shadows
Simulated screen · illustrative readings
Shadow Detective v1.1 · three illustrative shadows

Make It Happen

Try it

  1. Load and flash the complete program. Cover the sensor and press A; illuminate it and press B.
  2. Keep a steady light aimed at the sensor. Pass your hand through the light three times, allowing the reading to recover each time.
  3. Look for three valleys in the yellow trace and a count of three.
  4. Press A to cycle the threshold through 25%, 50%, and 75%.
  5. Press B to pause the graph and counting; press it again to resume.

What's Going On?

Yellow shows light level; blue marks the trigger threshold. The newest sample appears at the right. The graph holds 120 updates and scrolls once full. The program aims for four updates per second, but display work can slow this; use serial timestamps if you need actual timing.

A shadow is counted when the reading reaches or falls below the threshold after the detector has armed. It arms only after light reaches 10 percentage points above the threshold. At a 50% threshold, restore at least 60% before the next shadow. This prevents small fluctuations from counting repeatedly.

MIN and MAX are the lowest and highest percentages recorded since calibration, excluding pauses. Changing the threshold or resuming disarms detection until light recovers. Reset the micro:bit to recalibrate and clear the count.

Things to Try

Compare a slow hand pass with a fast one. Which valley is wider? Can a partly transparent material trigger a count at 75% but not at 25%?

Make It Your Own

Imagine using the shadow counter to count visitors. Which label would make the result easier to read, without changing how shadows are detected?

Troubleshooting

No new count: first restore light above threshold + 10, then make a clear shadow. Very brief shadows can occur between samples; make each pass last about a second for the first test. PAUSED B:GO: press B to resume. A is ignored while paused.

💻  View & Copy MicroPython Program  ▾ Expand / collapse

# Invisible World - Shadow Detective v1.1
# micro:bit; same wiring as Light Explorer.
# P1 phototransistor with 10k to GND.
# TFT: SCL P13, SDA P15, CS P16, DC P8, RES P12.
# Keep existing TFT power/backlight connections.
# Startup: cover sensor and press A, illuminate and press B.
# Running: A cycles threshold; B pauses/resumes graph AND counting.
# Reset micro:bit to recalibrate and clear count.
# Hardware-tested and approved by Ken Gracey, 2026-11-15.
from microbit import *

display.off()
W, H = 128, 160
BLACK, WHITE, BLUE, YELLOW = 0, 65535, 0x041F, 0xFFE0
CS, DC, RESET = pin16, pin8, pin12
spi.init(baudrate=1000000, bits=8, mode=0,
         sclk=pin13, mosi=pin15, miso=pin14)

def command(value, payload=None):
    CS.write_digital(0)
    DC.write_digital(0)
    spi.write(bytes([value]))
    if payload is not None:
        DC.write_digital(1)
        spi.write(payload)
    CS.write_digital(1)

def window(x, y, w, h):
    command(0x2A, bytes([0, x, 0, x+w-1]))
    command(0x2B, bytes([0, y, 0, y+h-1]))
    command(0x2C)

def rect(x, y, w, h, color):
    x, y, w, h = int(x), int(y), int(w), int(h)
    if x < 0 or y < 0 or x+w > W or y+h > H or w < 1 or h < 1:
        return
    window(x, y, w, h)
    row = bytes([color >> 8, color & 255]) * w
    CS.write_digital(0)
    DC.write_digital(1)
    for _ in range(h):
        spi.write(row)
    CS.write_digital(1)

# Compact 3x5 font. Rows stored as three-bit numbers.
FONT = {
 '0':(7,5,5,5,7), '1':(2,6,2,2,7), '2':(7,1,7,4,7),
 '3':(7,1,7,1,7), '4':(5,5,7,1,1), '5':(7,4,7,1,7),
 '6':(7,4,7,5,7), '7':(7,1,2,2,2), '8':(7,5,7,5,7),
 '9':(7,5,7,1,7), 'A':(2,5,7,5,5), 'B':(6,5,6,5,6),
 'C':(7,4,4,4,7), 'D':(6,5,5,5,6), 'E':(7,4,6,4,7),
 'F':(7,4,6,4,4), 'G':(7,4,5,5,7), 'H':(5,5,7,5,5),
 'Z':(7,1,2,4,7), 'K':(5,5,6,5,5), 'I':(7,2,2,2,7), 'L':(4,4,4,4,7), 'N':(5,7,7,7,5),
 'M':(5,7,7,5,5), 'X':(5,5,2,5,5), 'O':(7,5,5,5,7), 'P':(7,5,7,4,4), 'R':(6,5,6,5,5),
 'S':(7,4,7,1,7), 'T':(7,2,2,2,2), 'U':(5,5,5,5,7),
 'V':(5,5,5,5,2), 'W':(5,5,7,7,5), 'Y':(5,5,2,2,2),
 '%':(5,1,2,4,5), ':':(0,2,0,2,0), '-':(0,0,7,0,0),
 ' ':(0,0,0,0,0)
}

def text(value, x, y, scale=1, color=WHITE):
    # Render one text strip with one SPI transfer to avoid per-pixel traffic.
    value = str(value)
    width = len(value)*4*scale
    height = 5*scale
    if x+width > W or y+height > H:
        return
    buf = bytearray(width*height*2)
    hi, lo = color >> 8, color & 255
    for i, ch in enumerate(value):
        glyph = FONT.get(ch, FONT[' '])
        for gy in range(5):
            for gx in range(3):
                if glyph[gy] & (4 >> gx):
                    for sy in range(scale):
                        for sx in range(scale):
                            p = 2*((gy*scale+sy)*width+i*4*scale+gx*scale+sx)
                            buf[p], buf[p+1] = hi, lo
    window(x, y, width, height)
    CS.write_digital(0)
    DC.write_digital(1)
    spi.write(buf)
    CS.write_digital(1)

CS.write_digital(1)
RESET.write_digital(1)
sleep(10)
RESET.write_digital(0)
sleep(20)
RESET.write_digital(1)
sleep(120)
command(0x01)
sleep(150)
command(0x11)
sleep(150)
command(0x3A, b'\x05')
command(0x36, b'\x00')
command(0x13)
command(0x29)
sleep(100)
rect(0, 0, W, H, BLACK)
text('SHADOW', 40, 3, 2)
text('DETECTIVE', 28, 16, 2)


def read_light():
    total = 0
    for _ in range(16):
        total += pin1.read_analog()
        sleep(2)
    return total // 16


def field(value, y):
    text((value + '               ')[:15], 4, y, 2)


def calibrate():
    dark = None
    field('COVER THEN A', 40)
    field('LIGHT THEN B', 55)
    print('Cover sensor and press A. Illuminate and press B.')
    while True:
        raw = read_light()
        field('RAW:%4d' % raw, 75)
        if button_a.was_pressed():
            dark = raw
            field('DARK:%4d' % dark, 95)
            print('Dark reference saved:', dark)
        if button_b.was_pressed():
            if dark is None:
                field('SET DARK FIRST', 110)
            elif raw - dark < 50:
                field('MORE CONTRAST', 110)
                print('Increase light contrast, then press B again.')
            else:
                print('Bright reference saved:', raw)
                return dark, raw
        print('RAW:', raw)
        sleep(100)


def detect(level, threshold, armed, count):
    # Require light to return above threshold + 10 before another count.
    if level >= threshold + 10:
        armed = True
    elif level <= threshold and armed:
        count += 1
        armed = False
    return armed, count


GRAPH_W = 120
GRAPH_H = 64
plot = bytearray(GRAPH_W * GRAPH_H * 2)
history = []


def graph(threshold):
    # Reuse one small buffer; yellow trace, blue threshold line.
    for i in range(len(plot)):
        plot[i] = 0
    ty = 63 - threshold * 63 // 100
    for x in range(GRAPH_W):
        p = (ty * GRAPH_W + x) * 2
        plot[p], plot[p + 1] = 4, 31
    offset = GRAPH_W - len(history)
    last_y = None
    for i, level in enumerate(history):
        x = offset + i
        y = 63 - level * 63 // 100
        top = y if last_y is None else min(y, last_y)
        bottom = y if last_y is None else max(y, last_y)
        for py in range(top, bottom + 1):
            p = (py * GRAPH_W + x) * 2
            plot[p], plot[p + 1] = 255, 224
        last_y = y
    window(4, 60, GRAPH_W, GRAPH_H)
    CS.write_digital(0)
    DC.write_digital(1)
    spi.write(plot)
    CS.write_digital(1)


dark, bright = calibrate()
rect(0, 29, 128, 131, BLACK)
thresholds = (25, 50, 75)
threshold_index = 1
threshold = thresholds[threshold_index]
armed = False
count = 0
paused = False
minimum = 100
maximum = 0
last_count = -1
print('A: threshold 25/50/75 percent. B: pause/resume.')
print('Blue line: threshold. Yellow trace: relative light.')
print('Reset micro:bit to recalibrate and clear count.')

while True:
    started = running_time()
    a = button_a.was_pressed()
    b = button_b.was_pressed()
    if b:
        paused = not paused
        armed = False
        print('PAUSED' if paused else 'RUNNING')
    if a and not paused:
        threshold_index = (threshold_index + 1) % 3
        threshold = thresholds[threshold_index]
        armed = False
        print('Threshold:', threshold, '%')
    if not paused:
        raw = read_light()
        level = max(0, min(100, (raw - dark) * 100 // (bright - dark)))
        minimum = min(minimum, level)
        maximum = max(maximum, level)
        armed, count = detect(level, threshold, armed, count)
        history.append(level)
        if len(history) > GRAPH_W:
            history.pop(0)
        graph(threshold)
        field('LIGHT:%3d%%' % level, 32)
        field('COUNT:%6d' % min(count, 999999), 46)
        field('MIN:%3d MAX:%3d' % (minimum, maximum), 128)
        print('MS:', running_time(), '| RAW:', raw,
              '| LIGHT:', level, '| THRESHOLD:', threshold,
              '| SHADOWS:', count)
        if count != last_count:
            if last_count >= 0:
                print('SHADOW DETECTED')
            last_count = count
    field(('PAUSED B:GO' if paused else 'A:THR %2d B:HOLD' % threshold), 146)
    # Aim for four updates/second; actual sample times appear in serial.
    elapsed = running_time() - started
    sleep(max(1, 250 - elapsed))

If the copy button is unavailable, select the entire program in the gray box and copy it into the micro:bit Python Editor.

3.3 Light Through Materials

Predict and compare how materials change the light reaching the sensor.

Simulated TFT screen: Light Through Materials v1.0 · 37% relative response
Simulated screen · illustrative readings
Light Through Materials v1.0 · 37% relative response

Make It Happen

Try it

  1. Load and flash the complete program. Begin in a dim room.
  2. Cover the sensor completely; press A to save the dark baseline.
  3. Uncover it. Aim a stationary phone flashlight at the sensor with no sample between them; press B to save the reference.
  4. Keep the phone and sensor fixed. Place tissue, a leaf, fabric, or sunglasses between them.
  5. Record the sample percentage. Predict what a second layer will do, then test it.

What's Going On?

The blue reference bar is 100%. The yellow sample bar shows the current response relative to that reference. REDUCTION is 100 minus the sample percentage when the sample is at or below 100%. RAW remains visible, and serial output includes the dark and reference values.

Relative response (%) = 100 × (sample RAW − dark RAW) ÷ (reference RAW − dark RAW)

For example, dark = 1, reference = 150, and sample = 57 produce 37% after rounding down, with a 63% reduction. This is approximate relative transmission inferred from sensor response, not a calibrated measurement of optical transmission. Light color, sensor response, scattering, surrounding light, and geometry affect the result. A covered-sensor baseline does not subtract ambient light falling on an uncovered sensor, so keep ambient light low and steady.

Things to Try

Rank three materials from highest to lowest reading before testing. Does doubling a material’s layers halve the reading? Explain what your data shows rather than assuming a rule.

Material / layers Prediction Sample % Observation
Sample 1 — — —
Sample 2 — — —
Two layers — — —

Make It Your Own

Design a results chart to compare three materials. Would you recommend any of them as light filters or window shades? Explain using relative readings.

Troubleshooting

MORE LIGHT: the reference must be at least 50 counts above dark. REDUCE LIGHT: the reference is too near the ADC maximum. CHECK SETUP: the sample is above 105%; check alignment, surroundings, and the reference. Percentages above 100% remain visible, but the bar stops at full width. Return to the uncovered arrangement and press B to renew the reference. Pressing A saves a new dark baseline and clears the old reference.

💻  View & Copy MicroPython Program  ▾ Expand / collapse

# Invisible World - Light Through Materials v1.0
# micro:bit; same tested ST7735 driver and four-pixel text margins.
# Phototransistor: P1, 10k resistor to GND.
# TFT: SCL P13, SDA P15, CS P16, DC P8, RES P12.
# Retain existing power/backlight wiring.
# A records dark and clears reference; B records uncovered reference.
# Keep the source and sensor fixed; insert samples into the light path.
# Relative readings are approximate sensor-response comparisons, not lux.
# Hardware-tested and approved by Ken Gracey, 2026-11-15.
# Documentation follow-up: create accurate TFT screen simulations for
# Light Explorer, Shadow Detective, and Light Through Materials.
# Match each approved program; label simulated readings as illustrative.
from microbit import *

display.off()
W, H = 128, 160
BLACK, WHITE, BLUE, YELLOW = 0, 65535, 0x041F, 0xFFE0
CS, DC, RESET = pin16, pin8, pin12
spi.init(baudrate=1000000, bits=8, mode=0,
         sclk=pin13, mosi=pin15, miso=pin14)

def command(value, payload=None):
    CS.write_digital(0)
    DC.write_digital(0)
    spi.write(bytes([value]))
    if payload is not None:
        DC.write_digital(1)
        spi.write(payload)
    CS.write_digital(1)

def window(x, y, w, h):
    command(0x2A, bytes([0, x, 0, x+w-1]))
    command(0x2B, bytes([0, y, 0, y+h-1]))
    command(0x2C)

def rect(x, y, w, h, color):
    x, y, w, h = int(x), int(y), int(w), int(h)
    if x < 0 or y < 0 or x+w > W or y+h > H or w < 1 or h < 1:
        return
    window(x, y, w, h)
    row = bytes([color >> 8, color & 255]) * w
    CS.write_digital(0)
    DC.write_digital(1)
    for _ in range(h):
        spi.write(row)
    CS.write_digital(1)

# Compact 3x5 font. Rows stored as three-bit numbers.
FONT = {
 '0':(7,5,5,5,7), '1':(2,6,2,2,7), '2':(7,1,7,4,7),
 '3':(7,1,7,1,7), '4':(5,5,7,1,1), '5':(7,4,7,1,7),
 '6':(7,4,7,5,7), '7':(7,1,2,2,2), '8':(7,5,7,5,7),
 '9':(7,5,7,1,7), 'A':(2,5,7,5,5), 'B':(6,5,6,5,6),
 'C':(7,4,4,4,7), 'D':(6,5,5,5,6), 'E':(7,4,6,4,7),
 'F':(7,4,6,4,4), 'G':(7,4,5,5,7), 'H':(5,5,7,5,5),
 'Z':(7,1,2,4,7), 'K':(5,5,6,5,5), 'I':(7,2,2,2,7), 'L':(4,4,4,4,7), 'N':(5,7,7,7,5),
 'M':(5,7,7,5,5), 'X':(5,5,2,5,5), 'O':(7,5,5,5,7), 'P':(7,5,7,4,4), 'R':(6,5,6,5,5),
 'S':(7,4,7,1,7), 'T':(7,2,2,2,2), 'U':(5,5,5,5,7),
 'V':(5,5,5,5,2), 'W':(5,5,7,7,5), 'Y':(5,5,2,2,2),
 '%':(5,1,2,4,5), ':':(0,2,0,2,0), '-':(0,0,7,0,0),
 ' ':(0,0,0,0,0)
}

def text(value, x, y, scale=1, color=WHITE):
    # Render one text strip with one SPI transfer to avoid per-pixel traffic.
    value = str(value)
    width = len(value)*4*scale
    height = 5*scale
    if x+width > W or y+height > H:
        return
    buf = bytearray(width*height*2)
    hi, lo = color >> 8, color & 255
    for i, ch in enumerate(value):
        glyph = FONT.get(ch, FONT[' '])
        for gy in range(5):
            for gx in range(3):
                if glyph[gy] & (4 >> gx):
                    for sy in range(scale):
                        for sx in range(scale):
                            p = 2*((gy*scale+sy)*width+i*4*scale+gx*scale+sx)
                            buf[p], buf[p+1] = hi, lo
    window(x, y, width, height)
    CS.write_digital(0)
    DC.write_digital(1)
    spi.write(buf)
    CS.write_digital(1)

CS.write_digital(1)
RESET.write_digital(1)
sleep(10)
RESET.write_digital(0)
sleep(20)
RESET.write_digital(1)
sleep(120)
command(0x01)
sleep(150)
command(0x11)
sleep(150)
command(0x3A, b'\x05')
command(0x36, b'\x00')
command(0x13)
command(0x29)
sleep(100)
rect(0, 0, W, H, BLACK)
text('LIGHT THROUGH', 12, 3, 2)
text('MATERIALS', 28, 16, 2)


def field(value, y):
    text((value + '               ')[:15], 4, y, 2)


def read_light():
    total = 0
    for _ in range(16):
        total += pin1.read_analog()
        sleep(2)
    return total // 16


def relative(raw, dark, reference):
    return max(0, (raw - dark) * 100 // (reference - dark))


def bar(y, percent, color):
    width = min(100, max(0, percent)) * 120 // 100
    rect(4, y, 120, 12, 0x1082)
    if width:
        rect(4, y, width, 12, color)


field('A:DARK B:REF', 148)
dark = None
reference = None
notice = ''
notice_until = 0

print('LIGHT THROUGH MATERIALS')
print('Cover sensor completely; press A for dark baseline.')
print('Remove covering, aim steady flashlight; press B for reference.')
print('Keep phone and sensor fixed. Insert only the material.')
print('Approximate relative sensor response, not calibrated transmission.')

while True:
    raw = read_light()
    if button_a.was_pressed():
        dark = raw
        reference = None
        notice = 'DARK SAVED'
        notice_until = running_time() + 1200
        print('Dark baseline saved:', dark)

    if button_b.was_pressed():
        if dark is None:
            notice = 'SET DARK FIRST'
        elif raw >= 1020:
            notice = 'REDUCE LIGHT'
            print('Reference rejected: ADC near maximum.')
        elif raw - dark < 50:
            notice = 'MORE LIGHT'
            print('Reference rejected: need at least 50 counts above dark.')
        else:
            reference = raw
            notice = 'REF SAVED'
            print('Uncovered reference saved:', reference)
        notice_until = running_time() + 1200

    if reference is not None:
        percent = relative(raw, dark, reference)
        field('REF:100%', 34)
        bar(48, 100, BLUE)
        field('SAMPLE:%4d%%' % percent, 67)
        bar(81, percent, YELLOW)
        if percent <= 100:
            field('REDUCTION:%3d%%' % (100 - percent), 102)
        else:
            field('ABOVE REFERENCE', 102)
        status = 'INSERT MATERIAL'
        if percent > 105:
            status = 'CHECK SETUP'
        if raw >= 1020:
            status = 'ADC LIMIT'
        print('RAW:', raw, '| DARK:', dark, '| REF:', reference,
              '| RELATIVE:', percent, '%')
    else:
        field('REF: --', 34)
        bar(48, 0, BLUE)
        field('SAMPLE: --', 67)
        bar(81, 0, YELLOW)
        field('REDUCTION: --', 102)
        status = 'COVER THEN A' if dark is None else 'UNCOVER THEN B'
        print('RAW:', raw, '|', status)

    field('RAW:%4d' % raw, 118)
    if running_time() < notice_until:
        field(notice, 133)
    else:
        field(status, 133)
    sleep(150)

If the copy button is unavailable, select the entire program in the gray box and copy it into the micro:bit Python Editor.

4. Temperature — The Secret Life of Heat 
Invisible World engineering schematic Rev D, section D: thermistor divider
Engineering schematic · Section D · Rev D

Is temperature really invisible? Yes. Temperature is invisible, but its effects are visible. We see ice melt, water boil, and materials expand, but we cannot directly see the thermal energy associated with temperature. We feel warmth and cold through our skin, but our senses cannot accurately measure temperature. The 10 kΩ NTC thermistor turns changes in temperature into something students can watch on the color TFT.

The waterproof temperature probe makes invisible thermal changes visible as a filling spectrum thermometer, a temperature history graph, and a 256-level color display. The TFT measures temperature at one sensor location; its graphics are not thermal-camera images.

Build the Circuit

Use the Invisible World engineering schematic. Keep the TFT wired as before: SCL P13, SDA P15, CS P16, DC P8, RES P12, VCC regulated 3V and GND. Connect the voltage divider exactly as shown:

Regulated 3V → 10 kΩ NTC thermistor → P2 → 10 kΩ fixed resistor → Vss (GND)

P2 is the junction between the thermistor and fixed resistor. The fixed resistor has brown-black-orange bands. The thermistor is not polarized.

Important: The moisture/conductivity probe chapter also uses P2. Disconnect its AOUT wire before installing the thermistor divider. Never connect the thermistor and another sensor output to P2 simultaneously. If the infrared receiver OUT or moisture probe AOUT is attached to P2, disconnect it first. Switch power off before rewiring. Use regulated 3V, not battery Vin.

Meet the Waterproof Temperature Probe

The kit's 10 kΩ thermistor has a stainless-steel sensing tip on a cable. Its resistance changes as the tip warms or cools, letting the micro:bit measure the temperature of air, soil, or water. Only the metal tip goes into water—keep the connector, breadboard, battery pack, and other electronics dry.

Two temperature experiments side by side: a stainless-steel DROK temperature probe in steaming warm water and in an ice-water bath, with both black wires and the probe junction kept above the water.
Compare warm water and an ice bath. Immerse only the stainless-steel sensing tip; keep the cable junction and electronics dry.
Optional reference: Probe specifications and design choices

Our Waterproof 10 kΩ Thermistor Probe

Why we chose this thermistor: We deliberately selected a commercially packaged, specification-rated temperature probe instead of an inexpensive bare thermistor with short, fragile leads and uncertain documentation. Its stainless-steel waterproof sensing tip, 1-meter cable, 10 kΩ/B3950 specifications, and usable temperature range make it more versatile for real experiments: measuring air, water, soil, warming and cooling, and temperature changes over time. The sensor can be reused well beyond this tutorial in student-built instruments and inventions. The published ratings describe the probe; they do not mean the entire micro:bit circuit is waterproof or independently certified for industrial applications.

The new sensor is a 10K/B3950 stainless-steel waterproof temperature probe, with a one-meter insulated cable. Its sealed metal tip can be immersed in water, making temperature measurements possible without moving the breadboard, micro:bit, or TFT. The probe is a passive two-wire NTC thermistor: there is no polarity, and its resistance decreases as temperature rises. 

Specification Value and meaning
Thermistor type 10 kΩ NTC at 25°C / 77°F
Beta coefficient B3950 (3950 K): defines how resistance changes with temperature
Listed tolerance 1% stated; this is not a guarantee of 1% temperature accuracy
Probe operating range Advertised −25°C to +125°C (−13°F to +257°F)
Immersion tip Waterproof stainless-steel housing, approximately 5 mm × 25 mm
Lead and connector 1 m / 3.28 ft PVC lead, 2-pin JST XH 2.54 mm connector
Electrical use Passive 2-wire resistance sensor; use regulated 3V in our divider

Sensor specifications: kit component SKU 28093 (10 kΩ/B3950 waterproof temperature probe). The listed measurement range describes the probe, not the safe temperature range of the micro:bit or breadboard. Only immerse the stainless-steel tip; keep connectors and electronics dry.

Engineering Lab — How the micro:bit Measures Temperature

The thermistor changes electrically when it becomes warmer or cooler. The micro:bit reads that change and Python turns it into a temperature on the TFT. You don't need to solve equations to try these experiments.

  1. Temperature changes the sensor. A thermistor is a special resistor. Its resistance gets lower when it warms up and higher when it cools down.
  2. The circuit changes the voltage. The thermistor and the fixed 10 kΩ resistor make a voltage divider. Warmer temperatures send a higher voltage to pin P2 in this circuit.
  3. The micro:bit reads a number. P2 converts the voltage to an analog reading from 0 to 1023. Around room temperature (25°C / 77°F), the reading is about 512; warmer temperatures give larger numbers.
  4. Python shows the temperature. The program uses the reading to calculate Celsius or Fahrenheit and updates the colors and numbers on the TFT.

Example micro:bit Readings

These are calculated examples for the supplied 10 kΩ/B3950 thermistor and 10 kΩ resistor, not measurements from a particular kit.

Temperature Approximate P2 reading (0–1023)
10°C / 50°F (cool) 339
25°C / 77°F (room temperature) 512
40°C / 104°F (warm) 669

Try it: Place only the waterproof stainless-steel tip in cool water and then in comfortably warm water. Watch the numbers rise or fall. These P2 numbers are electrical readings, not degrees—the program does the conversion for you.

New Experiments Made Possible by a Waterproof Probe

  • Ice-water reference: Immerse the stainless-steel tip in stirred ice water and compare the measurement to 0°C / 32°F.
  • Warm and cool water: Compare two cups of comfortably warm and cool water, watching the Thermal Spectrum bar rise.
  • Thermal mixing: Predict and measure the temperature when different quantities of warm and cool water are mixed.
  • Cooling curves: Move the probe from warm water to cool water and record its response in Heat Detective.
  • Environmental investigations: Compare soil, shady and sunny sites, or shallow water while keeping the electronics dry.

Safety: Never immerse the connector, bare connections, breadboard, TFT, micro:bit, or battery pack. Do not assume the cable connector is waterproof. Use classroom-safe water temperatures; do not use the project as a food-safety, medical or burn-safety thermometer.

What You'll See

THERMAL SPECTRUM
179.2F
F
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 


212
140
99
72
32
0
BOIL
BODY
ROOM
ICE
A MODE B C/F
Thermal Spectrum — 179.2°F, rainbow thermometer 84.5% full
HEAT DETECTIVE
179.2F
A MODE   B C/F
Heat Detective — 179.2°F (graph at upper limit)
CHAMELEON
179.2F
TOUCH SENSOR


A MODE   B C/F
Chameleon — 179.2°F (palette maximum)
4.1 Thermal Spectrum — From Freezing to Boiling

Make It Happen

Goal: Build a temperature instrument with a large digital number and a multicolored thermometer bar. The bar fills upward as the probe gets warmer. The fixed scale spans 0–212°F (approximately −17.8°C to 100°C). Water normally freezes at 32°F (0°C) and boils near 212°F (100°C) at sea level.

Get the Code — Thermal World v1.8 (All Three Modes)

Open the micro:bit Python Editor. Expand the complete program below in 4.1, click Copy Code or Download Code, then flash it to your micro:bit. Chapter 4 uses one complete program; you do not need separate code for each experiment.

Controls: Button A cycles through Thermal Spectrum, Heat Detective and Temperature Chameleon. Button B switches Celsius and Fahrenheit. The program uses the 10 kΩ/B3950 nominal thermistor model without the original prototype's one-point offset.

Hardware-approved: Thermal World v1.8 has been tested on the actual Invisible World micro:bit, ST7735 TFT, and waterproof 10 kΩ/B3950 thermistor hardware and approved for the Chapter 4 experiments. Button A switches between Thermal Spectrum, Heat Detective, and Temperature Chameleon; Button B switches °C/°F. This is a classroom measurement and visualization project, not a certified precision thermometer. If a reading is implausible, compare with a reference thermometer and check for wet electrical connections.

Water safety: Experiment from ice water through comfortably hot tap water under supervision. Avoid scalding, boiling, and freshly microwaved water. Submerge only the stainless-steel sensing tip, keeping the connector, wire junctions, micro:bit, power pack, and TFT dry.

Complete Thermal World v1.8 MicroPython code: The full listing is directly below with Copy Code and Download Code buttons.

💻  View & Copy MicroPython Program — Thermal World v1.8  ▾ Expand / collapse

Select all the code below and copy it directly to the micro:bit Python Editor. No library files are required.

# ==========================================================
# INVISIBLE WORLD - THERMAL WORLD v1.8
# Parallax Limited Edition micro:bit Kit - SKU 32890
# micro:bit / ST7735 128x160 TFT
#
# TFT: SCL=P13 SDA=P15 CS=P16 DC=P8 RES=P12
# 3V -> 10K NTC -> P2 -> 10K fixed resistor -> GND
# Button A: next mode    Button B: Celsius/Fahrenheit
#
# Modes: Thermal Spectrum / Heat Detective / Chameleon
# Only changing screen regions are updated.
# Thermistor: R25=10K, Beta=3950 (no calibration offset)
# ==========================================================
from microbit import *
import math

W, H = 128, 160
CS, DC, RST, NTC = pin16, pin8, pin12, pin2
R_FIXED = 10000.0
R25 = 10000.0
BETA = 3950.0
T25 = 298.15

BLACK = 0x0000
WHITE = 0xFFFF
NAVY = 0x0010
BLUE = 0x047F
CYAN = 0x07FF
GREEN = 0x07E0
YELLOW = 0xFFE0
ORANGE = 0xFD20
RED = 0xF800
GREY = 0x8410
DARK = 0x1082

CS.write_digital(1)
DC.write_digital(1)
RST.write_digital(1)
spi.init(baudrate=8000000, bits=8, mode=0,
         sclk=pin13, mosi=pin15, miso=pin14)


def command(value, data=None):
    CS.write_digital(0)
    DC.write_digital(0)
    spi.write(bytes([value]))
    if data is not None:
        DC.write_digital(1)
        spi.write(data)
    CS.write_digital(1)


def init_tft():
    RST.write_digital(0)
    sleep(50)
    RST.write_digital(1)
    sleep(120)
    command(0x01)
    sleep(150)
    command(0x11)
    sleep(150)
    command(0x3A, b'\x05')
    command(0x36, b'\x00')
    command(0x13)
    sleep(20)
    command(0x29)
    sleep(100)


def window(x, y, w, h):
    command(0x2A, bytes([0, x, 0, x + w - 1]))
    command(0x2B, bytes([0, y, 0, y + h - 1]))
    command(0x2C)


def pixel_bytes(color):
    return bytes([(color >> 8) & 255, color & 255])


def fill_rect(x, y, w, h, color):
    if w <= 0 or h <= 0:
        return
    row = pixel_bytes(color) * w
    window(x, y, w, h)
    CS.write_digital(0)
    DC.write_digital(1)
    for _ in range(h):
        spi.write(row)
    CS.write_digital(1)


def clear():
    fill_rect(0, 0, W, H, BLACK)


# Built-in 5x5 characters scaled to the TFT.
FONT = {}
for ch in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.- /:':
    try:
        glyph = Image(ch)
        rows = []
        for yy in range(5):
            mask = 0
            for xx in range(5):
                if glyph.get_pixel(xx, yy):
                    mask |= 1 << (4 - xx)
            rows.append(mask)
        FONT[ch] = rows
    except Exception:
        FONT[ch] = [0] * 5


def draw_text_box(x, y, width, message, scale=1,
                  fg=WHITE, bg=BLACK, align='center'):
    message = str(message).upper()
    while scale > 1 and len(message) * 6 * scale > width:
        scale -= 1
    text_width = len(message) * 6 * scale
    if align == 'left':
        pad = 0
    elif align == 'right':
        pad = max(0, width - text_width)
    else:
        pad = max(0, (width - text_width) // 2)
    foreground = pixel_bytes(fg)
    background = pixel_bytes(bg)
    window(x, y, width, 5 * scale)
    CS.write_digital(0)
    DC.write_digital(1)
    for py in range(5 * scale):
        gy = py // scale
        parts = [background * pad]
        for ch in message:
            mask = FONT.get(ch, [0] * 5)[gy]
            for gx in range(5):
                parts.append((foreground if mask & (1 << (4-gx))
                              else background) * scale)
            parts.append(background * scale)
        line = b''.join(parts)
        if len(line) < width * 2:
            line += background * ((width * 2 - len(line)) // 2)
        spi.write(line[:width * 2])
    CS.write_digital(1)


def draw_text(message, y, scale=1, fg=WHITE, bg=BLACK):
    draw_text_box(0, y, W, message, scale, fg, bg)


def read_temperature_c():
    total = 0
    for _ in range(16):
        total += NTC.read_analog()
        sleep(2)
    adc = total / 16.0
    if adc < 2 or adc > 1021:
        return None
    resistance = R_FIXED * (1023.0 - adc) / adc
    inv_k = 1.0/T25 + math.log(resistance/R25)/BETA
    return 1.0/inv_k - 273.15


def formatted_temperature(c):
    if fahrenheit:
        return '%.1fF' % (c*1.8 + 32.0)
    return '%.1fC' % c


def band_color(c):
    if c < 18: return BLUE
    if c < 23: return CYAN
    if c < 28: return GREEN
    if c < 33: return YELLOW
    if c < 38: return ORANGE
    return RED


# 256 levels made by RGB interpolation between eight stops.
STOPS = ((38, 27, 146), (8, 124, 255),
         (0, 213, 238), (0, 198, 107),
         (255, 233, 44), (255, 134, 28),
         (237, 32, 53), (255, 184, 226))


def rgb565(r, g, b):
    return ((r & 248) << 8) | ((g & 252) << 3) | (b >> 3)


def make_palette():
    result = []
    for i in range(256):
        pos = i * 7
        segment = min(6, pos // 255)
        fraction = pos - segment * 255
        a = STOPS[segment]
        b = STOPS[segment + 1]
        red = (a[0]*(255-fraction)+b[0]*fraction+127)//255
        green = (a[1]*(255-fraction)+b[1]*fraction+127)//255
        blue = (a[2]*(255-fraction)+b[2]*fraction+127)//255
        result.append(rgb565(red, green, blue))
    return result


PALETTE = make_palette()


def palette_index(c, maximum):
    if c <= 0: return 0
    if c >= maximum: return 255
    return int(c * 255 / maximum + 0.5)


def draw_changing_number(c, fg=WHITE, bg=BLACK, y=28):
    global last_number
    value = formatted_temperature(c)
    if value != last_number:
        # Only the 20-pixel high number strip changes.
        fill_rect(0, y, W, 23, bg)
        draw_text(value, y+1, 4, fg, bg)
        last_number = value


# ----------------------------------------------------------
# MODE 1: THERMAL SPECTRUM
# Static titles, ticks, scale and bar border drawn once.
# 0..212F maps to -17.78..100C.
# Each reading changes only newly-filled/emptied bar rows
# plus the little external position marker and number.
# ----------------------------------------------------------
BAR_X, BAR_Y, BAR_W, BAR_H = 50, 58, 28, 82
INNER_X, INNER_Y = BAR_X+2, BAR_Y+2
INNER_W, INNER_H = BAR_W-4, BAR_H-4
old_fill = 0
old_marker_y = -1


def fraction_on_scale(c):
    # True 0..212F scale, equivalent to -17.78..100C.
    f = c*1.8+32.0
    return max(0.0, min(1.0, f/212.0))


def marker_y(c):
    return INNER_Y + int((1.0-fraction_on_scale(c))*(INNER_H-1)+0.5)


def draw_scale():
    # Labels are static until the user changes C/F.
    if fahrenheit:
        labels = ((100, '212'), (60, '140'), (37, '99'),
                  (22, '72'), (0, '32'), (-17.7778, '0'))
        unit = 'F'
    else:
        labels = ((100, '100'), (60, '60'), (37, '37'),
                  (22, '22'), (0, '0'), (-17.7778, '-18'))
        unit = 'C'
    draw_text_box(0, 51, 38, unit, 1, YELLOW)
    for t, name in labels:
        yy = marker_y(t)
        fill_rect(BAR_X-5, yy, 5, 1, WHITE)
        draw_text_box(0, max(51, min(137, yy-2)),
                      38, name, 1, WHITE, BLACK, 'right')


def init_spectrum():
    global old_fill, old_marker_y
    fill_rect(0, 23, W, 123, BLACK)
    fill_rect(BAR_X, BAR_Y, BAR_W, BAR_H, WHITE)
    fill_rect(INNER_X, INNER_Y, INNER_W, INNER_H, BLACK)
    draw_scale()
    draw_text_box(88, 57, 40, 'BOIL', 1, ORANGE, BLACK, 'left')
    draw_text_box(88, 88, 40, 'BODY', 1, WHITE, BLACK, 'left')
    draw_text_box(88, 104, 40, 'ROOM', 1, CYAN, BLACK, 'left')
    draw_text_box(88, 124, 40, 'ICE', 1, BLUE, BLACK, 'left')
    old_fill = 0
    old_marker_y = -1


def update_bar(c):
    global old_fill, old_marker_y
    new_fill = int(fraction_on_scale(c)*INNER_H + 0.5)
    if new_fill != old_fill:
        # A single continuous SPI window for only changed rows.
        first = INNER_H-max(old_fill, new_fill)
        count = abs(new_fill-old_fill)
        window(INNER_X, INNER_Y+first, INNER_W, count)
        CS.write_digital(0)
        DC.write_digital(1)
        for row in range(first, first+count):
            if row >= INNER_H-new_fill:
                # The color of each row is fixed on the 0-100C scale.
                scale_fraction = (INNER_H-1-row)/(INNER_H-1)
                color = PALETTE[int(scale_fraction*255+0.5)]
            else:
                color = BLACK
            spi.write(pixel_bytes(color)*INNER_W)
        CS.write_digital(1)
        old_fill = new_fill

    yy = marker_y(c)
    if yy != old_marker_y:
        # External indicator never overwrites the colored bar.
        if old_marker_y >= 0:
            fill_rect(80, old_marker_y, 5, 2, BLACK)
        fill_rect(80, yy, 5, 2, WHITE)
        old_marker_y = yy


def update_spectrum(c):
    draw_changing_number(c)
    update_bar(c)


# ----------------------------------------------------------
# MODE 2: HEAT DETECTIVE
# An oscilloscope-style time sweep: one column per second.
# Grid/axes remain, with old column erased when reused.
# ----------------------------------------------------------
GRAPH_X, GRAPH_Y, GRAPH_W, GRAPH_H = 8, 59, 112, 79
sweep_pos = 0
previous_y = None


def graph_y(c):
    val = max(0.0, min(1.0, (c-10.0)/35.0))
    return 137-int(val*78)


def init_graph():
    global sweep_pos, previous_y
    fill_rect(0, 23, W, 123, BLACK)
    fill_rect(GRAPH_X-1, GRAPH_Y, 1, GRAPH_H, GREY)
    fill_rect(GRAPH_X, 137, GRAPH_W, 1, GREY)
    sweep_pos = 0
    previous_y = None


def add_graph_point(c):
    global sweep_pos, previous_y
    x = GRAPH_X+sweep_pos
    y = graph_y(c)
    # Erase ONLY this column (and restore its axes/grid pixel).
    fill_rect(x, GRAPH_Y, 1, GRAPH_H, BLACK)
    for gy in (59, 98, 137):
        fill_rect(x, gy, 1, 1, DARK)
    # Connect adjacent samples within the current sweep.
    if previous_y is not None and sweep_pos > 0:
        lo = min(previous_y, y)
        hi = max(previous_y, y)
        fill_rect(x, lo, 1, hi-lo+1, band_color(c))
    else:
        fill_rect(x, y, 1, 2, band_color(c))
    sweep_pos += 1
    if sweep_pos >= GRAPH_W:
        sweep_pos = 0
        previous_y = None
    else:
        previous_y = y


# ----------------------------------------------------------
# MODE 3: TEMPERATURE CHAMELEON
# Full background only changes when its color index changes.
# When only the digits change, update just their own strip.
# Right-hand gradient stays in place.
# ----------------------------------------------------------
last_chameleon_level = -1
last_chameleon_number = None


def chameleon_text_color(level):
    # Keep white on dark colors and black on the rest.
    if level < 45: return WHITE
    return BLACK


def init_chameleon():
    global last_chameleon_level, last_chameleon_number
    last_chameleon_level = -1
    last_chameleon_number = None


def draw_chameleon_scale(level):
    window(119, 23, 9, 123)
    CS.write_digital(0)
    DC.write_digital(1)
    for row in range(123):
        idx = 255-row*255//122
        spi.write(pixel_bytes(PALETTE[idx])*9)
    CS.write_digital(1)
    yy = max(23, min(143, 23+(255-level)*122//255))
    fill_rect(114, yy, 5, 2, WHITE)


def update_chameleon(c):
    global last_chameleon_level, last_chameleon_number
    level = palette_index(c, 60.0)
    value = formatted_temperature(c)
    color = PALETTE[level]
    fg = chameleon_text_color(level)
    if level != last_chameleon_level:
        # Solid background must change when the palette index changes.
        fill_rect(0, 23, W, 123, color)
        draw_text('TOUCH SENSOR', 118, 1, fg, color)
        draw_chameleon_scale(level)
        last_chameleon_number = None
        last_chameleon_level = level
    if value != last_chameleon_number:
        # Preserve the fixed spectrum and update the text area only.
        fill_rect(0, 63, 114, 24, color)
        draw_text_box(0, 64, 114, value, 3, fg, color)
        last_chameleon_number = value


# ----------------------------------------------------------
# USER INTERFACE / MAIN LOOP
# ----------------------------------------------------------
mode = 0
fahrenheit = False
smoothed = None
last_number = None
last_sample = running_time()
last_graph = running_time()
error_displayed = False


def draw_interface():
    global last_number
    clear()
    fill_rect(0, 0, W, 23, NAVY)
    titles = ('THERMAL SPECTRUM', 'HEAT DETECTIVE', 'CHAMELEON')
    draw_text(titles[mode], 8, 1, WHITE, NAVY)
    fill_rect(0, 146, W, 14, NAVY)
    draw_text('A MODE B C/F', 150, 1, WHITE, NAVY)
    last_number = None
    if mode == 0:
        init_spectrum()
    elif mode == 1:
        init_graph()
    else:
        init_chameleon()


init_tft()
draw_interface()

while True:
    now = running_time()
    if button_a.was_pressed():
        mode = (mode+1)%3
        draw_interface()
        error_displayed = False
        # Draw the new mode on the next reading.
        last_sample = now-500

    if button_b.was_pressed():
        fahrenheit = not fahrenheit
        last_number = None
        last_chameleon_number = None
        if mode == 0:
            # Labels only; keep filled bar intact.
            fill_rect(0, 50, 43, 92, BLACK)
            draw_scale()
        last_sample = now-500

    now = running_time()
    if now-last_sample >= 500:
        last_sample = now
        reading = read_temperature_c()
        if reading is None:
            smoothed = None
            if not error_displayed:
                draw_interface()
                draw_text('CHECK SENSOR', 65, 1, YELLOW)
                error_displayed = True
        else:
            if error_displayed:
                draw_interface()
                error_displayed = False
            if smoothed is None:
                smoothed = reading
            else:
                smoothed = 0.65*smoothed+0.35*reading
            if mode == 0:
                update_spectrum(smoothed)
            elif mode == 1:
                draw_changing_number(smoothed, y=30)
                if now-last_graph >= 1000:
                    add_graph_point(smoothed)
                    last_graph = now
            else:
                update_chameleon(smoothed)
    sleep(20)

What's Going On?

How the code works: Scale labels, border, and captions are drawn once. Each new measurement redraws only changed temperature digits, newly filled or emptied bar rows, and the small marker. The color strip is drawn using 256 interpolated palette levels, though the TFT has fewer vertical pixels than palette levels.

Things to Try

Experiment: Prepare five cups: ice water, cold tap water, room-temperature water, lukewarm water, and comfortably hot tap water. Start in room-temperature water, then immerse only the waterproof stainless-steel tip in the ice water and wait for the reading to stabilize. Work through the remaining cups, moving from cool to warm. Watch the bar rise, its colors appear, and the indicator move. Reverse the order to see the bar fall. Check against a separate thermometer when available.

Make It Your Own

Record: Write down the temperature reading, bar height, and appearance at each cup. Does ice water read near 32°F even though the scale begins at 0°F? Does switching Button B between °F and °C change the bar height? Explain why it should not.

4.2 Heat Detective — Follow the Temperature Curve

Make It Happen

Goal: Observe how fast objects warm and cool. Press A once to enter Heat Detective. The display records approximately one reading per second in an oscilloscope-style sweep. Old data remains visible until the graph cursor returns to its column.

What's Going On?

Discuss: Why does the reading take time to settle? How are temperature and rate of temperature change different? What does a steep graph indicate? The graph's vertical working range is approximately 10–45°C; readings outside that window are clipped, even though the numeric temperature can show a larger range.

How the code works: Only the changing digits and one graph column are refreshed. No complete graph repaint is needed for every sample.

Things to Try

Experiment: Let the probe rest in room air. Immerse the stainless tip in comfortably warm water for 15–20 seconds, then transfer it to cool water. Observe the graph rising, leveling off, and falling. Try ice water and compare the response. Keep all wiring and connectors dry.

Make It Your Own

Design a cooling-time alarm. How might a portable thermometer warn you when a sample reaches your chosen temperature? Sketch the message before changing code.

4.3 Temperature Chameleon — Color as a Sensor Reading

Make It Happen

Goal: Turn a temperature measurement into a full-screen color display. From the first mode, press A twice to enter Chameleon. The entire background changes through 256 smoothly interpolated color levels as temperature changes. A fixed spectrum at the right shows the palette, with a white indicator for the current value.

What's Going On?

Important range distinction: Chameleon maps its 256 levels across 0–60°C (32–140°F) for more dramatic classroom color changes; the Thermal Spectrum thermometer maps height across 0–212°F. Temperatures beyond the Chameleon color range use the endpoint colors. Colors come from software, not from light emitted by the probe.

Things to Try

Experiment: Immerse the waterproof probe tip in the same ice, cool, room-temperature, warm, and hot-tap-water samples. Wait for each sample to stabilize. Observe how even small changes can shift the background color. Compare these colors with the bar in Thermal Spectrum, and repeat while pressing B to change temperature units.

Chameleon Temperature Spectrum


0°C / 32°F20°C40°C60°C / 140°F

This spectrum represents the 256-level RGB565 palette implemented in v1.8. Adjacent palette levels may look alike due to color quantization.

Make It Your Own

Investigate: Which color is associated with room temperature? Can you produce a slow color change? Design a new gradient by modifying the eight RGB stop values in the code.

What's Going On?

A thermistor is a resistor whose resistance changes with temperature. An NTC (negative temperature coefficient) thermistor has lower resistance when warmer. Along with a fixed 10 kΩ resistor, it forms a voltage divider read by the micro:bit's analog pin P2. Python converts voltage to resistance and uses the thermistor Beta equation to estimate temperature. The approved 10 kΩ/B3950 probe uses nominal resistance and Beta values without a manual calibration offset.

Engineering & AI Challenge

How could you detect the moment the sensor starts cooling? Ask AI to add a WARMING / COOLING / STABLE label while preserving the tested TFT pin assignments, divider orientation, thermistor calculations, and button controls. Test one change at a time. As an advanced challenge, compare cooling curves in still air and moving air.

5. Motion & Gravity — Make Movement Visible 

What if you could see gravity? Your micro:bit has a three-axis accelerometer. By combining it with the kit's color TFT, you can turn an unseen force into a moving 3D vector—and build a useful digital level with no extra components.

These three experiments use your already-assembled Invisible World kit: micro:bit, I/O Edge and 128 × 160 TFT. No additional sensor or wiring changes are required.

Open the micro:bit Python Editor. Use one complete MicroPython program at a time.

5.1 3D Gravity — Your invisible force has a direction

The accelerometer detects acceleration along the micro:bit's X, Y and Z axes. When you hold the board still, it also responds to Earth's gravity. Tilting the board changes how this acceleration is divided among the axes.

Simulation of the 3D Gravity TFT display, showing wireframe cube and vector
Illustrative TFT simulation; not a photograph of the hardware.

Make It Happen

  1. Load Motion & Gravity 3D v0.4 into the micro:bit Python Editor.
  2. Hold the board flat and look at the yellow vector inside the cube.
  3. Rotate the board slowly through different orientations. What changes? Which direction seems to represent gravity?
  4. Try holding one axis steady while rotating the other two.
💻  View MicroPython Program — 5.1 Motion & Gravity 3D v0.4  ▾ Expand / collapse

# Invisible World - Motion & Gravity 3D v0.4
# Experimental MicroPython for micro:bit + ST7735 128x160 TFT
# Existing TFT wiring: SCL P13, SDA P15, CS P16, DC P8, RES P12
# A = next visualization. B = zero the bubble level.
# Only 8x8 blocks whose pixels changed are transmitted to TFT.
from microbit import *

display.off()
CS, DC, RST = pin16, pin8, pin12
spi.init(baudrate=4000000, bits=8, mode=0,
         sclk=pin13, mosi=pin15, miso=pin14)

def cmd(n, data=None):
    CS.write_digital(0)
    DC.write_digital(0)
    spi.write(bytes([n]))
    if data is not None:
        DC.write_digital(1)
        spi.write(data)
    CS.write_digital(1)

def window(x, y, w, h):
    cmd(0x2A, bytes([0,x,0,x+w-1]))
    cmd(0x2B, bytes([0,y,0,y+h-1]))
    cmd(0x2C)

def solid(x, y, w, h, color):
    window(x, y, w, h)
    row = bytes([color >> 8, color & 255]) * w
    CS.write_digital(0)
    DC.write_digital(1)
    for _ in range(h):
        spi.write(row)
    CS.write_digital(1)

PAL = (0x0000, 0x18E3, 0x39E7, 0xFFFF, 0xF800,
       0x07E0, 0x041F, 0xFFE0, 0x07FF, 0xFD20)
BLACK, DIM, GRID, WHITE, RED, GREEN, BLUE, YELLOW, CYAN, ORANGE = range(10)
S = 96
N = S*S
old = bytearray(N)
new = bytearray(N)
tile = bytearray(128)

def px(x, y, c):
    if 0 <= x < S and 0 <= y < S:
        new[y*S+x] = c

def line(x0, y0, x1, y1, c):
    x0,y0,x1,y1 = int(x0),int(y0),int(x1),int(y1)
    dx, dy = abs(x1-x0), abs(y1-y0)
    sx = 1 if x0<x1 else -1
    sy = 1 if y0<y1 else -1
    err = dx-dy
    while True:
        px(x0,y0,c)
        px(x0+1,y0,c)
        px(x0,y0+1,c)
        if x0==x1 and y0==y1:
            break
        twice=err*2
        if twice > -dy:
            err -= dy
            x0 += sx
        if twice < dx:
            err += dx
            y0 += sy

def circle(cx,cy,r,c):
    x,y,err=r,0,1-r
    while x>=y:
        px(cx+x,cy+y,c); px(cx+y,cy+x,c)
        px(cx-y,cy+x,c); px(cx-x,cy+y,c)
        px(cx-x,cy-y,c); px(cx-y,cy-x,c)
        px(cx+y,cy-x,c); px(cx+x,cy-y,c)
        y+=1
        if err < 0:
            err += 2*y+1
        else:
            x-=1
            err += 2*(y-x)+1

def thick_circle(cx,cy,r,c):
    circle(cx,cy,r,c)
    circle(cx,cy,r+1,c)

def disc(cx,cy,r,c):
    for yy in range(-r,r+1):
        for xx in range(-r,r+1):
            if xx*xx+yy*yy <= r*r:
                px(cx+xx,cy+yy,c)

def begin():
    global new
    new = bytearray(N)

def flush():
    global old
    for ty in range(0,S,8):
        for tx in range(0,S,8):
            changed=False
            for dy in range(8):
                p=(ty+dy)*S+tx
                if old[p:p+8] != new[p:p+8]:
                    changed=True
                    break
            if not changed:
                continue
            k=0
            for dy in range(8):
                p=(ty+dy)*S+tx
                for ci in new[p:p+8]:
                    color=PAL[ci]
                    tile[k]=color>>8
                    tile[k+1]=color&255
                    k+=2
            window(16+tx, 32+ty, 8, 8)
            CS.write_digital(0)
            DC.write_digital(1)
            spi.write(tile)
            CS.write_digital(1)
    old = new

def project(x,y,z):
    return int(48+(x-z)*0.84), int(49+(x+z)*0.40-y*0.85)

def cube(x,y,z):
    for a in (-27,27):
        for b in (-27,27):
            p=project(-27,a,b); q=project(27,a,b)
            line(p[0],p[1],q[0],q[1],DIM)
            p=project(a,-27,b); q=project(a,27,b)
            line(p[0],p[1],q[0],q[1],DIM)
            p=project(a,b,-27); q=project(a,b,27)
            line(p[0],p[1],q[0],q[1],DIM)
    origin=project(0,0,0)
    for xx,yy,zz,color in ((31,0,0,RED),(0,31,0,GREEN),(0,0,31,BLUE)):
        p=project(xx,yy,zz)
        line(origin[0],origin[1],p[0],p[1],color)
        disc(p[0],p[1],2,color)
    xx=max(-30,min(30,x*30//1000))
    yy=max(-30,min(30,y*30//1000))
    zz=max(-30,min(30,z*30//1000))
    end=project(xx,yy,zz)
    line(origin[0],origin[1],end[0],end[1],YELLOW)
    disc(end[0],end[1],4,ORANGE)
    disc(end[0],end[1],2,WHITE)

def level(x,y,zero_x,zero_y):
    for radius in (18,32,45):
        thick_circle(48,48,radius,GRID)
    line(48,3,48,93,DIM)
    line(3,48,93,48,DIM)
    bx=max(10,min(86,48+(x-zero_x)*38//1000))
    by=max(10,min(86,48+(y-zero_y)*38//1000))
    disc(bx+3,by+4,7,DIM)
    disc(bx,by,7,BLUE)
    disc(bx-2,by-2,3,CYAN)
    px(bx-3,by-3,WHITE)

def motion(power,phase):
    line(48,0,48,95,DIM)
    line(0,48,95,48,DIM)
    for r in (14,28,42):
        circle(48,48,r,GRID)
    if power > 35:
        for i in range(3):
            radius=(phase+i*19)%46+2
            color=(ORANGE,YELLOW,CYAN)[i]
            thick_circle(48,48,radius,color)
    disc(48,48,4,WHITE if power>70 else BLUE)

CS.write_digital(1)
RST.write_digital(1)
sleep(10)
RST.write_digital(0)
sleep(20)
RST.write_digital(1)
sleep(120)
cmd(0x01); sleep(150)
cmd(0x11); sleep(150)
cmd(0x3A,b'\x05')
cmd(0x36,b'\x00')
cmd(0x13)
cmd(0x29); sleep(100)
solid(0,0,128,160,0x0000)

FONT = {
 ' ':(0,0,0,0,0), '3':(7,1,7,1,7), 'D':(6,5,5,5,6),
 'G':(7,4,5,5,7), 'R':(6,5,6,5,5), 'A':(2,5,7,5,5),
 'V':(5,5,5,5,2), 'I':(7,2,2,2,7), 'T':(7,2,2,2,2),
 'Y':(5,5,2,2,2), 'B':(6,5,6,5,6), 'U':(5,5,5,5,7),
 'L':(4,4,4,4,7), 'E':(7,4,6,4,7), 'O':(7,5,5,5,7),
 'M':(5,7,7,5,5), 'N':(5,7,7,7,5), 'S':(7,4,7,1,7),
 'C':(7,4,4,4,7), 'H':(5,5,7,5,5)
}
NAMES=('3D GRAVITY','BUBBLE LEVEL','MOTION RINGS')
def header(mode):
    buf=bytearray(128*14*2)
    color=COLORS[mode]
    for i,ch in enumerate(NAMES[mode]):
        glyph=FONT.get(ch,FONT[' '])
        for gy in range(5):
            for gx in range(3):
                if glyph[gy] & (4 >> gx):
                    for sy in range(2):
                        for sx in range(2):
                            x=4+i*10+gx*2+sx
                            y=gy*2+sy+2
                            k=2*(y*128+x)
                            buf[k]=color>>8
                            buf[k+1]=color&255
    window(0,16,128,14)
    CS.write_digital(0)
    DC.write_digital(1)
    spi.write(buf)
    CS.write_digital(1)

COLORS=(PAL[CYAN], PAL[GREEN], PAL[ORANGE])
mode=0
zero_x=0
zero_y=0
last=None
prev=accelerometer.get_values()
power=0
phase=0
last_tick=running_time()
header(mode)

while True:
    x,y,z=accelerometer.get_values()
    dx=abs(x-prev[0])+abs(y-prev[1])+abs(z-prev[2])
    prev=(x,y,z)
    power=max(dx,power*7//8)
    if button_a.was_pressed():
        mode=(mode+1)%3
        last=None
        header(mode)
    if button_b.was_pressed() and mode==1:
        zero_x,zero_y=x,y
        last=None
    t=running_time()
    if t-last_tick >= 85:
        signature=(x//25,y//25,z//25) if mode==0 else (
            ((x-zero_x)//18,(y-zero_y)//18) if mode==1 else power//35)
        if mode==2:
            phase=(phase+4)%46
        if signature!=last or (mode==2 and power>35):
            begin()
            if mode==0:
                cube(x,y,z)
            elif mode==1:
                level(x,y,zero_x,zero_y)
            else:
                motion(power,phase)
            flush()
            last=signature
        last_tick=t
    sleep(12)

What's Going On?

Engineering insight: The program projects a three-dimensional vector onto a two-dimensional display. The wireframe cube is a reference frame; it is not a physical cube around the sensor. A stationary accelerometer responds to gravity, but when you move or shake it, the reading also includes motion-related acceleration.

Things to Try

Try this: Can you identify X, Y and Z from the red, green and blue axes? Does the yellow vector respond differently if you rotate slowly versus shake quickly?

Make It Your Own

Sketch a clearer gravity-direction display with a different label or color. Keep the approved motion sensor readings and TFT wiring.

5.2 Digital Bubble Level — Build a useful instrument

A traditional bubble level uses a real air bubble floating in liquid. Our digital version senses tilt electronically and draws a bright yellow bubble on the TFT. It also allows you to set a reference angle.

Illustrative TFT digital bubble level with centered yellow bubble
Centered level · simulation
Illustrative TFT digital bubble level showing tilted yellow bubble
Tilted level · simulation

Make It Happen

  1. Load Digital Bubble Level v1.1 into the micro:bit Python Editor.
  2. Place the micro:bit on a stable, level surface.
  3. Press Button B to calibrate the center point.
  4. Gently tilt the board forward, backward and sideways, then return to level.
  5. Press B again while the board is slightly tilted. What does the bubble now consider its center?
💻  View MicroPython Program — 5.2 Digital Bubble Level v1.1  ▾ Expand / collapse

# Invisible World - Digital Bubble Level v1.1
# micro:bit and ST7735 128x160 TFT
# White title, larger yellow bubble, no decorative bars
# Button B: calibrate center
# Selective 8x8 screen updates
# Hardware-approved master
from microbit import *

display.off()
CS = pin16
DC = pin8
RST = pin12
spi.init(baudrate=4000000, bits=8, mode=0,
         sclk=pin13, mosi=pin15, miso=pin14)

def cmd(n, data=None):
    CS.write_digital(0)
    DC.write_digital(0)
    spi.write(bytes([n]))
    if data is not None:
        DC.write_digital(1)
        spi.write(data)
    CS.write_digital(1)

def window(x, y, w, h):
    cmd(0x2A, bytes([0,x,0,x+w-1]))
    cmd(0x2B, bytes([0,y,0,y+h-1]))
    cmd(0x2C)

def solid(x,y,w,h,color):
    window(x,y,w,h)
    row=bytes([color>>8,color&255])*w
    CS.write_digital(0)
    DC.write_digital(1)
    for _ in range(h):
        spi.write(row)
    CS.write_digital(1)

PAL = (0x0000,0x18E3,0x39E7,0xFFFF,0x041F,
       0x07FF,0xFFE0,0xFD20,0x2104)
BLACK,DIM,GRID,WHITE,BLUE,CYAN,YELLOW,ORANGE,SHADOW=range(9)
S=96
N=S*S
old=bytearray(N)
new=bytearray(N)
tile=bytearray(128)

def px(x,y,c):
    if 0<=x<S and 0<=y<S:
        new[y*S+x]=c

def line(x0,y0,x1,y1,c):
    x0,y0,x1,y1=int(x0),int(y0),int(x1),int(y1)
    dx=abs(x1-x0)
    dy=abs(y1-y0)
    sx=1 if x0<x1 else -1
    sy=1 if y0<y1 else -1
    err=dx-dy
    while True:
        px(x0,y0,c)
        px(x0+1,y0,c)
        px(x0,y0+1,c)
        if x0==x1 and y0==y1:
            break
        twice=2*err
        if twice>-dy:
            err-=dy
            x0+=sx
        if twice<dx:
            err+=dx
            y0+=sy

def circle(cx,cy,r,c):
    x,y,err=r,0,1-r
    while x>=y:
        px(cx+x,cy+y,c); px(cx+y,cy+x,c)
        px(cx-y,cy+x,c); px(cx-x,cy+y,c)
        px(cx-x,cy-y,c); px(cx-y,cy-x,c)
        px(cx+y,cy-x,c); px(cx+x,cy-y,c)
        y+=1
        if err<0:
            err+=2*y+1
        else:
            x-=1
            err+=2*(y-x)+1

def thick_circle(cx,cy,r,c):
    circle(cx,cy,r,c)
    circle(cx,cy,r+1,c)

def disc(cx,cy,r,c):
    for yy in range(-r,r+1):
        for xx in range(-r,r+1):
            if xx*xx+yy*yy<=r*r:
                px(cx+xx,cy+yy,c)

def begin():
    global new
    new=bytearray(N)

def flush():
    global old
    for ty in range(0,S,8):
        for tx in range(0,S,8):
            changed=False
            for dy in range(8):
                p=(ty+dy)*S+tx
                if old[p:p+8]!=new[p:p+8]:
                    changed=True
                    break
            if not changed:
                continue
            k=0
            for dy in range(8):
                p=(ty+dy)*S+tx
                for ci in new[p:p+8]:
                    color=PAL[ci]
                    tile[k]=color>>8
                    tile[k+1]=color&255
                    k+=2
            window(16+tx,32+ty,8,8)
            CS.write_digital(0)
            DC.write_digital(1)
            spi.write(tile)
            CS.write_digital(1)
    old=new

def draw_level(x,y,zero_x,zero_y):
    for radius in (18,32):
        thick_circle(48,48,radius,GRID)
    circle(48,48,45,GRID)
    line(48,4,48,92,DIM)
    line(4,48,92,48,DIM)
    bx=48+(x-zero_x)*38//1000
    by=48+(y-zero_y)*38//1000
    dx=bx-48
    dy=by-48
    distance2=dx*dx+dy*dy
    if distance2>34*34:
        distance=distance2**0.5
        bx=int(48+dx*34/distance)
        by=int(48+dy*34/distance)
    disc(bx+2,by+3,10,SHADOW)
    disc(bx,by,10,BLACK)
    disc(bx,by,9,ORANGE)
    disc(bx-1,by-1,7,YELLOW)
    disc(bx-3,by-4,3,WHITE)
    px(bx-4,by-5,WHITE)

CS.write_digital(1)
RST.write_digital(1)
sleep(10)
RST.write_digital(0)
sleep(20)
RST.write_digital(1)
sleep(120)
cmd(0x01)
sleep(150)
cmd(0x11)
sleep(150)
cmd(0x3A,b'\x05')
cmd(0x36,b'\x00')
cmd(0x13)
cmd(0x29)
sleep(100)
solid(0,0,128,160,0x0000)
FONT={' ':(0,0,0,0,0),'B':(6,5,6,5,6),
      'U':(5,5,5,5,7),'L':(4,4,4,4,7),
      'E':(7,4,6,4,7),'V':(5,5,5,5,2)}

def header():
    buf=bytearray(128*14*2)
    name='BUBBLE LEVEL'
    color=0xFFFF
    for i,ch in enumerate(name):
        glyph=FONT.get(ch,FONT[' '])
        for gy in range(5):
            for gx in range(3):
                if glyph[gy]&(4>>gx):
                    for sy in range(2):
                        for sx in range(2):
                            x=4+i*10+gx*2+sx
                            y=gy*2+sy+2
                            k=2*(y*128+x)
                            buf[k]=color>>8
                            buf[k+1]=color&255
    window(0,16,128,14)
    CS.write_digital(0)
    DC.write_digital(1)
    spi.write(buf)
    CS.write_digital(1)

header()
zero_x=0
zero_y=0
last=None
last_tick=running_time()
while True:
    x,y,z=accelerometer.get_values()
    if button_b.was_pressed():
        zero_x=x
        zero_y=y
        last=None
    t=running_time()
    if t-last_tick>=85:
        signature=((x-zero_x)//18,(y-zero_y)//18)
        if signature!=last:
            begin()
            draw_level(x,y,zero_x,zero_y)
            flush()
            last=signature
        last_tick=t
    sleep(12)

What's Going On?

Engineering insight: Calibration defines a relative reference. It does not prove the table is truly level. If you calibrate on a tilted surface, the display will still center at that angle.

Things to Try

Try this: Build a cardboard stand or test a bookshelf. Can you make repeated readings without changing the calibration?

Make It Your Own

Invent an easier-to-read level for checking a table or picture frame. What would you change about the bubble or target circles without changing Button B calibration?

Try It with AI! What if the bubble changed color when the surface was level? Share your Digital Bubble Level code with AI and ask for that one change, keeping Button B calibration and the TFT connections as they are.

5.3 Motion Rings — Watch Movement Spread

Make It Happen

Return to the complete Motion & Gravity 3D v0.4 program in 5.1 and flash it again. This is important: the separate Bubble Level v1.1 program in 5.2 has no Motion Rings mode.

  1. Press micro:bit A twice from the initial 3D GRAVITY screen to reach MOTION RINGS.
  2. Hold the micro:bit still, then gently move or tilt it. Watch how orange, yellow, and cyan rings appear and travel outward.
  3. Try a smooth movement and then a quicker movement. Can you make the rings appear again after holding still?

What's Going On?

The accelerometer senses changes in motion along three axes. This program compares recent readings and draws rings when their combined change is large enough. These are motion indicators, not literal waves moving through the air. Button A cycles among 3D GRAVITY, BUBBLE LEVEL, and MOTION RINGS.

Things to Try

Compare moving the board straight upward, rocking it gently, and rotating it. Which action creates the biggest change? Hold the board securely and never throw it.

Make It Your Own

Imagine turning the same motion detector into a shake alarm or a movement counter. What colors or patterns would help you see the difference between stillness and movement?

Uses the complete, previously tested v0.4 program from 5.1; no new code is required.

Why the TFT can respond quickly

These graphics use selective screen updates. The program compares small 8 × 8 pixel regions and sends only changed regions to the TFT, instead of repeatedly painting the entire display. Watch how the cube lines and bubble move without flashing the entire screen.

Think like an engineer

Describe one change you would make to the graphic or calibration. Ask AI to propose that single change, explain its reasoning, and keep the existing TFT connections and selective-update method. Test your modification against the approved programs before accepting it.

Approved program versions: Motion & Gravity 3D v0.4 (including its Motion Rings mode) and standalone Digital Bubble Level v1.1. Both are hardware-tested; the separate Motion Energy Visualizer is a possible future experiment.

6. Sound — Invisible Waves in Air

Make invisible sound activity visible with the micro:bit's built-in microphone and our color TFT. No extra sensor or wiring required.

6.1 Can You See Sound?
Simulated TFT sound visualizer, green yellow red bars and SOUND numeric reading
Illustrative TFT simulation using the tested rendering logic.

Make It Happen

Keep the TFT connected as in the Start Here wiring table. The micro:bit microphone is built in. Open the program below, copy it into the micro:bit Python Editor, and download it to the micro:bit. Speak, whistle, or clap: watch 16 colored bars slide from right to left. Press A to clear the bar history; B pauses or resumes.

💻  View & Copy MicroPython Program — 6.1 Sound Visualizer  ▾ Expand / collapse

from microbit import *

# Invisible World 6.1 - Sound Visualizer
# micro:bit / 128x160 ST7735 TFT
#
# A = Clear history
# B = Freeze / Resume
#
# LOUD_THRESHOLD can be adjusted.

W = 128
H = 160
GRAPH_H = 116

LOUD_THRESHOLD = 70
QUIET_THRESHOLD = 45

cs = pin16
dc = pin8
rst = pin12

cs.write_digital(1)
dc.write_digital(1)
rst.write_digital(1)

spi.init(baudrate=8000000, bits=8, mode=0,
         sclk=pin13, mosi=pin15, miso=pin14)

def command(c):
    cs.write_digital(0)
    dc.write_digital(0)
    spi.write(bytes([c]))
    cs.write_digital(1)

def data(b):
    cs.write_digital(0)
    dc.write_digital(1)
    spi.write(b)
    cs.write_digital(1)

def init_tft():
    rst.write_digital(0)
    sleep(100)
    rst.write_digital(1)
    sleep(150)
    command(0x01)
    sleep(150)
    command(0x11)
    sleep(150)
    command(0x3A)
    data(bytes([0x05]))
    command(0x36)
    data(bytes([0x00]))
    command(0x13)
    sleep(10)
    command(0x29)
    sleep(100)

def window(x0, y0, x1, y1):
    command(0x2A)
    data(bytes([0, x0, 0, x1]))
    command(0x2B)
    data(bytes([0, y0, 0, y1]))
    command(0x2C)

# RGB565 byte pairs

BLACK = (0, 0)
WHITE = (255, 255)
GREEN = (7, 224)
YELLOW = (255, 224)
RED = (248, 0)
GRAY = (49, 134)

FONT = {
    ' ': (0,0,0,0,0,0,0),
    '0': (14,17,19,21,25,17,14),
    '1': (4,12,4,4,4,4,14),
    '2': (14,17,1,2,4,8,31),
    '3': (30,1,1,14,1,1,30),
    '4': (2,6,10,18,31,2,2),
    '5': (31,16,30,1,1,17,14),
    '6': (6,8,16,30,17,17,14),
    '7': (31,1,2,4,8,8,8),
    '8': (14,17,17,14,17,17,14),
    '9': (14,17,17,15,1,2,12),
    'D': (30,17,17,17,17,17,30),
    'N': (17,25,21,19,17,17,17),
    'O': (14,17,17,17,17,17,14),
    'S': (15,16,16,14,1,1,30),
    'U': (17,17,17,17,17,17,14)
}

# Small display buffers
row = bytearray(W * 2)
column = bytearray(8 * GRAPH_H * 2)

# Sixteen bars and their last drawn heights
bars = [0] * 16
drawn = [-1] * 16

def clear_row():
    for i in range(len(row)):
        row[i] = 0

def pixel(x, color):
    if 0 <= x < W:
        k = x * 2
        row[k] = color[0]
        row[k+1] = color[1]

def text_row(txt, x0, yy, scale):
    gy = yy // scale

    if gy < 0 or gy >= 7:
        return

    for ci, ch in enumerate(txt):
        bits = FONT.get(ch, FONT[' '])[gy]

        for gx in range(5):
            if bits & (1 << (4-gx)):
                for sx in range(scale):
                    x = x0 + ci*6*scale + gx*scale + sx
                    pixel(x, WHITE)

def draw_text_area(y0, y1, txt, scale, text_y):
    window(0, y0, W-1, y1)

    cs.write_digital(0)
    dc.write_digital(1)

    x0 = (W - len(txt)*6*scale) // 2

    for y in range(y0, y1+1):
        clear_row()
        text_row(txt, x0, y-text_y, scale)
        spi.write(row)

    cs.write_digital(1)

def draw_column(index, height):
    # Update a vertical 8-pixel strip,
    # rather than repaint the entire screen.

    if height < 0:
        height = 0
    if height > GRAPH_H:
        height = GRAPH_H

    k = 0

    for y in range(GRAPH_H):
        active = y >= GRAPH_H-height

        if y < 35:
            color = RED
        elif y < 70:
            color = YELLOW
        else:
            color = GREEN

        grid = y in (29, 58, 87, 115)

        for x in range(8):
            hi = 0
            lo = 0

            # Thin reference lines
            if grid and x % 4 == 0:
                hi, lo = GRAY

            # Bar interior: leave a small gap
            if active and 1 <= x <= 6:
                hi, lo = color

            column[k] = hi
            column[k+1] = lo
            k += 2

    x0 = index * 8
    window(x0, 0, x0+7, GRAPH_H-1)

    cs.write_digital(0)
    dc.write_digital(1)
    spi.write(column)
    cs.write_digital(1)

def update_bars():
    for i in range(16):
        if bars[i] != drawn[i]:
            draw_column(i, bars[i])
            drawn[i] = bars[i]

def clear_history():
    for i in range(16):
        bars[i] = 0
        drawn[i] = -1

init_tft()
display.off()

# Set up microphone event detection
microphone.set_threshold(
    SoundEvent.LOUD, LOUD_THRESHOLD)
microphone.set_threshold(
    SoundEvent.QUIET, QUIET_THRESHOLD)

microphone.get_events()

# Draw fixed SOUND label once
draw_text_area(116, 137, "SOUND", 2, 119)
draw_text_area(138, 159, "0", 2, 142)

clear_history()
update_bars()

paused = False
last_a = False
last_b = False
last_number = -1
last_number_time = -300

while True:
    a = button_a.is_pressed()
    b = button_b.is_pressed()

    if a and not last_a:
        clear_history()
        microphone.get_events()

    if b and not last_b:
        paused = not paused
        microphone.get_events()

    last_a = a
    last_b = b

    if paused:
        sleep(20)
        continue

    # Sample current sound level
    level = 0

    for i in range(8):
        s = microphone.sound_level()
        if s > level:
            level = s
        sleep(3)

    # Detect a loud event, including events
    # occurring during TFT drawing.
    loud = microphone.was_event(
        SoundEvent.LOUD)

    height = (level * GRAPH_H) // 255

    if loud:
        # A clap produces a full-height
        # bar that remains in history.
        height = GRAPH_H

    # Shift history left
    for i in range(15):
        bars[i] = bars[i+1]

    bars[15] = height

    # Update only changed columns
    update_bars()

    # Update large number less frequently
    now = running_time()

    if now-last_number_time >= 250:
        draw_text_area(
            138, 159, str(level), 2, 142)
        last_number = level
        last_number_time = now

 

Or select the complete program in the gray box to copy it into the Python Editor.

What's Going On?

Sound waves make air vibrate. The micro:bit's microphone senses these changes and estimates a relative sound level from 0 to 255—not calibrated decibels. Each column records a recent reading. Short, loud events such as claps produce a full-height bar, showing an event was detected rather than a measured value of 255.

Things to Try

Clap once, speak softly, whistle, or play music nearby. Which sounds make the tallest bars? How does distance change the result? Freeze the scrolling display with B, then resume and clear it with A.

Make It Your Own

Experiment with the green/yellow/red color boundaries or adjust LOUD_THRESHOLD and QUIET_THRESHOLD for your room. If you choose to use AI, ask it to preserve the tested SPI wiring, column-update graphics, and button controls while changing only one feature.

6.2 Invisible Wave Machine — Sound Level & Duration
Software simulated TFT showing cyan sound graph with red spike, LEVEL 142, and 2450ms duration
Illustrative TFT simulation; numbers represent example readings, not recorded data.

Turn the TFT into a miniature sound-level recorder. A cyan trace sweeps across the display, loud events produce red spikes, and the large numbers show relative microphone level and sound-event duration in milliseconds.

Make It Happen

Use the same TFT wiring and built-in micro:bit microphone. Load the 6.2 Sound Level & Duration MicroPython program. Press A to clear the graph and measurements; press B to freeze and resume. The screen plots sound level, while the duration value is shown without a TIME label so longer readings fit.

💻  View & Copy MicroPython Program — 6.2 Sound Level & Duration  ▾ Expand / collapse

from microbit import *

# Invisible World 6.2 - Sound Level & Duration
# micro:bit / 128x160 ST7735 TFT
# A = Clear measurements
# B = Freeze / Resume

W = 128
GRAPH_H = 116
SOUND_THRESHOLD = 50
QUIET_GAP_MS = 120
LOUD_THRESHOLD = 70
QUIET_THRESHOLD = 45

cs = pin16
dc = pin8
rst = pin12
cs.write_digital(1)
dc.write_digital(1)
rst.write_digital(1)
spi.init(baudrate=8000000, bits=8, mode=0,
         sclk=pin13, mosi=pin15, miso=pin14)

def command(c):
    cs.write_digital(0)
    dc.write_digital(0)
    spi.write(bytes([c]))
    cs.write_digital(1)

def data(b):
    cs.write_digital(0)
    dc.write_digital(1)
    spi.write(b)
    cs.write_digital(1)

def init_tft():
    rst.write_digital(0)
    sleep(100)
    rst.write_digital(1)
    sleep(150)
    command(0x01)
    sleep(150)
    command(0x11)
    sleep(150)
    command(0x3A)
    data(bytes([0x05]))
    command(0x36)
    data(bytes([0x00]))
    command(0x13)
    sleep(10)
    command(0x29)
    sleep(100)

def window(x0, y0, x1, y1):
    command(0x2A)
    data(bytes([0, x0, 0, x1]))
    command(0x2B)
    data(bytes([0, y0, 0, y1]))
    command(0x2C)

BLACK = (0, 0)
WHITE = (255, 255)
CYAN = (7, 255)
YELLOW = (255, 224)
RED = (248, 0)
GRID = (24, 195)

FONT = {
    ' ': (0,0,0,0,0,0,0),
    '0': (14,17,19,21,25,17,14),
    '1': (4,12,4,4,4,4,14),
    '2': (14,17,1,2,4,8,31),
    '3': (30,1,1,14,1,1,30),
    '4': (2,6,10,18,31,2,2),
    '5': (31,16,30,1,1,17,14),
    '6': (6,8,16,30,17,17,14),
    '7': (31,1,2,4,8,8,8),
    '8': (14,17,17,14,17,17,14),
    '9': (14,17,17,15,1,2,12),
    'E': (31,16,16,30,16,16,31),
    'I': (14,4,4,4,4,4,14),
    'L': (16,16,16,16,16,16,31),
    'M': (17,27,21,21,17,17,17),
    'T': (31,4,4,4,4,4,4),
    'V': (17,17,17,17,17,10,4),
    'm': (0,0,26,21,21,21,21),
    's': (0,0,15,16,14,1,30)
}
row = bytearray(W * 2)
colbuf = bytearray(GRAPH_H * 4)

def clear_row():
    for i in range(len(row)):
        row[i] = 0

def pixel(x):
    if 0 <= x < W:
        k = x * 2
        row[k] = 255
        row[k+1] = 255

def text_row(txt, yy, scale):
    gy = yy // scale
    if gy < 0 or gy >= 7:
        return
    x0 = (W - len(txt)*6*scale)//2
    for ci, ch in enumerate(txt):
        bits = FONT.get(ch, FONT[' '])[gy]
        for gx in range(5):
            if bits & (1 << (4-gx)):
                for sx in range(scale):
                    pixel(x0 + ci*6*scale + gx*scale + sx)

def draw_text_area(y0, y1, txt):
    window(0, y0, W-1, y1)
    cs.write_digital(0)
    dc.write_digital(1)
    for y in range(y0, y1+1):
        clear_row()
        text_row(txt, y-y0-4, 2)
        spi.write(row)
    cs.write_digital(1)

def graph_column(index, old_y, new_y, color):
    if old_y < new_y:
        top, bottom = old_y, new_y
    else:
        top, bottom = new_y, old_y
    k = 0
    for y in range(GRAPH_H):
        c = BLACK
        if y in (28, 57, 86, 115):
            c = GRID
        if top <= y <= bottom:
            c = color
        for x in range(2):
            colbuf[k] = c[0]
            colbuf[k+1] = c[1]
            k += 2
    x0 = index*2
    window(x0, 0, x0+1, GRAPH_H-1)
    cs.write_digital(0)
    dc.write_digital(1)
    spi.write(colbuf)
    cs.write_digital(1)

def clear_graph():
    for index in range(64):
        graph_column(index, -1, -1, BLACK)

def reset_event():
    global active, start_ms, last_sound_ms
    global duration_ms, previous_y, position
    active = False
    start_ms = 0
    last_sound_ms = 0
    duration_ms = 0
    previous_y = 108
    position = 0
    microphone.get_events()
    clear_graph()

init_tft()
display.off()
microphone.set_threshold(SoundEvent.LOUD, LOUD_THRESHOLD)
microphone.set_threshold(SoundEvent.QUIET, QUIET_THRESHOLD)
microphone.get_events()
clear_graph()
draw_text_area(116, 137, "LEVEL 0")
draw_text_area(138, 159, "0ms")

active = False
start_ms = 0
last_sound_ms = 0
duration_ms = 0
position = 0
previous_y = 108
paused = False
pause_started = 0
last_a = False
last_b = False
last_text = -300

while True:
    a = button_a.is_pressed()
    b = button_b.is_pressed()
    if a and not last_a:
        reset_event()
        draw_text_area(116, 137, "LEVEL 0")
        draw_text_area(138, 159, "0ms")
    if b and not last_b:
        paused = not paused
        if paused:
            pause_started = running_time()
        else:
            elapsed = running_time()-pause_started
            if active:
                start_ms += elapsed
                last_sound_ms += elapsed
            microphone.get_events()
    last_a = a
    last_b = b
    if paused:
        sleep(20)
        continue

    level = 0
    for i in range(8):
        s = microphone.sound_level()
        if s > level:
            level = s
        sleep(3)
    now = running_time()
    loud = microphone.was_event(SoundEvent.LOUD)
    detected = (level >= SOUND_THRESHOLD) or loud

    if detected:
        if not active:
            active = True
            start_ms = now
            duration_ms = 0
        last_sound_ms = now
        duration_ms = now-start_ms
    elif active:
        if now-last_sound_ms >= QUIET_GAP_MS:
            duration_ms = last_sound_ms-start_ms
            active = False
        else:
            duration_ms = last_sound_ms-start_ms

    y = 108-(level*100)//255
    if loud:
        y = 6
        color = RED
    elif level > 140:
        color = YELLOW
    else:
        color = CYAN
    if position == 0:
        previous_y = y
    graph_column(position, previous_y, y, color)
    previous_y = y
    position = (position+1) % 64

    if now-last_text >= 250:
        draw_text_area(116, 137, "LEVEL "+str(level))
        if duration_ms > 9999:
            time_text = str(duration_ms//1000)+"s"
        else:
            time_text = str(duration_ms)+"ms"
        draw_text_area(138, 159, time_text)
        last_text = now

 

What's Going On?

LEVEL is a relative sound-intensity reading from 0–255, not calibrated decibels. The duration is an estimate of how long a detected sound event lasts. Sounds below the detection threshold for at least 120 ms end an event; the last measured duration stays on screen. The trace represents successive loudness readings, not raw audio waveform samples.

Things to Try

Compare one clap, a spoken word, a two-second whistle, and sustained music. Which produces the tallest trace? Which lasts the longest? What happens when you pause briefly while speaking?

Make It Your Own

Try changing SOUND_THRESHOLD (50) or QUIET_GAP_MS (120). Ask AI how those thresholds change the start and end of an event, then test with repeated sounds.

6.3 Disco Dance Floor
Simulated TFT disco floor with twenty colorful squares and DISCO SOUND 0 readout
Simulation from the tested display logic; sample sound reading.

Turn invisible sound into a miniature disco party! Twenty colored tiles respond to music, speech, and claps using the micro:bit's built-in microphone.

Make It Happen

Connect the TFT as shown in Start Here. Copy the approved program below into the micro:bit Python Editor and download to your micro:bit. Speak or play music to change the tiles faster. Clap to flash the two center tiles and change patterns. Button A changes the color palette; Button B freezes or resumes.

💻  View & Copy MicroPython Program — 6.3 Disco Dance Floor  ▾ Expand / collapse

from microbit import *
# Invisible World 6.3 - Disco Dance Floor
# micro:bit + ST7735 128x160 TFT
# A = Change color palette; B = Freeze / Resume

LOUD_THRESHOLD = 70
QUIET_THRESHOLD = 45
cs = pin16
dc = pin8
rst = pin12
cs.write_digital(1)
dc.write_digital(1)
rst.write_digital(1)
spi.init(baudrate=8000000, bits=8, mode=0,
         sclk=pin13, mosi=pin15, miso=pin14)

def command(c):
    cs.write_digital(0)
    dc.write_digital(0)
    spi.write(bytes([c]))
    cs.write_digital(1)

def data(b):
    cs.write_digital(0)
    dc.write_digital(1)
    spi.write(b)
    cs.write_digital(1)

def init_tft():
    rst.write_digital(0)
    sleep(100)
    rst.write_digital(1)
    sleep(150)
    command(0x01)
    sleep(150)
    command(0x11)
    sleep(150)
    command(0x3A)
    data(bytes([0x05]))
    command(0x36)
    data(bytes([0x00]))
    command(0x13)
    sleep(10)
    command(0x29)
    sleep(100)

def window(x0, y0, x1, y1):
    command(0x2A)
    data(bytes([0, x0, 0, x1]))
    command(0x2B)
    data(bytes([0, y0, 0, y1]))
    command(0x2C)

BLACK = (0, 0)
WHITE = (255, 255)
RED = (248, 0)
GREEN = (7, 224)
BLUE = (0, 31)
CYAN = (7, 255)
MAGENTA = (248, 31)
YELLOW = (255, 224)
ORANGE = (253, 0)
PURPLE = (120, 15)
PINK = (251, 146)
LIME = (135, 224)

PALETTES = [
    (CYAN, MAGENTA, BLUE, PINK, PURPLE, WHITE),
    (GREEN, LIME, YELLOW, ORANGE, CYAN, WHITE),
    (RED, ORANGE, YELLOW, MAGENTA, PURPLE, WHITE)
]

FONT = {
    ' ': (0,0,0,0,0,0,0),
    '0': (14,17,19,21,25,17,14),
    '1': (4,12,4,4,4,4,14),
    '2': (14,17,1,2,4,8,31),
    '3': (30,1,1,14,1,1,30),
    '4': (2,6,10,18,31,2,2),
    '5': (31,16,30,1,1,17,14),
    '6': (6,8,16,30,17,17,14),
    '7': (31,1,2,4,8,8,8),
    '8': (14,17,17,14,17,17,14),
    '9': (14,17,17,15,1,2,12),
    'C': (14,17,16,16,16,17,14),
    'D': (30,17,17,17,17,17,30),
    'I': (14,4,4,4,4,4,14),
    'O': (14,17,17,17,17,17,14),
    'S': (15,16,16,14,1,1,30),
    'U': (17,17,17,17,17,17,14),
    'N': (17,25,21,19,17,17,17)
}

textrow = bytearray(128 * 2)

def draw_text(y0, y1, txt, text_y):
    x0 = (128-len(txt)*12)//2
    window(0, y0, 127, y1)
    cs.write_digital(0)
    dc.write_digital(1)
    for y in range(y0, y1+1):
        for k in range(len(textrow)):
            textrow[k] = 0
        gy = (y-text_y)//2
        if 0 <= gy < 7:
            for ci, ch in enumerate(txt):
                bits = FONT.get(ch, FONT[' '])[gy]
                for gx in range(5):
                    if bits & (1 << (4-gx)):
                        x = x0+ci*12+gx*2
                        for sx in range(2):
                            xx = x+sx
                            if 0 <= xx < 128:
                                k = xx*2
                                textrow[k] = 255
                                textrow[k+1] = 255
        spi.write(textrow)
    cs.write_digital(1)

def fill_rect(x, y, w, h, color):
    window(x, y, x+w-1, y+h-1)
    line = bytes([color[0], color[1]]) * w
    cs.write_digital(0)
    dc.write_digital(1)
    for i in range(h):
        spi.write(line)
    cs.write_digital(1)

COLS = 4
ROWS = 5
TILE_W = 32
TILE_H = 23

def draw_tile(index, color):
    col = index % COLS
    row = index // COLS
    x = col*TILE_W+2
    y = row*TILE_H+2
    fill_rect(x, y, 28, 19, color)

shown = [-1]*20

def floor_color(index, phase, palette, level):
    colors = PALETTES[palette]
    row = index//4
    col = index%4
    pattern = (row+col+phase) % 6
    if level > 110:
        pattern = (pattern+col*2) % 6
    return pattern

def refresh_floor(phase, palette, level, count):
    global tile_cursor
    colors = PALETTES[palette]
    for j in range(count):
        i = tile_cursor
        tile_cursor = (tile_cursor+1) % 20
        choice = floor_color(i, phase, palette, level)
        if shown[i] != choice:
            draw_tile(i, colors[choice])
            shown[i] = choice

def flash_center():
    draw_tile(9, WHITE)
    draw_tile(10, WHITE)
    shown[9] = -1
    shown[10] = -1

init_tft()
display.off()
microphone.set_threshold(SoundEvent.LOUD, LOUD_THRESHOLD)
microphone.set_threshold(SoundEvent.QUIET, QUIET_THRESHOLD)
microphone.get_events()

fill_rect(0, 0, 128, 116, BLACK)
palette = 0
phase = 0
tile_cursor = 0
paused = False
level = 0
last_phase = running_time()
last_text = -300
last_clap = -1000

draw_text(116, 137, "DISCO", 119)
draw_text(138, 159, "SOUND 0", 142)
refresh_floor(phase, palette, 0, 20)

while True:
    if button_a.was_pressed():
        palette = (palette+1) % 3
        shown = [-1]*20
    if button_b.was_pressed():
        paused = not paused
        microphone.get_events()
    if paused:
        sleep(20)
        continue
    level = 0
    for i in range(6):
        s = microphone.sound_level()
        if s > level:
            level = s
        sleep(3)
    now = running_time()
    loud = microphone.was_event(SoundEvent.LOUD)
    if loud and now-last_clap > 250:
        phase += 3
        last_clap = now
        flash_center()
    if level > 120:
        interval = 90
    elif level > 65:
        interval = 160
    else:
        interval = 500
    if now-last_phase >= interval:
        phase += 1
        last_phase = now
    refresh_floor(phase, palette, level, 4)
    if now-last_text >= 300:
        draw_text(138, 159, "SOUND "+str(level), 142)
        last_text = now

 

What's Going On?

The microphone measures changing sound intensity. The program adjusts tile-update timing based on the level and uses a loud-sound event to trigger a clap flash. This is sound-reactive color animation, not analysis of musical notes or frequencies.

Things to Try

Play quiet music, speak, whistle, then clap. Compare how rapidly the grid changes. Try the three palettes with Button A. Which sound produces the most dramatic effect?

Make It Your Own

Experiment with the color palettes, the three update intervals (500, 160, and 90 ms), or the clap flash tiles. Ask AI to modify one design feature without changing the tested TFT wiring or microphone event detector.

6.4 Pocket Disco Ball
Simulated Pocket Disco Ball TFT with colorful mirrored tiles and side beams
Simulation based on the tested TFT drawing logic; illustrative sound level.

Make It Happen

Use the existing TFT wiring and the micro:bit built-in microphone. Download the MicroPython program below and run it. Watch the mirrored tiles change as if a disco ball were turning, while colorful side beams move. Music or speech speeds the animation; clapping makes the center flash. Button A selects one of three palettes and Button B freezes or resumes.

💻  View & Copy MicroPython Program — 6.4 Pocket Disco Ball  ▾ Expand / collapse

from microbit import *

# Invisible World 6.4 - Pocket Disco Ball
# micro:bit / 128x160 ST7735 TFT
# A = Change palette
# B = Freeze / Resume

cs = pin16
dc = pin8
rst = pin12
cs.write_digital(1)
dc.write_digital(1)
rst.write_digital(1)
spi.init(baudrate=8000000, bits=8, mode=0,
         sclk=pin13, mosi=pin15, miso=pin14)

def command(c):
    cs.write_digital(0)
    dc.write_digital(0)
    spi.write(bytes([c]))
    cs.write_digital(1)

def data(b):
    cs.write_digital(0)
    dc.write_digital(1)
    spi.write(b)
    cs.write_digital(1)

def init_tft():
    rst.write_digital(0)
    sleep(100)
    rst.write_digital(1)
    sleep(150)
    command(0x01)
    sleep(150)
    command(0x11)
    sleep(150)
    command(0x3A)
    data(bytes([0x05]))
    command(0x36)
    data(bytes([0x00]))
    command(0x13)
    sleep(10)
    command(0x29)
    sleep(100)

def window(x0, y0, x1, y1):
    command(0x2A)
    data(bytes([0, x0, 0, x1]))
    command(0x2B)
    data(bytes([0, y0, 0, y1]))
    command(0x2C)

BLACK = (0, 0)
WHITE = (255, 255)
CYAN = (7, 255)
BLUE = (0, 31)
MAGENTA = (248, 31)
PURPLE = (120, 15)
GREEN = (7, 224)
YELLOW = (255, 224)
ORANGE = (253, 0)
RED = (248, 0)

PALETTES = [
    (CYAN, BLUE, MAGENTA, PURPLE, WHITE, CYAN),
    (GREEN, CYAN, YELLOW, BLUE, WHITE, GREEN),
    (RED, ORANGE, YELLOW, MAGENTA, WHITE, RED)
]

FONT = {
    ' ': (0,0,0,0,0,0,0),
    '0': (14,17,19,21,25,17,14),
    '1': (4,12,4,4,4,4,14),
    '2': (14,17,1,2,4,8,31),
    '3': (30,1,1,14,1,1,30),
    '4': (2,6,10,18,31,2,2),
    '5': (31,16,30,1,1,17,14),
    '6': (6,8,16,30,17,17,14),
    '7': (31,1,2,4,8,8,8),
    '8': (14,17,17,14,17,17,14),
    '9': (14,17,17,15,1,2,12),
    'D': (30,17,17,17,17,17,30),
    'I': (14,4,4,4,4,4,14),
    'S': (15,16,16,14,1,1,30),
    'C': (14,17,16,16,16,17,14),
    'O': (14,17,17,17,17,17,14),
    'U': (17,17,17,17,17,17,14),
    'N': (17,25,21,19,17,17,17)
}

textrow = bytearray(256)

def draw_text(y0, y1, txt, text_y):
    x0 = (128-len(txt)*12)//2
    window(0, y0, 127, y1)
    cs.write_digital(0)
    dc.write_digital(1)
    for y in range(y0, y1+1):
        for i in range(256):
            textrow[i] = 0
        gy = (y-text_y)//2
        if 0 <= gy < 7:
            for ci, ch in enumerate(txt):
                bits = FONT.get(ch, FONT[' '])[gy]
                for gx in range(5):
                    if bits & (1 << (4-gx)):
                        x = x0+ci*12+gx*2
                        for sx in range(2):
                            xx = x+sx
                            if 0 <= xx < 128:
                                k = xx*2
                                textrow[k] = 255
                                textrow[k+1] = 255
        spi.write(textrow)
    cs.write_digital(1)

def fill_rect(x, y, w, h, color):
    window(x, y, x+w-1, y+h-1)
    line = bytes([color[0], color[1]]) * w
    cs.write_digital(0)
    dc.write_digital(1)
    for i in range(h):
        spi.write(line)
    cs.write_digital(1)

BALL_X = 28
BALL_Y = 20
TILE = 12
MASK = (
    0, 1, 1, 1, 1, 0,
    1, 1, 1, 1, 1, 1,
    1, 1, 1, 1, 1, 1,
    1, 1, 1, 1, 1, 1,
    1, 1, 1, 1, 1, 1,
    0, 1, 1, 1, 1, 0
)

shown = [-1]*36
tile_cursor = 0
phase = 0
palette = 0

def draw_mirror(i, color):
    row = i//6
    col = i%6
    x = BALL_X+col*TILE
    y = BALL_Y+row*TILE
    fill_rect(x+1, y+1, 10, 10, color)

def update_ball(count, flash):
    global tile_cursor
    colors = PALETTES[palette]
    for n in range(count):
        i = tile_cursor
        tile_cursor = (tile_cursor+1) % 36
        if not MASK[i]:
            continue
        row = i//6
        col = i%6
        choice = (col+row*2+phase) % 6
        if flash:
            choice = 4
        if shown[i] != choice:
            draw_mirror(i, colors[choice])
            shown[i] = choice

def draw_beams():
    colors = PALETTES[palette]
    for i in range(4):
        choice = (i+phase) % 6
        fill_rect(i*7, 4, 5, 108,
                  colors[choice])
        fill_rect(100+i*7, 4, 5, 108,
                  colors[(choice+3) % 6])

def flash_ball():
    for i in (14, 15, 20, 21):
        draw_mirror(i, WHITE)
        shown[i] = -1

init_tft()
display.off()
microphone.set_threshold(SoundEvent.LOUD, 70)
microphone.set_threshold(SoundEvent.QUIET, 45)
microphone.get_events()
fill_rect(0, 0, 128, 116, BLACK)
draw_text(116, 137, "DISCO", 119)
draw_text(138, 159, "SOUND 0", 142)
draw_beams()
update_ball(36, False)

paused = False
last_clap = -1000
last_phase = running_time()
last_text = -300
level = 0

while True:
    if button_a.was_pressed():
        palette = (palette+1) % 3
        shown = [-1]*36
        draw_beams()
    if button_b.was_pressed():
        paused = not paused
        microphone.get_events()
    if paused:
        sleep(20)
        continue
    level = 0
    for i in range(6):
        s = microphone.sound_level()
        if s > level:
            level = s
        sleep(3)
    now = running_time()
    loud = microphone.was_event(SoundEvent.LOUD)
    if loud and now-last_clap > 250:
        phase += 3
        last_clap = now
        flash_ball()
    if level > 120:
        interval = 100
    elif level > 65:
        interval = 180
    else:
        interval = 550
    if now-last_phase >= interval:
        phase += 1
        last_phase = now
        draw_beams()
    update_ball(6, False)
    if now-last_text >= 300:
        draw_text(138, 159, "SOUND "+str(level), 142)
        last_text = now

 

What's Going On?

The microphone senses changing sound intensity. A color-phase pattern makes a grid of mirrored tiles appear to rotate; the tiles do not physically move. The clap detector causes a brief white flash.

Things to Try

Compare the animation in silence, during normal speech, and while playing music. Try clapping and pressing Button A to compare palettes.

Make It Your Own

Change the palette colors or how often the mirrored tiles are updated. Ask AI to modify the animation while keeping the working microphone and TFT connections unchanged.

7. Moisture & Conductivity — Seeing Water's Electrical Effects
Invisible World engineering schematic Rev D, section E: moisture probe
Engineering schematic · Section E · Rev D

Use the Parallax Moisture Sensor Probe to discover how liquid and dissolved ions change electrical conduction. The probe responds to conductivity rather than directly measuring the percentage of water present.

Understanding the measurements: The numbers labeled ADC (0–1023) are raw, relative sensor readings, not calibrated conductivity measurements. They do not represent microsiemens per centimeter (µS/cm), and differences between two ADC values are also relative, not standard physical units. The 0–100% indication in Program 7.3 is a relative scale between the dry and wet reference samples, not an absolute percentage of water in soil. Probe immersion depth, temperature, dissolved salts, and sensor characteristics affect the readings. Compare samples using the same setup and conditions.

Change from the temperature experiment: Switch off USB and battery power, disconnect the thermistor's P2 junction and its divider circuit, and remove any other sensor output from P2. Keep the permanent TFT wiring connected. Do not leave the thermistor and moisture probe connected to P2 together.

Wiring: red → 3V; black → GND; yellow analog output → P2 through a 220 Ω series resistor. Power off before changing connections. Keep the electronics dry.

7.1 First Program — Serial Terminal & LED Test

Make It Happen

Run this first. The micro:bit averages ten analog readings, prints the raw 0–1023 value to the serial console, and displays a five-row LED bar graph. Compare air, dry soil, moist soil, and water. Record the raw values; these are not moisture percentages.

💻  View & Copy MicroPython Program — Select and copy the complete listing below

from microbit import *

# Invisible World 7.1 - Moisture Probe Test
# Probe AOUT -> 220 ohms -> P2

while True:
    total = 0
    for i in range(10):
        total += pin2.read_analog()
        sleep(10)

    moisture = total // 10
    bars = moisture * 5 // 1024
    display.clear()
    for row in range(bars):
        for col in range(5):
            display.set_pixel(col, 4 - row, 9)

    print("Moisture ADC:", moisture)
    sleep(300)

Open the micro:bit Python Editor, flash the code, and view the serial output. Observe whether the raw value increases or decreases when the probe gets wet.

What's Going On?

The micro:bit turns the probe's voltage into a number from 0 to 1023. Its LED rows give a simple picture of that raw reading; the numbers are not moisture percentages.

Things to Try

Compare air, dry soil, and damp soil. Keep the probe at the same depth for fair comparisons and record the raw values.

Make It Your Own

Sketch a clearer LED-bar label for someone measuring soil, without claiming the instrument is calibrated.

7.2 Live Moisture Visualization on TFT
Moisture TFT display for 7.2 with example ADC reading 612 and green bar
7.2 — raw moisture sensor reading · Simulated from the approved MicroPython display routines; example readings, not measured data.

Make It Happen

Keep the probe on P2 and the existing 128 × 160 ST7735 TFT wiring unchanged. Watch a large 0–1023 raw reading and colored horizontal bar while the serial console continues to print ADC readings. Colors are preliminary ADC ranges, not moisture classifications.

💻  View & Copy MicroPython Program — Select and copy the complete listing below

from microbit import *

# Invisible World 7.2 - Moisture TFT Meter
# Parallax Inc. - SKU 32890
# micro:bit with 128x160 ST7735 TFT
# Moisture probe AOUT -> 220 ohm -> P2
# TFT SCL=P13, SDA=P15, RES=P12, DC=P8, CS=P16
# TFT backlight: existing tested connection

W = 128
H = 160
cs = pin16
dc = pin8
rst = pin12

cs.write_digital(1)
dc.write_digital(1)
rst.write_digital(1)
spi.init(baudrate=8000000, bits=8, mode=0,
         sclk=pin13, mosi=pin15, miso=pin14)

def command(c):
    cs.write_digital(0)
    dc.write_digital(0)
    spi.write(bytes([c]))
    cs.write_digital(1)

def data(b):
    cs.write_digital(0)
    dc.write_digital(1)
    spi.write(b)
    cs.write_digital(1)

def init_tft():
    rst.write_digital(0)
    sleep(100)
    rst.write_digital(1)
    sleep(150)
    command(0x01)
    sleep(150)
    command(0x11)
    sleep(150)
    command(0x3A)
    data(bytes([0x05]))
    command(0x36)
    data(bytes([0x00]))
    command(0x13)
    sleep(10)
    command(0x29)
    sleep(100)

def window(x0, y0, x1, y1):
    command(0x2A)
    data(bytes([0, x0, 0, x1]))
    command(0x2B)
    data(bytes([0, y0, 0, y1]))
    command(0x2C)

BLACK = (0x00, 0x00)
WHITE = (0xFF, 0xFF)
CYAN = (0x07, 0xFF)
BLUE = (0x03, 0x1F)
GREEN = (0x07, 0xE0)
YELLOW = (0xFF, 0xE0)
GRAY = (0x42, 0x08)

def fill_rect(x, y, w, h, color):
    if w <= 0 or h <= 0:
        return
    window(x, y, x+w-1, y+h-1)
    line = bytes([color[0], color[1]]) * w
    cs.write_digital(0)
    dc.write_digital(1)
    for i in range(h):
        spi.write(line)
    cs.write_digital(1)

FONT = {
    ' ': (0,0,0,0,0,0,0),
    '0': (14,17,19,21,25,17,14),
    '1': (4,12,4,4,4,4,14),
    '2': (14,17,1,2,4,8,31),
    '3': (30,1,1,14,1,1,30),
    '4': (2,6,10,18,31,2,2),
    '5': (31,16,30,1,1,17,14),
    '6': (6,8,16,30,17,17,14),
    '7': (31,1,2,4,8,8,8),
    '8': (14,17,17,14,17,17,14),
    '9': (14,17,17,15,1,2,12),
    'A': (14,17,17,31,17,17,17),
    'C': (14,17,16,16,16,17,14),
    'D': (30,17,17,17,17,17,30),
    'I': (14,4,4,4,4,4,14),
    'M': (17,27,21,21,17,17,17),
    'O': (14,17,17,17,17,17,14),
    'P': (30,17,17,30,16,16,16),
    'R': (30,17,17,30,20,18,17),
    'S': (15,16,16,14,1,1,30),
    'T': (31,4,4,4,4,4,4),
    'U': (17,17,17,17,17,17,14),
    'W': (17,17,17,21,21,21,10),
}

def draw_text(x, y, text, scale, color):
    for ch in text:
        glyph = FONT.get(ch, FONT[' '])
        for gy in range(7):
            bits = glyph[gy]
            for gx in range(5):
                if bits & (1 << (4-gx)):
                    fill_rect(x+gx*scale, y+gy*scale,
                              scale, scale, color)
        x += 6*scale

def read_probe():
    total = 0
    for i in range(10):
        total += pin2.read_analog()
        sleep(10)
    return total // 10

def draw_meter(value):
    fill_rect(4, 48, 120, 36, BLACK)
    reading = str(value)
    width = len(reading)*24
    x = (W-width)//2
    draw_text(x, 51, reading, 4, WHITE)
    fill_rect(7, 99, 114, 24, GRAY)
    bar_width = value*110//1023
    if value < 340:
        color = YELLOW
    elif value < 680:
        color = GREEN
    else:
        color = CYAN
    fill_rect(9, 101, 110, 20, BLACK)
    fill_rect(9, 101, bar_width, 20, color)

init_tft()
fill_rect(0, 0, W, H, BLACK)
fill_rect(0, 0, W, 5, BLUE)
draw_text(13, 15, "MOISTURE", 2, CYAN)
draw_text(43, 88, "ADC", 1, WHITE)
draw_text(9, 133, "0", 1, WHITE)
draw_text(97, 133, "1023", 1, WHITE)

last_value = -1
while True:
    value = read_probe()
    if value != last_value:
        draw_meter(value)
        last_value = value
    print("Moisture ADC:", value)
    sleep(350)

What's Going On?

The TFT bar shows the raw electrical reading. Its color bands mark low, medium, and high ADC values, not automatically dry, damp, or wet soil.

Things to Try

Measure the same probe in two soil samples and compare the numbers. Do they rise or fall as conditions change?

Make It Your Own

Design a new bar graph label that tells users the value is a raw ADC measurement rather than a calibrated moisture percentage.

7.3 Calibrated Moisture Meter
Moisture TFT display for 7.3 with example 65 percent calibrated response
7.3 — relative moisture after setting two references · Simulated from the approved MicroPython display routines; example readings, not measured data.

Make It Happen

Place the probe in a dry reference and press A. Place it in a wet reference and press B. The TFT then displays a 0–100% relative reading based on your two references; raw ADC data remain in the serial terminal. A calibration range smaller than 20 ADC counts is rejected. Conductivity also depends on dissolved salts and soil composition, so this is not an absolute water-content percentage.

What's Going On?

Important — calibration is stored in RAM only. The dry and wet reference values are not saved permanently. Every time the micro:bit is reset, loses power, or receives a new program, both calibration points are cleared. Press A in dry material and B in wet material again before interpreting the percentage. Until both references are set, the TFT displays raw ADC readings instead.

💻  View & Copy MicroPython Program — Select and copy the complete listing below

from microbit import *

# Invisible World 7.3 - Calibrated Moisture
# Parallax Inc. - SKU 32890
# Probe analog output -> P2 via 220 ohms
# TFT: SCL=P13 SDA=P15 RES=P12 DC=P8 CS=P16
# Calibration is stored ONLY in RAM (resets on restart).

W, H = 128, 160
cs, dc, rst = pin16, pin8, pin12
spi.init(baudrate=8000000, bits=8, mode=0,
         sclk=pin13, mosi=pin15, miso=pin14)

def command(n):
    cs.write_digital(0)
    dc.write_digital(0)
    spi.write(bytes([n]))
    cs.write_digital(1)

def data(b):
    cs.write_digital(0)
    dc.write_digital(1)
    spi.write(b)
    cs.write_digital(1)

def init_tft():
    cs.write_digital(1)
    dc.write_digital(1)
    rst.write_digital(0)
    sleep(100)
    rst.write_digital(1)
    sleep(150)
    command(0x01)
    sleep(150)
    command(0x11)
    sleep(150)
    command(0x3A)
    data(bytes([0x05]))
    command(0x36)
    data(bytes([0x00]))
    command(0x13)
    sleep(10)
    command(0x29)
    sleep(100)

def window(x0, y0, x1, y1):
    command(0x2A)
    data(bytes([0, x0, 0, x1]))
    command(0x2B)
    data(bytes([0, y0, 0, y1]))
    command(0x2C)

BLACK = (0, 0)
WHITE = (255, 255)
BLUE = (3, 31)
CYAN = (7, 255)
GREEN = (7, 224)
YELLOW = (255, 224)
GRAY = (66, 8)

def fill_rect(x, y, w, h, color):
    if w <= 0 or h <= 0:
        return
    window(x, y, x+w-1, y+h-1)
    line = bytes(color)*w
    cs.write_digital(0)
    dc.write_digital(1)
    for i in range(h):
        spi.write(line)
    cs.write_digital(1)

FONT = {
    ' ': (0,0,0,0,0,0,0),
    '0': (14,17,19,21,25,17,14),
    '1': (4,12,4,4,4,4,14),
    '2': (14,17,1,2,4,8,31),
    '3': (30,1,1,14,1,1,30),
    '4': (2,6,10,18,31,2,2),
    '5': (31,16,30,1,1,17,14),
    '6': (6,8,16,30,17,17,14),
    '7': (31,1,2,4,8,8,8),
    '8': (14,17,17,14,17,17,14),
    '9': (14,17,17,15,1,2,12),
    '%': (17,2,4,8,17,0,0),
    'A': (14,17,17,31,17,17,17),
    'B': (30,17,17,30,17,17,30),
    'C': (14,17,16,16,16,17,14),
    'D': (30,17,17,17,17,17,30),
    'E': (31,16,16,30,16,16,31),
    'I': (14,4,4,4,4,4,14),
    'M': (17,27,21,21,17,17,17),
    'O': (14,17,17,17,17,17,14),
    'R': (30,17,17,30,20,18,17),
    'S': (15,16,16,14,1,1,30),
    'T': (31,4,4,4,4,4,4),
    'U': (17,17,17,17,17,17,14),
    'W': (17,17,17,21,21,21,10)
}

def draw_text(x, y, msg, scale, color):
    for ch in msg:
        glyph = FONT.get(ch, FONT[' '])
        for gy in range(7):
            bits = glyph[gy]
            for gx in range(5):
                if bits & (1 << (4-gx)):
                    fill_rect(x+gx*scale, y+gy*scale,
                              scale, scale, color)
        x += 6*scale

def read_probe():
    total = 0
    for i in range(10):
        total += pin2.read_analog()
        sleep(10)
    return total//10

# Calibration starts unset; dry and wet exist only in RAM
dry = None
wet = None

def calibrated_percent(value):
    if dry is None or wet is None:
        return None
    difference = wet-dry
    if abs(difference) < 20:
        return None
    percent = (value-dry)*100//difference
    if percent < 0:
        percent = 0
    if percent > 100:
        percent = 100
    return percent

def draw_meter(value, percent):
    fill_rect(0, 43, 128, 96, BLACK)
    if percent is None:
        number = str(value)
        scale = 3
        width = len(number)*6*scale
        draw_text((128-width)//2, 49,
                  number, scale, WHITE)
        draw_text(52, 78, "ADC", 1, CYAN)
        fill_rect(9, 105, 110, 20, GRAY)
        bar = value*106//1023
        fill_rect(11, 107, bar, 16, BLUE)
    else:
        number = str(percent)+"%"
        scale = 3
        width = len(number)*6*scale
        draw_text((128-width)//2, 49,
                  number, scale, WHITE)
        draw_text(37, 81, "ADC "+str(value),
                  1, CYAN)
        fill_rect(9, 105, 110, 20, GRAY)
        fill_rect(11, 107, 106, 16, BLACK)
        bar = percent*106//100
        if percent < 30:
            color = YELLOW
        elif percent < 70:
            color = GREEN
        else:
            color = CYAN
        fill_rect(11, 107, bar, 16, color)

def draw_calibration():
    fill_rect(0, 139, 128, 21, BLACK)
    a = "---" if dry is None else str(dry)
    b = "---" if wet is None else str(wet)
    draw_text(3, 145, "A "+a, 1, WHITE)
    draw_text(67, 145, "B "+b, 1, WHITE)

init_tft()
display.off()
fill_rect(0, 0, W, H, BLACK)
fill_rect(0, 0, W, 5, BLUE)
draw_text(13, 16, "MOISTURE", 2, CYAN)
draw_calibration()

while True:
    value = read_probe()
    if button_a.was_pressed():
        dry = value
        print("DRY reference:", dry)
        draw_calibration()
    if button_b.was_pressed():
        wet = value
        print("WET reference:", wet)
        draw_calibration()
    percent = calibrated_percent(value)
    draw_meter(value, percent)
    if percent is None:
        print("ADC:", value,
              "Dry:", dry, "Wet:", wet)
    else:
        print("ADC:", value,
              "Relative moisture:", percent, "%")
    sleep(250)

Things to Try

Recalibrate using soil from a different location. Compare tap water and distilled water. Keep the probe electronics dry, and rinse/dry the probe between samples.

Make It Your Own

Would your instrument benefit from LOW, MEDIUM, and HIGH labels? Explain how to set boundaries using the saved dry and wet references, not guessed absolute water-content values.

Try It with AI! Turn your calibrated moisture meter into a plant-watering helper! Ask AI to add LOW, MEDIUM, and HIGH labels based on your saved dry/wet readings, without changing the sensor wiring or calibration buttons.

7.4 Conductivity Detective — Comparing Water Samples
Conductivity detective TFT display with example ADC 625, stored 418, difference plus 207
7.4 — comparing a saved reading with a live reading · Simulated from the approved MicroPython display routines; example readings, not measured data.

Challenge: Can water samples that look identical conduct electricity differently? Test distilled water, tap water, and tap water containing a little dissolved salt.

Make It Happen

Keep the same wiring as Programs 7.1–7.3. Flash the MicroPython program below. Read the live 0–1023 ADC number and bar on the TFT. Press A to save a sample's ADC reference; move the rinsed probe into a different sample to see the live reading and DIFF (live minus saved). Press B to clear the saved reference. Keep probe depth and temperature as consistent as possible, rinse with distilled water and dry between samples, and keep the TFT and micro:bit dry.

Relative measurements, not calibrated conductivity units: LIVE ADC, SAVED ADC, and DIFF are raw analog-to-digital converter counts (0–1023 for the individual readings). They are useful for comparing samples, but they are not conductivity values in µS/cm or a calibrated percentage. More dissolved ions generally increase water conductivity, but the direction of ADC change depends on the sensor electronics. Do not equate a higher ADC number with higher conductivity until you check the hardware's response.

RAM-only reference: The saved value is stored in RAM, not permanent memory. Resetting, powering off, or reflashing the micro:bit clears it. Press Button A again to save a fresh reference after every restart.

💻  View & Copy MicroPython Program — 7.4 Conductivity Detective  ▾ Expand / collapse

from microbit import *

# Invisible World 7.4 - Conductivity Detective
# Parallax Inc. - SKU 32890
# micro:bit / 128x160 ST7735 TFT
# Probe AOUT -> 220 ohm -> P2
# TFT SCL=P13, SDA=P15, RES=P12
# TFT DC=P8, CS=P16
# A: save reference ADC reading
# B: clear reference
# All saved values are in RAM only

W, H = 128, 160
cs, dc, rst = pin16, pin8, pin12

spi.init(baudrate=8000000, bits=8, mode=0,
         sclk=pin13, mosi=pin15, miso=pin14)

def command(n):
    cs.write_digital(0)
    dc.write_digital(0)
    spi.write(bytes([n]))
    cs.write_digital(1)

def data(b):
    cs.write_digital(0)
    dc.write_digital(1)
    spi.write(b)
    cs.write_digital(1)

def init_tft():
    cs.write_digital(1)
    dc.write_digital(1)
    rst.write_digital(0)
    sleep(100)
    rst.write_digital(1)
    sleep(150)
    command(0x01)
    sleep(150)
    command(0x11)
    sleep(150)
    command(0x3A)
    data(bytes([0x05]))
    command(0x36)
    data(bytes([0x00]))
    command(0x13)
    sleep(10)
    command(0x29)
    sleep(100)

def window(x0, y0, x1, y1):
    command(0x2A)
    data(bytes([0, x0, 0, x1]))
    command(0x2B)
    data(bytes([0, y0, 0, y1]))
    command(0x2C)

BLACK = (0, 0)
WHITE = (255, 255)
CYAN = (7, 255)
BLUE = (3, 31)
GREEN = (7, 224)
YELLOW = (255, 224)
GRAY = (66, 8)

def fill_rect(x, y, w, h, color):
    if w <= 0 or h <= 0:
        return
    window(x, y, x+w-1, y+h-1)
    line = bytes(color) * w
    cs.write_digital(0)
    dc.write_digital(1)
    for i in range(h):
        spi.write(line)
    cs.write_digital(1)

FONT = {
    ' ': (0,0,0,0,0,0,0),
    '+': (0,4,4,31,4,4,0),
    '-': (0,0,0,31,0,0,0),
    '0': (14,17,19,21,25,17,14),
    '1': (4,12,4,4,4,4,14),
    '2': (14,17,1,2,4,8,31),
    '3': (30,1,1,14,1,1,30),
    '4': (2,6,10,18,31,2,2),
    '5': (31,16,30,1,1,17,14),
    '6': (6,8,16,30,17,17,14),
    '7': (31,1,2,4,8,8,8),
    '8': (14,17,17,14,17,17,14),
    '9': (14,17,17,15,1,2,12),
    'A': (14,17,17,31,17,17,17),
    'B': (30,17,17,30,17,17,30),
    'C': (14,17,16,16,16,17,14),
    'D': (30,17,17,17,17,17,30),
    'E': (31,16,16,30,16,16,31),
    'F': (31,16,16,30,16,16,16),
    'I': (14,4,4,4,4,4,14),
    'L': (16,16,16,16,16,16,31),
    'N': (17,25,21,19,17,17,17),
    'O': (14,17,17,17,17,17,14),
    'R': (30,17,17,30,20,18,17),
    'S': (15,16,16,14,1,1,30),
    'T': (31,4,4,4,4,4,4),
    'U': (17,17,17,17,17,17,14),
    'V': (17,17,17,17,17,10,4),
    'Y': (17,17,10,4,4,4,4)
}

def draw_text(x, y, msg, scale, color):
    for ch in msg:
        glyph = FONT.get(ch, FONT[' '])
        for gy in range(7):
            bits = glyph[gy]
            for gx in range(5):
                if bits & (1 << (4-gx)):
                    fill_rect(x+gx*scale,
                              y+gy*scale,
                              scale, scale, color)
        x += 6*scale

def read_probe():
    total = 0
    for i in range(10):
        total += pin2.read_analog()
        sleep(10)
    return total // 10

def centered(y, msg, scale, color):
    width = len(msg) * 6 * scale
    draw_text((W-width)//2, y,
              msg, scale, color)

def draw_meter(value, saved):
    fill_rect(0, 37, 128, 123, BLACK)
    centered(46, str(value), 3, WHITE)
    fill_rect(9, 75, 110, 18, GRAY)
    fill_rect(11, 77, 106, 14, BLACK)
    bar = value * 106 // 1023
    if value < 340:
        color = BLUE
    elif value < 680:
        color = GREEN
    else:
        color = CYAN
    fill_rect(11, 77, bar, 14, color)

    if saved is None:
        centered(103, "A TO SAVE", 1, YELLOW)
        centered(122, "B TO CLEAR", 1, WHITE)
    else:
        draw_text(6, 103, "SAVED", 1, CYAN)
        draw_text(76, 103, str(saved), 1, WHITE)
        difference = value - saved
        if difference >= 0:
            change = "+" + str(difference)
        else:
            change = str(difference)
        draw_text(6, 123, "DIFF", 1, CYAN)
        draw_text(68, 123, change, 1, WHITE)

    draw_text(9, 147, "A SAVE B CLEAR",
              1, WHITE)

init_tft()
display.off()
fill_rect(0, 0, W, H, BLACK)
fill_rect(0, 0, W, 5, BLUE)
centered(15, "CONDUCTIVITY", 1, CYAN)

saved = None
while True:
    value = read_probe()
    if button_a.was_pressed():
        saved = value
        print("Saved ADC:", saved)
    if button_b.was_pressed():
        saved = None
        print("Reference cleared")
    draw_meter(value, saved)
    if saved is None:
        print("Live ADC:", value)
    else:
        print("Live:", value,
              "Saved:", saved,
              "Difference:", value-saved)
    sleep(350)

What's Going On?

Dissolved ions carry electric current through water. Distilled water usually has lower conductivity than mineral-containing tap water; adding table salt generally increases conductivity. The probe measures an electrical response influenced by these properties, not ionic concentration directly.

Things to Try

Record three readings per sample and compare averages. Change only one variable at a time. Briefly immerse the probe to reduce electrode polarization and corrosion; do not leave a DC-powered resistive probe submerged for extended periods.

Make It Your Own

Ask AI to modify the program to display the average of three saved samples while retaining the proven TFT wiring and pin assignments.

Leave A Comment