//ICC-AVR application builder : 2011-01-20 ¿ÀÈÄ 10:48:52
// Target : M128
// Crystal: 16.000Mhz

#include <iom128v.h>
#include <macros.h>
#include <stdio.h>

#define	 ON		  1
#define	 OFF	  0

volatile unsigned char RXdata0;
volatile int RXon0=OFF, hh=0, mm=0, ss=0, tt=0, count=0;
int toggle=0;

int putchar(char c)
{
  while (((UCSR0A>>UDRE0)&0x01) == 0) ;  // UDRE, data register empty
  UDR0 = c;
  return c;
}

void port_init(void)
{
 PORTA = 0x00;
 DDRA  = 0x00;
 PORTB = 0x00;
 DDRB  = 0x00;
 PORTC = 0x00; //m103 output only
 DDRC  = 0x00;
 PORTD = 0x00;
 DDRD  = 0x00;
 PORTE = 0x00;
 DDRE  = 0x00;
 PORTF = 0x00;
 DDRF  = 0x00;
 PORTG = 0x00;
 DDRG  = 0x03;
}

//TIMER0 initialize - prescale:64
// WGM: Normal
// desired value: 1KHz
// actual value:  1.000KHz (0.0%)
void timer0_init(void)
{
 TCCR0 = 0x00; //stop
 ASSR  = 0x00; //set async mode
 TCNT0 = 0x06; //set count
 OCR0  = 0xFA;
 TCCR0 = 0x06; //start timer
}

#pragma interrupt_handler timer0_ovf_isr:iv_TIM0_OVF
void timer0_ovf_isr(void)
{
 TCNT0 = 0x06; //reload counter value
 count++;
 if(count >= 25)
 {
    tt++; count=0;
	if(tt >= 10)
    {
        ss++; tt=0;
  	}
 	if(ss >= 60)
 	{
        mm++; ss=0;
 	}
	if(mm >= 60)
 	{
        hh++; mm=0;
 	}
	  	printf("%d : %d : %d.%d\r\n",hh,mm,ss,tt);
 	}	
}

//UART0 initialize
// desired baud rate: 9600
// actual: baud rate:9615 (0.2%)
// char size: 8 bit
// parity: Disabled
void uart0_init(void)
{
 UCSR0B = 0x00; //disable while setting baud rate
 UCSR0A = 0x00;
 UCSR0C = 0x06;
 UBRR0L = 0x67; //set baud rate lo
 UBRR0H = 0x00; //set baud rate hi
 UCSR0B = 0x98;
}

//call this routine to initialize all peripherals
void init_devices(void)
{
 //stop errant interrupts until set up
 CLI(); //disable all interrupts
 XDIV  = 0x00; //xtal divider
 XMCRA = 0x00; //external memory
 port_init();
 //timer0_init();
 uart0_init();

 MCUCR = 0x00;
 EICRA = 0x00; //extended ext ints
 EICRB = 0x00; //extended ext ints
 EIMSK = 0x00;
 TIMSK = 0x01; //timer interrupt sources
 ETIMSK = 0x00; //extended timer interrupt sources
 SEI(); //re-enable interrupts
 //all peripherals are now initialized
}

//
void main(void)
{
 init_devices();
 //insert your functional code here...
 while(1)
 {
    if(((PING & 0x0c)>>2) == 0x01)
	{
	 	while(!(((PING & 0x0c)>>2) == 0x00));
		{
	        if(toggle == 0){
		        PORTG=0x01;
				toggle=1;
				timer0_init();
			}
			else if(toggle == 1){
	      		PORTG=0x02;
				TCCR0=0x00;
				toggle=0;
	 	    }
		}
	}
	
	if(((PING & 0x0c)>>2) == 0x02)
	{
	    while(!(((PING & 0x0c)>>2) == 0x00));
		{
		    PORTG=0x00;
	        hh=0; mm=0; ss=0; tt=0; count=0;
			printf("%d : %d : %d.%d\r\n",hh,mm,ss,tt);
		}
	}
 }
 
}

#pragma interrupt_handler uart0_rx_isr:iv_USART0_RXC
void uart0_rx_isr(void)
{
//uart has received a character in UDR
  //while ((UCSR0A & 0x80) == 0);
  RXdata0=UDR0;
  RXon0=ON;
}