Controlling the display

Copyright © 2017–2023 J. M. Spivey
Jump to navigation Jump to search

One of the attractions of the micro:bit for exploring low-level programming is that it has the 25-LED display, but that controlling this display is not quite trivial, giving a series of non-trivial but nevertheless manageable challenges. Our early attempts to program the display will depend on controlling the hardware directly, and will need different code on the V1 and V2 {microbit}}s, whose displays are wired differently. However, once we start to use the display as a tool for investigating other aspects of the hardware (for example, when we use it to implement a 2-D spirit level based on the accelerometer), it's good if client code can be written in a way that is the same for V1 and V2. The micro:bian operating system provides a server process – implemented differently on V1 and V2 – that provides just this abstraction.

Static images

The IMAGE macro can be used to create a static image, with the macro call written the same way for both V1 and V2, but expanding into an array initialiser that has length 3 words in V1 and 10 words on V2.

static const unsigned heart[] =
    IMAGE(0,1,0,1,0,
          1,1,1,1,1,
          1,1,1,1,1,
          0,1,1,1,0,
          0,0,1,0,0);

That call of the IMAGE macro expands and simplifies (on V1) to something equivalent to the text

{ 0x28f0, 0x5e00, 0x8060 }

The expansion and simplification process relies both on the macro expansion provided by the C preprocessor, and the fact that the C compiler itself can take complex expressions involving shifts and bitwise-or operations and reduce them to simple constants, suitable for defining a read-only array.

Computing images dynamically

The micro:bian display server