/*
Exercicio - 15/04/02
Alunos: Francisco do Nascimento
        Zilma Felix
*/

#include <reg51.h>

#define FrClk 12000000
#define FreqTimer0_emHz 100
#define VALOR_TH0 ((65536 - (FrClk / (12 * FreqTimer0_emHz - 8 ))) >>8)
#define VALOR_TL0 ((65536 - (FrClk / (12 * FreqTimer0_emHz - 8 ))) & 0xFF)

int countL = 0;
int countH = 0;
bit testeL = 0;
bit testeH = 0;
sbit cL = P2^0;
sbit cH = P2^1;

void timer0_inicializa() 
  {
  TR0 = 0;              // Desliga Timer0
  TMOD |= 0x01;  // Timer 0 programado como timer de 16 bits
  TH0 = VALOR_TH0;  // Programa contagem do Timer0
  TL0 = VALOR_TL0;
  ET0 = 1;      // Habilita interrupcao do timer 0
  TR0 = 1;      // Habilita contagem do timer 0
  }

void timer0_int (void) interrupt 1 using 2
{
  TR0 = 0;              // Desliga Timer0
  TH0 += VALOR_TH0;  // Programa contagem do Timer0
  TL0  += VALOR_TL0;
  TR0 = 1;      // Habilita contagem do timer 0
  if (testeL == 1) {
      if (countL != 100) {
	    countL++;
	  }
  }
  if (testeH == 1) {
	  if (countH != 100) {
	    countH++;
	  }
  }

} 

void TarefaL() {
    static char estadoL = 'A';

   	switch (estadoL) {
		case 'A': 
			if (cL == 1) {
			    estadoL = 'B';
				P1 = (P1&0xf0) | (P0&0x0f);
				testeL = 1;
				countL = 0;
			}
			break;
		case 'B':
			if (countL == 100) {
			    testeL = 0;
		        estadoL = 'C';
				P1 = P1&0xf0;
			}
			break;
		case 'C':
		    if (cL == 0) {
			   estadoL = 'A';
			}
			break;
	}
	
}

void TarefaH() {
    static char estadoH = 'A';

   	switch (estadoH) {
		case 'A': 
			if (cH == 1) {
			    estadoH = 'B';
				P1 = (P1&0x0F) | (P0&0xf0);
				testeH = 1;
				countH = 0;
			}
			break;
		case 'B':
			if (countH == 100) {
				testeH = 0;
		        estadoH = 'C';
				P1 = P1&0x0F;
			}
			break;
		case 'C':
		    if (cH == 0) {
			   estadoH = 'A';
			}
			break;
	}
	
}

void main(){
	timer0_inicializa();
	EA = 1; // habilita as interrupcoes
	while(1){
	   TarefaL();
	   TarefaH();
	}
}

/*
Observações:
como count é uma variavel compartilhada deveria ter sido usada atomicamente.
ex.:
EA = 0;
count = 0;
EA = 1;
*/
