#include <intrins.h>                             // for _nop_();
#include "def.h"
#include "val.h"
#include "dfu.h"
#include "usb.h"
#include "mcu.h"


//-----MCU.C-----//
extern void Reboot_Mcu( BYTE );


//-----USB.C-----//
extern void USB_Int( void );


BYTE Wdt;


void Delay_nop( void )
  { _nop_();
  }


void Delay_Xms( BYTE X )
  { BYTE Cnt;
    
    
    while( X )
      { Cnt = 250;                               // 1ms at 12Mhz
        while( Cnt )
          { Delay_nop();
            Delay_nop();
            Delay_nop();
            Delay_nop();
            Cnt--;
          }
      	X--;
      }
  }


void Reboot_Mcu( BYTE Cmd )
  { ISPCR = Cmd;
  }


void INT_USB(void) interrupt 15 using 2          // USB Interrupt
  { WDTCR = Wdt;                                 // Reset Watch Dog Timer
    USB_Int();
  }


void Initial_Mcu( void )
  { P2M0 = 0x03;                                 // Set P2.0 , P2.1 Open_Drain Output
    P2M1 = 0x03;                                 // Set P2.0 , P2.1 Open_Drain Output
    SICON |= ( ENTWAI | CR1 | CR0 );             // Enalbe IIC and Setting CLK = 200K
    
    IE  = 0x00;	                                 // disable all interrupt
    
    AUXIE = EUSB;                                // Enable USB int
    
    PSW = 0x00;	                                 // bank 0
    
    Wdt = WDTCR;
    Wdt |= 0x37;                                 // Setting and Reset WDT
    
    CKCON = (BYTE)(( 12 - 1 ) << 3);             // CLKin -> Default , OSCDN = 12Mhz - 1
        
    CKCON2 |= EN_PLL;                            // Enalbe EN_PLL ( for USB )
    while( 1 )
      { if ( CKCON2 & PLL_RDY )                  // Check PLL ready ? ( APLL Ready )
          break;
      }
    
    CKCON2 |= EN_USB;                            // Enalbe EN_USB
    
    USB[ACKCTL] |= EN_DLL;                       // Enable DPLL
    Delay_Xms( 3 );
    USB[ACKCTL] |= UCK_SEL;                      // Switch DPLL to USB
    
    USB[ACKCTL] |= ACKEN;                        // Enable Audio Clock
    
    Delay_Xms( 250 );
    
    EA  = 1;                                     // enable all interrupt
  }