#include <stdint.h>

#define TIMER_LOW (*(volatile uint32_t *)(uintptr_t)0xff202100u)
#define KEY_EDGES (*(volatile uint32_t *)(uintptr_t)0xff20005cu)
#define HEX3_TO_0 (*(volatile uint32_t *)(uintptr_t)0xff200020u)
#define HEX5_TO_4 (*(volatile uint32_t *)(uintptr_t)0xff200030u)
#define TICKS_PER_UPDATE 50000000u

/* d E 1 - S o C, then a blank before the word repeats. */
static const uint8_t message[] = {94, 121, 6, 64, 109, 92, 57, 0};

static void show(unsigned first)
{
    uint32_t low = 0, high = 0;
    for (unsigned column = 0; column < 6; ++column) {
        uint8_t pattern = message[column % sizeof message /* TODO: include the start position. */];
        if (column < 2)
            high = (high << 8) | pattern;
        else
            low = (low << 8) | pattern;
    }
    HEX5_TO_4 = high;
    HEX3_TO_0 = low;
}

int main(void)
{
    unsigned position = 0u;
    unsigned running = 1;
    KEY_EDGES = 15u;
    uint32_t previous = TIMER_LOW;
    show(position);
    for (;;) {
        uint32_t now = TIMER_LOW;
        uint32_t edges = KEY_EDGES & 15u;
        if (edges != 0u) {
            KEY_EDGES = edges;
            running = !running;
            previous = now;
        }
        /* Unsigned subtraction also works across the timer's low-word wrap. */
        uint32_t ticks = now - previous;
        if (running && ticks >= TICKS_PER_UPDATE) {
            uint32_t steps = ticks / TICKS_PER_UPDATE;
            previous += steps * TICKS_PER_UPDATE;
            position = (position + steps) % sizeof message;
            show(position);
        }
    }
}
