#include "common.h"
#include "uif.h"
#include "misc.h"


void led_test(int a,char** b)
{
    printf("\r\n***LED Test, press any key to exit.***\r\n");
 
    // enable PTC7,8,9,10 as GPIO output pin
    ENABLE_GPIO_CLOCKS;
    LED0_EN;    
    LED1_EN;
    LED2_EN;
    LED3_EN;
    LED_Dir_Out();
    
    SIM_SCGC6 |= SIM_SCGC6_PIT_MASK; // enable PIT module
    PIT_MCR = 0x00;
    PIT_TCTRL0 = 0x00; // disable PIT0
    PIT_LDVAL0 = 0x16E3600; // 0.5s for 48MHz bus clock
    PIT_TCTRL0 = PIT_TCTRL_TIE_MASK; // enable PIT0 and interrupt
    PIT_TFLG0 = 0x01; // clear flag
    PIT_TCTRL0 |= PIT_TCTRL_TEN_MASK;
    enable_irq(INT_PIT0 - 16);

    in_char();  // wait for key;
    disable_irq(INT_PIT0 - 16);
    PIT_TFLG0 = 0x01; // clear flag
    PIT_TCTRL0 = 0x00; // disable PIT0
    PIT_MCR = 0x02;
    GPIOC_PDOR &= ~0x780; 
    GPIOC_PDDR &= ~0x780;  // disable PTC7,8,9, 10
}

void int_pit0(void)
{
    static uint8 led = 0;

    PIT_TFLG0 = 0x01; // clear flag
    PIT_TCTRL0; // dummy read to ensure the interrupt, 
                // must be executed here, or interrupt will never happen.

    switch(led)
    {
        case 0:
            LED0_TOGGLE;
            break;
        case 3:
            LED1_TOGGLE;
            break;
        case 2:
            LED2_TOGGLE;
            break;           
        case 1:
            LED3_TOGGLE;
            break;            
        default:
            GPIOC_PDOR |= 0x780;
            led = 0;
            return;
    }
    led++;
}