#include <16F877A.h>  
#device ADC=10  
#fuses XT,NOWDT,NOPROTECT,PUT,BROWNOUT  
#use delay(clock=4000000)

#priority rb,ext,timer1,timer0

int16 temp_analogo_f;
int temp_f;
int temp_min;
int temp_max;
int temp_sp;
int temp_sp_ee;

int d_temp_f;
int retardo = 10;
int contador = 0;
short flanco = 0;
short sp = 0;

#INT_TIMER0
void control_flanco()
{
  contador++;
  if(contador == retardo)
  {
    output_high(pin_C3);
    disable_interrupts(INT_TIMER1);
    contador = 0;
    if(flanco == 0)
    {
      ext_int_edge(H_TO_L);
      flanco = 1;
    }
    else
    {
      ext_int_edge(L_TO_H);
      flanco = 0;
    }
  }
}

// El timer 0 es de 8 bits, eso significa 0 a 255
#INT_TIMER1
void lectura_temperatura()
{
  // Agua fría
  set_adc_channel(0);
  temp_analogo_f=(read_adc()-559L)/2; //10 bits
  temp_f=(int)temp_analogo_f; //conversion a °C (LM335) se mejora con Vref A/D 
    
  temp_min = temp_f+1;
  temp_max = temp_f+4;
}
 
#INT_EXT
void control()
{ 
  output_low(pin_C3);
  enable_interrupts(INT_TIMER1);
  set_timer1(6);
}

#INT_RB
void cambio_temperatura()
{
  if(!input(pin_B4))
  {
    if(temp_sp < temp_max)
    {
      temp_sp++;
      sp = 1;
    }
  }
  if(!input(pin_B5))
  {
    if(temp_sp > temp_min)
    {
      temp_sp--;
      sp = 1;
    }
  }   
}

void main()
{
  set_tris_a(0b00111111);
  set_tris_b(0xFF);
  set_tris_c(0x00);

  setup_adc(ADC_CLOCK_DIV_32);
  setup_adc_ports(ALL_ANALOG); 

//  setup_spi(FALSE); 
  setup_timer_0(RTCC_INTERNAL|RTCC_DIV_256);
  setup_timer_1(T1_DIV_BY_1); 
  setup_timer_2(T2_DISABLED,0,1);

  setup_comparator(NC_NC_NC_NC); 
//  setup_vref(VREF_LOW|-2); 

  ext_int_edge(L_TO_H);

  enable_interrupts(GLOBAL);
  enable_interrupts(INT_EXT);
  enable_interrupts(INT_RB);
  enable_interrupts(INT_TIMER0);
  enable_interrupts(INT_TIMER1);

  output_high(pin_C3);
  
  // Agua fría
  set_adc_channel(0);
  temp_analogo_f=(read_adc()-559L)/2; //10 bits
  temp_f=(int)temp_analogo_f; //conversion a °C (LM335) se mejora con Vref A/D 
  
  temp_sp_ee = read_eeprom(0);
  if(temp_sp_ee != 255)
  {
    temp_sp = temp_sp_ee;
  }
  else   
  {
    temp_sp = 15;
  }
  set_timer0(6);
  set_timer1(0);
  
  do
  {
    d_temp_f = temp_sp - temp_f;
// hay que ponerle un cálculo acá para decirle al contador cuantas veces enteras y "decimales" debe contar
    switch(d_temp_f)
    {
       case 1:retardo = 30;
              break;
       case 2:retardo = 20;
              break;
       case 3:retardo = 10;
              break;
       default:retardo = 0;
               break;
    }
    if(sp == 1)
    {
      sp = 0;
      write_eeprom(0,temp_sp);
    }
  }
  while(true);
}
