#include <stdint.h>

#define UART_TX      (*(volatile unsigned char *)0x10000000u)
#define UART_STATUS  (*(volatile unsigned int  *)0x10000004u)
#define WDT_ARM      (*(volatile unsigned int  *)0x30000000u)
#define WDT_KICK     (*(volatile unsigned int  *)0x30000004u)
#define GPIO_DIR     (*(volatile unsigned int  *)0x40000008u)
#define GPIO_TOG     (*(volatile unsigned int  *)0x40000014u)

#ifndef APP_ID
#define APP_ID 0
#endif
#ifndef APP_VER
#define APP_VER 1
#endif

static void delay(unsigned int n)
{
    volatile unsigned int i;
    for (i = 0u; i < n; ++i) __asm__ volatile ("nop");
}

static void putc(char c) { while (UART_STATUS & 1u) ; UART_TX = (unsigned char)c; }
static void puts(const char *s) { while (*s) putc(*s++); }
static void puthex(unsigned int v)
{
    int i;
    for (i = 28; i >= 0; i -= 4) putc("0123456789abcdef"[(v >> i) & 0xfu]);
}

int main(void)
{
    unsigned int beat = 0u;
    GPIO_DIR = 0xffu;
    puts("\r\nEP09 APP ");
    putc(APP_ID ? 'B' : 'A');
    puts(" VER="); puthex((unsigned int)APP_VER);
    puts(" RUNNING\r\n");
    WDT_ARM = 1u;
    while (1) {
        WDT_KICK = 1u;
        GPIO_TOG = 1u;
        if (beat < 5u) {
            puts("HEARTBEAT "); puthex(beat); puts("\r\n");
            ++beat;
        }
        delay(2000000u);
    }
    return 0;
}
