/*
 * Peripheral device configuration and initializations
 */
#include <t_services.h>
#include <cqnxparm.h>
#include <lpc2388def.h>

void user_config()
{
    UW otg_clock_enable;

    /* Set interrupt priorities */
    chg_pri(INHNO_TIMER2, 5);	/* System Timer */
    chg_pri(INHNO_U0, 4);	/* UART0 */
    chg_pri(INHNO_USB, 4);	/* USB Host */
    chg_pri(INHNO_GPDMA, 4);
    chg_pri(INHNO_SD,  5);
    chg_pri(INHNO_TIMER0, 6);	/* IR Control */
    chg_pri(INHNO_EINT3, 7);	/* Touch panel */
    chg_pri(INHNO_RTC, 10);

    /* Enable /PENIRQ from touch panel on P2[8] */
    FIO2DIR = 0;    /* Input */
    PINMODE4 |= (0x02 << 16);   /* Disable pull-up/down */
    IO2_INT_CLR = PENIRQ;
    IO2_INT_EN_F = PENIRQ;

    PCONP |= PCUSB; /* Power the USB block */

    /* Enable USB host and USB OTG clock */
    otg_clock_enable = USB_HOST_CLK_EN | USB_OTG_CLK_EN /*| USB_AHB_CLK_EN | USB_DEV_CLK_EN*/;
    OTG_CLK_CTRL =otg_clock_enable; 
    while( (OTG_CLK_STAT & otg_clock_enable) != otg_clock_enable);

    /* use always Host Port 1 */
    OTG_STAT_CTRL=OTCTRL_PORT1_HOST;
    /* P0.29 = USB1:D+  P0.30= USB1:D- */
    PINSEL1 |= PS1_P029_USB_DP1 | PS1_P030_USB_DM1;

    /* Enable PWM1.2 */
    PINSEL4 |= (0x01 << 2);

    /* Enable I2S on P0 */
    PCLKSEL1 &= ~ (0x03 << 22); /* Select CCLK */
    PCLKSEL1 |= (0x01 << 22);
    PCONP |= PCI2S;
    PINSEL0 |= (0x01 << 8) | (0x01 << 10) | (0x01 << 12) |
        (0x01 << 14 ) | (0x01 << 16) | (0x01 << 18);
    /* Enable SCL1 and SDA1 on P0[0] and P0[1] */
    PINSEL0 |= (0x03 << 0) | (0x03 << 2);
    /* Enable SCL2 and SDA2 on P0[10] and P0[11] */
    PINSEL0 |= (0x02 << 20) | (0x02 << 22);

    /* Enable SCK0, SSEL0, MISO0 and MOSI0
     * on P0[15], P0[16], P1[23] and P1[24]
     */
    PINSEL0 |= (0x02 << 30);
    PINSEL1 |= (0x02 << 0);
    PINSEL3 |= (0x03 << 14) | (0x03 << 16);
    PCLKSEL1 &= ~(0x03 << 10);
    PCLKSEL1 |= (0x01 << 10);   /* Select CCLK */

    /*
     * Enable CAP0.0 and CAP0.1 on P1[26] and P1[27].
     * This is for IR controller.
     */
    PINSEL3 |= (0x03 << 20) | (0x03 << 22);

    /* Generate 12MHz on MAT1[0] on P1[22].
     * This clock is used for CODEC.
     */
    PINSEL3 |= (0x03 << 12);
    PCLKSEL0 |= (0x01<<4);    /* Use 72MHz clock */
    T1TCR = 2;      /* Reset timer */
    T1TCR = 0;      /* Stop timer */
    T1PR = 0;       /* No prescale */
#define	EM0	(1<<0)
#define	BITPOS_EMC0  4
#define	MR0R	(1<<1)
    T1EMR = EM0 | (0x03 << BITPOS_EMC0);
    T1MCR = MR0R;   /* Reset on MR0 match */
    T1MR0 = 2;
    T1TCR = 1;      /* Start couting */

    adc_init();
    rtc_init();
    pwm_init();
    ir_init();
    s9705_init();
}
