#include <hidef.h>
#include "derivative.h"

void Init_Port()
{
// PTA偼慡晹瞻晦奐曻(偲傝偁偊偢慡诉萏哔悲踢)
  PTAD  = 0x00;
  PTADD = 0x00;
  PTAPE = 0xff;
  PTASE = 0x00;
  PTADS = 0x00;

// PTB
// PB[0]:---
// PB[1]:ResetSwitch
// PB[2]:BKGD
// PB[3]:BLMS讲/LED
// PB[4]:XTAL(12MHz)
// PB[5]=>XTAL(12MHz)
// PB[6]=> N/A
// PB[7]=> N/A
  PTBD  = 0x08;
  PTBDD = 0x08;
  PTBPE = 0x03;
  PTBSE = 0x00;
  PTBDS = 0x00;
}

//
// 鼐屻偺撪晹港影霓(栺16MHz)偐傜
// 12MHz偺奜晅偗悈徎傪巊偭偨PLL影霓(48MHz)傊偺愗傝懼偊
//
void Init_Clock()
{
  MCGC2 = MCGC2_HGO_MASK
    | MCGC2_EREFS_MASK
    | MCGC2_RANGE_MASK
    | MCGC2_ERCLKEN_MASK;
  while (MCGSC_OSCINIT == 0)
    ;
  MCGC1 = (2<<6) // external reference clock.
      | (3<<3);  // RDIV = 3 : 12MHz/8=1.5 MHz
  while ((MCGSC_IREFST != 0) || (MCGSC_CLKST != 2))

  // FBE  PBE (PLL bypassed internal) 影霓偵堏峴
  MCGC3=MCGC3_PLLS_MASK
    | (8<<0); // multiply by 32 -> 1.5MHz*32=48MHz
  while((MCGSC_PLLST != 1) || (MCGSC_LOCK != 1))
    ;
// PBE影霓偐傜PEE 
// (PLL enabled external mode)
// 影霓偵堏峴
 MCGC1 = (0<<6) //PLL or FLL Clock
  | (3<<3); // 12MHz/8=1.5 MHz
 while(MCGSC_CLKST !=3)
    ;
}


void delay()
{
  unsigned int i,j,k;
  for(k=0;k<20;k++) {
    for (i=0; i<100; i++) {
      for (j=0; j<100; j++)
        ;
    }
  }
}

void main(void) {
 unsigned char c;
 SOPT1 = 0x13; // WDT掆巭.PB1傪鼐擖椡

 Init_Clock();

 Init_Port();
 c = 0;
 for (;;) {
  if (c & 1) {
    PTBD |= 0x08;
    } else {
      PTBD &= ~0x08;
    }
    c++;
    delay();
  }
}