#include "IEC60335.h"

extern void RTC_Init( void );

volatile unsigned char clock_100ms;


void SysTick_Handler(void)
{
  static unsigned long ticks;

    IEC60335_Clocktest_TimerIntHandler();

    if (ticks++ >= 9)
    {
        ticks       = 0;
        clock_100ms = 1;
    }
}

int main(void)
{
    SysTick_Config(SystemCoreClock/100);           // Generate IRQ each 10 ms

    LPC_SYSCON->SYSAHBCLKCTRL |= (1UL << 31);      // enable clock for GPIO0
    LPC_GPIO0->DIR |= (1 << 23);                   // LED1 at PIO0_23
    LPC_GPIO0->SET |= (1 << 23);                   // LED1 off
    LPC_GPIO0->DIR |= (1 << 24);                   // LED2 at PIO0_24
    LPC_GPIO0->SET |= (1 << 24);                   // LED2 off

    RTC_Init();
/*
  IEC60335_initClockTest(timerOccThreshold, rtcOccThreshold, timerLowerBound, timerUpperBound);

  Used:
    SysTick timer  : every 10 msec
	Real Time Clock: every 1 sec
	Main loop clock test is called every ~100 msec

  So:
    timerOccThreshold = 1  (within 100 msec always more than 1 systick interrupt has occurred
    rtcOccThreshold   = 11 (need 11 x 100 msec to have at least 1 RTC interrupt

  Within 1 RTC interrupt 100 systick interrupts should have occurred
  So:
    timerLowerBound = 99  (more timer interrupts than lower bound)
    timerUpperBound = 101 (less timer interrupts than upper bound)

*/
    IEC60335_initClockTest(1, 11, 99, 101);

    while (1)
    {
        if (clock_100ms)
        {
            clock_100ms = 0;
            LPC_GPIO0->OUT ^= (1 << 24);           // toggle LED2

            /* Periodic IEC60335 Class B testing */
            if (IEC60335_Clocktest_MainLoopHandler() == IEC60335_testFailed)
            {
                while(1)
                    LPC_GPIO0->CLR |= (1 << 23);   // LED1 on
            }
        }
    }
}
