#include "BoardCfg.h"

int InitBoard()
{
    HEARTBEAT_LED_1_PIN_DIR = PIN_OUTPUT;
//	HEARTBEAT_LED_2_PIN_DIR = PIN_OUTPUT;
	
//	HEARTBEAT_LED_2_PIN = LED_ON;
	HEARTBEAT_LED_1_PIN = LED_ON;
    
    GP_DEBUG_1_PIN_DIR = PIN_OUTPUT;
    GP_DEBUG_1_PIN = 0;
    GP_DEBUG_2_PIN_DIR = PIN_OUTPUT;
    GP_DEBUG_2_PIN = 0;
    
    
    SPI_SDI_PIN_DIR	= PIN_INPUT;
    SD_SPI_SS_PIN_DIR = PIN_OUTPUT;
    SPI_SDO_PIN_DIR = PIN_OUTPUT;
    SPI_SCK_PIN_DIR	= PIN_OUTPUT;
    
     //Wifi (WINC1500 module)
    WIFI_SPI_SS_PIN_DIR = PIN_OUTPUT;
    WIFI_SPI_SS_PIN = 1;
    WIFI_IRQ_PIN_DIR = PIN_INPUT;
//    WIFI_WAKE_PIN_DIR = PIN_OUTPUT;
//    WIFI_WAKE_PIN = 1;
    WIFI_SPI_CFG_PIN_DIR = PIN_OUTPUT;
    WIFI_SPI_CFG_PIN = 0;
    WIFI_CHP_EN_PIN_DIR = PIN_OUTPUT;
    WIFI_CHP_EN_PIN = 0;
    WIFI_CHP_RST_PIN_DIR = PIN_OUTPUT;
    WIFI_CHP_RST_PIN = 0;
    
    //Wifi chip IRQ
    IEC0bits.INT0IE = 0;
    IFS0bits.INT0IF = 0;
    INTCONbits.INT0EP = 0;  //Rising edge
    IPC0bits.INT0IP = 3;
    IPC0bits.INT0IS = 0;
    IEC0bits.INT0IE = 1;
    
    //Wifi chip SPI
     SPI2CON = 0;
     SPI2CONbits.MSTEN = 1;
     SPI2CONbits.CKE = 0;
     SPI2CONbits.SMP = 0;
     SPI2CONbits.CKP = 0;
     SPI2BRG = SPICalculateBRG(PERIPHERAL_FREQ, 500000);
     SPI2CONbits.ON = 1;
     
     

    //Control knob encoder
    KNOB_PH_A_PIN_DIR = PIN_INPUT;
    KNOB_PH_B_PIN_DIR = PIN_INPUT;
    KNOB_TGLE_BTN_PIN_DIR = PIN_INPUT;
    IEC0bits.INT1IE = 0;
    IFS0bits.INT1IF = 0;
    INTCONbits.INT1EP = 1;  //Rising edge
    IPC1bits.INT1IP = 2;
    IPC1bits.INT1IS = 1;
//    IEC0bits.INT1IE = 1;

    
    


    //Led controller PWM
    LED_PWM_PIN_DIR = PIN_OUTPUT;
    LED_PWM_PIN = 0;
    
	OC3CON = 0;
	OC3R = 0;
	OC3RS = 2000;   //50% PWM
	OC3CONbits.OCTSEL = 0;
	OC3CONbits.OCM = 0b110;	//PWM mode, no fault protection
	
	T2CONbits.TON = 0; // Disable Timer
	T2CONbits.TCS = 0; // Select internal instruction cycle clock
	T2CONbits.TGATE = 0; // Disable Gated Timer mode
	T2CONbits.TCKPS = 0b00; // Select 1:1 Prescaler
	TMR2 = 0x00; // Clear timer register
	
	//PR2 = 256; // Load the period value
    PR2 = PWM_RANGE_MAX;     //10KHz @ 80MHz
	
	IPC2bits.T2IP = 0x01; // Set Timer 2 Interrupt Priority Level
	IFS0bits.T2IF = 0; // Clear Timer 2 Interrupt Flag
	IEC0bits.T2IE = 0; // Disable Timer 2 interrupt
	T2CONbits.TON = 1; // Start Timer
    
    OC3CONbits.ON = 1;
    
    
    return RET_OK;
}
