#include <ezusb.h>
#include <ezregs.h>

#include "type.h"

#include "led.h"
#include "AD7739.h"
#include "mag.h"

/**
 * Timer0 setting
 */
static u8 timer0_period_l;
static u8 timer0_period_h;

void timer0_set_counter(void)
{
	if(timer0_period_l > (TL0 += timer0_period_l)){
    TH0 += (timer0_period_h + 1);
  }else{
    TH0 += timer0_period_h;
  }
}

void timer0_set_period(u16 period)
{
	timer0_period_l = (period & 0xFF);
  timer0_period_h = (period >> 8);
}

void timer0_init(void)
{
	
	TR0 = 0; // Timer0 stop

	CKCON &= 0xF7; // Timer 0 using CLK 24/12
	TMOD &= 0xF0; // clear Timer 0 mode bits
	TMOD |= 0x01; // Timer0 => 16bit
	
	TL0 = 0;
	TH0 = 0;
	timer0_set_period(0x10000 - 20000); // 24M / 12 / 20000 = 100(Hz)

	timer0_set_counter();

	//PTO = 0; // sets the Timer 0 interrupt to low priority
	ET0 = 1; // enables Timer 0 interrupt
	TR0 = 1; // starts Timer 0
}

s32 global_ms = 0;

void ISR_TMR0 (void) interrupt TMR0_VECT
{
	static int loop = 0;
	//TR0 = 0; // stop timer 0
	timer0_set_counter();
	//TR0 = 1; // start timer 0

	ad7739_start();
  
  global_ms += 10;
  
  if(++loop == 100){
    //led0_toggle();
    loop = 0;
    mag_read();
  }
}

