//ICC-AVR application builder : 2005-09-22 오전 2:27:10
// Target : M128
// Crystal: 11.059Mhz

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

#define SETCANCLE  0
#define SETOK	   1
#define SETSUSPEND 2

// 20us 타이머와 10ms 타이머용 변수를 만든다
int twenty_ustimer,Half_sectimer;

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

//TIMER0 initialize - prescale:1
// WGM: Normal
// desired value: 20uSec
// actual value: 19.984uSec (0.1%)
void timer0_init(void)
{
 TCCR0 = 0x00; //stop
 ASSR  = 0x00; //set async mode
 TCNT0 = 0x23; //set count
 OCR0  = 0xDD;
 TCCR0 = 0x01; //start timer
}

#pragma interrupt_handler timer0_ovf_isr:17
void timer0_ovf_isr(void)
{
 twenty_ustimer++;   // 20us마다 timer0 오버플로우 걸리면 20us 타이머를 하나씩 증가시킨다.
 if(twenty_ustimer>=25000){   //20us 타이머가 25000보다 크면 즉,0.5초마다 1초 타이머를 하나씩 증가시킨다.
 	if(Half_sectimer==SETOK)
		Half_sectimer = SETCANCLE;
	else
		Half_sectimer = SETOK;	
	twenty_ustimer=0;  	// 20us 타이머 0으로 초기화
 }
 
 TCNT0 = 0x23; //reload counter value 이 값은 실제 오실로 스코프로 찍어서, 정확한 값을 결정한다.
               //이유: 실제로는 이 값대로 되어야 하나, 인터럽트 함수에서 많은 라인들로 인하여 값이 느려진다.     
}

//UART0 initialize
// desired baud rate: 9600
// actual: baud rate:9600 (0.0%)
// char size: 5 bits
// parity: Disabled
void uart0_init(void)
{
 UCSR0B = 0x00; //disable while setting baud rate
 UCSR0A = 0x00;
 UCSR0C = 0x00;
 UBRR0L = 0x47; //set baud rate lo
 UBRR0H = 0x00; //set baud rate hi
 UCSR0B = 0xF8;
}

#pragma interrupt_handler uart0_rx_isr:19
void uart0_rx_isr(void)
{
 //uart has received a character in UDR
}

#pragma interrupt_handler uart0_udre_isr:20
void uart0_udre_isr(void)
{
 //character transferred to shift register so UDR is now empty
}

#pragma interrupt_handler uart0_tx_isr:21
void uart0_tx_isr(void)
{
 //character has been tdransmitted
}

//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();
	 
	 twenty_ustimer=Half_sectimer=0;
	 while(1){
	 	if(Half_sectimer==SETOK){
			PORTC=0x01;
			Half_sectimer=SETSUSPEND;
		}else{
			PORTC=0x02;
			Half_sectimer=SETSUSPEND;
		}
	 }
}    		
			 
	 	 