/*
 * File:		demo_gpio.c
 * Purpose:		Main process
 *
 */

#include "common.h"

/********************************************************************/

#define PIN_NUM_LED     7
#define PIN_NUM_SW1     1

static void _init_gpio()
{
    // enable PORTC clock
    SIM_SCGC5 = SIM_SCGC5_PORTC_MASK;

    // set pin as gpio, default to be input
    PORTC_PCR1 = PORT_PCR_MUX(1);
    PORTC_PCR7 = PORT_PCR_MUX(1);

    // enable inter pull-up resistor
    PORTC_PCR1 |= PORT_PCR_PE_MASK|PORT_PCR_PS_MASK;

    // enable interrupt on falling edge
    PORTC_PCR1 |= PORT_PCR_IRQC(0xA);

    // set ptc7 to be output pin
    GPIOC_PDDR = 1<<PIN_NUM_LED;

    enable_irq(89); //GPIOC Vector is 105. IRQ# is 105-16=89
}



void main (void)
{
  	_init_gpio();

    printf("******************************************************\n");
    printf("This demo shows how to use the GPIO module, including:\n");
    printf("1. GPIO output, using PTC7 to controle the green led.\n");
    printf("2. GPIO input, using PTC1 by SW1, it also generate interrupt\n");
    printf("\n\n");
    printf("When SW1 is pressed down, LED will be dark.\n");

    while(1)
    {
        //printf("GPIOC_PDIR %x\n", GPIOC_PDIR);
        if((GPIOC_PDIR & (1<<PIN_NUM_SW1)) != 0)
            GPIOC_PSOR = 1<<PIN_NUM_LED;
        else
            GPIOC_PCOR = 1<<PIN_NUM_LED;
    }
}

void isr_gpio_portc(void)
{
    PORTC_ISFR=0xFFFFFFFF;  //Clear ISR flags
    printf("gpio interrupt, falling edge\n");
}
/********************************************************************/
