#include <stdint.h>

#define INTERVAL ((volatile uint32_t *)(uintptr_t)0xff202000u)
#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_HUNDREDTH 1000000u
#define HUNDREDTHS_PER_STEP 50u

/* 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[(first + column) % sizeof message];
        if (column < 2)
            high = (high << 8) | pattern;
        else
            low = (low << 8) | pattern;
    }
    HEX5_TO_4 = high;
    HEX3_TO_0 = low;
}

static void start_timer(void)
{
    uint32_t reload = TICKS_PER_HUNDREDTH - 1u;
    INTERVAL[1] = 8u; /* STOP while programming. */
    INTERVAL[2] = reload & 0xffffu;
    INTERVAL[3] = reload >> 16;
    INTERVAL[0] = 0u; /* Clear any previous timeout. */
    INTERVAL[1] = 4u; /* TODO: keep the timer running after the first timeout. */
}

int main(void)
{
    unsigned position = 0, hundredths = 0, running = 1;
    KEY_EDGES = 15u;
    show(position);
    start_timer();
    for (;;) {
        uint32_t edges = KEY_EDGES & 15u;
        if (edges != 0u) {
            KEY_EDGES = edges;
            running = !running;
        }
        if ((INTERVAL[0] & 1u) != 0u) {
            INTERVAL[0] = 0u;
            if (running && ++hundredths == HUNDREDTHS_PER_STEP) {
                hundredths = 0;
                position = (position + 1u) % sizeof message;
                show(position);
            }
        }
    }
}
