Autor Tema: Proyecto Acuario Autonomo  (Leído 4701 veces)

0 Usuarios y 1 Visitante están viendo este tema.

Desconectado jaimearmandofc

  • PIC10
  • *
  • Mensajes: 22
Proyecto Acuario Autonomo
« en: 20 de Marzo de 2011, 16:29:40 »
les presento lo que llevo de mi proyecto de acuario: el cual es con un PIC18f887 un LCD programado en MicroC PRO

les dejo el codigo para lo vean y opinen que tal voy, hasta ahora funciona y activa las luces y apaga a las horas de prueba  aplica los 3 alimentos correctamente

sus funciones son:

-Endendido de Luces
-3 alimentos al dia (programados a determinada hora)
-control de temperatura
-control de ph
-revision de nivel de agua
Código: [Seleccionar]
/*Cabecera******************************************************/
sbit LCD_RS at RB4_bit;
sbit LCD_EN at RB5_bit;
sbit LCD_D4 at RB0_bit;
sbit LCD_D5 at RB1_bit;
sbit LCD_D6 at RB2_bit;
sbit LCD_D7 at RB3_bit;
sbit LCD_RS_Direction at TRISB4_bit;
sbit LCD_EN_Direction at TRISB5_bit;
sbit LCD_D4_Direction at TRISB0_bit;
sbit LCD_D5_Direction at TRISB1_bit;
sbit LCD_D6_Direction at TRISB2_bit;
sbit LCD_D7_Direction at TRISB3_bit;
// Final de conexiones del módulo LCD

int i;
char *ph = "7.0"; //valor por defecto de ph [NORMAL]
unsigned menu=0;
unsigned char segundo =50;
unsigned char minuto=59;
unsigned char hora=7;
unsigned char mensaje =0;
char *texto ;

//variables RAM valores de agua
unsigned char tempunit =25;
unsigned char tempdec = 0;
unsigned char phunit = 7;
unsigned char phdeci = 0;

//pecesitos
const char pez1[] = {0,10,28,10,0,0,0,0};
const char pez2[] = {0,10,28,10,0,0,0,0};
const char pez3[] = {0,0,0,10,28,10,0,0};
const char pez4[] = {0,0,0,0,10,28,10,0};

//variables de carga de EEPROM
//LUCES
unsigned short luce_enc_hor;//hora encendido luces
unsigned short luce_enc_min;//minuto encendido luces
unsigned short luce_off_hor;//hora apagado luces
unsigned short luce_off_min;//minuto apagado luces
////TEMPERATURA
unsigned short grad;//grado temperatura
unsigned short miligrad;//miligradotemperatura
unsigned short tempmax;//temperatura maxima
unsigned short tempmin;//temperatura minima
//ALIMENTO
unsigned short hor_alim1;//hora alimento1
unsigned short min_alim1;//minuto alimento1
unsigned short hor_alim2;//hora alimento2
unsigned short min_alim2;//minuto alimento2
unsigned short hor_alim3;//hora alimento3
unsigned short min_alim3;//minuto alimento3
//PH
unsigned short ph_unit;//ph unidad
unsigned short ph_decim;//ph decimal
unsigned short ph_tol;//ph tolerancia decimal

void display_temperatura(){
     char *temp;
     Lcd_Out(1,15,"°");
     Lcd_Out(1,16,"C");
     BytetoStr(tempdec,temp);
     Lcd_Out(1,12,temp);
     Lcd_Out(1,13,".");
     BytetoStr(tempunit,temp);
     Lcd_Out(1,10,temp);
     Lcd_Out(1,9,"T=");
}

void display_ph(){
char *temp;
BytetoStr(phdeci,temp);
Lcd_Out(2,13,temp);
Lcd_Out(2,14,".");
BytetoStr(phunit,temp);
Lcd_Out(2,11,temp);
Lcd_Out(2,10,"Ph=");
}


void alimento(unsigned char action){
     if (action==1){ //ENCEDEMOS LUCES ACTIVANDO EL PORTC.4
        PORTC.F4=1;
     }
     if (action==0){ //APAGAMOS LUCES DESACTIVANDO EL PORTD.4
        PORTC.F4=0;
     }
}

void luces(unsigned char action){
     if (action==1){ //ENCEDEMOS LUCES ACTIVANDO EL PORTC.6
        PORTC.F6=1;
     }
     if (action==0){ //APAGAMOS LUCES DESACTIVANDO EL PORTD.6
        PORTC.F6=0;
     }
}

void display_mensaje(){
     if (mensaje==1){
     Lcd_Out(2,1,texto);}
     if (mensaje==0){
     Lcd_Out(2,1,"         ");}
}

void programacion(){//revisamos las programaciones segun la hora
     //Luces encendido a las 08:00
     if ((hora==luce_enc_hor) && (minuto==luce_enc_min) && (segundo==0)){//revisar el encendido de Luces
        mensaje=1;
        texto="Luces ON";
        luces(1);
     }
     if ((hora==luce_off_hor) && (minuto==luce_off_min) && (segundo==0)){//revisar el apagado de Luces
        mensaje=1;
        texto="Luces OF";
        luces(0);
     }
     if((hora==hor_alim1)&&(minuto==min_alim1)&&(segundo==0)){//Primer almento
        mensaje=1;
        texto="Alim 1";
        alimento(1);
        Delay_ms(100);
        alimento(0);
     }
     if((hora==hor_alim2)&&(minuto==min_alim2)&&(segundo==0)){//segundo almento
        mensaje=1;
        texto="Alim 2";
        alimento(1);
        Delay_ms(100);
        alimento(0);
     }
     if((hora==hor_alim3)&&(minuto==min_alim3)&&(segundo==0)){//tercer almento
        mensaje=1;
        texto="Alim 3";
        alimento(1);
        Delay_ms(100);
        alimento(0);
     }
     if(segundo==10)mensaje=0;
}

void display_hora(){
char *temp;
//BytetoStr(segundo,temp);
//Lcd_Out(1,8,temp);
//if(segundo<=9)Lcd_Out(1,9,"0");

BytetoStr(minuto,temp);
Lcd_Out(1,5,temp);
if(minuto<=9)Lcd_Out(1,6,"0");

BytetoStr(hora,temp);
if(hora<=9)Lcd_Out(1,3,"0");
Lcd_Out(1,2,temp);
if(hora<=9)Lcd_Out(1,3,"0");

Lcd_Out(1,5,":");
//Lcd_Out(1,8,":"); //segundero
Lcd_Out(1,2,"=");
Lcd_Out(1,5,":");
Lcd_Out(1,1,"H");
}

void LeeEEPROM(){
luce_enc_hor = EEPROM_Read(0x32);   //hora encendido luces
luce_enc_min = EEPROM_Read(0x33);//minuto encendido luces
luce_off_hor = EEPROM_Read(0x34);//hora apagado luces
luce_off_min = EEPROM_Read(0x35);//minuto apagado luces
////TEMPERATURA
grad = EEPROM_Read(0x36);//grado temperatura
miligrad = EEPROM_Read(0x37);//miligradotemperatura
tempmax = EEPROM_Read(0x38);//temperatura maxima
tempmin = EEPROM_Read(0x39);//temperatura minima
//ALIMENTO
hor_alim1 = EEPROM_Read(0x3A);//hora alimento1
min_alim1 = EEPROM_Read(0x3B);//minuto alimento1
hor_alim2 = EEPROM_Read(0x3C);//hora alimento2
min_alim2 = EEPROM_Read(0x3D);//minuto alimento2
hor_alim3 = EEPROM_Read(0x3E);//hora alimento3
min_alim3 = EEPROM_Read(0x3F);//minuto alimento3
//PH
ph_unit = EEPROM_Read(0x40);//ph unidad
ph_decim = EEPROM_Read(0x41);//ph decimal
ph_tol = EEPROM_Read(0x42);//ph tolerancia decimal
}

void timer(){
//incremento del tiempo
segundo++;
if (segundo==60){
segundo=0;
minuto=minuto+1;
display_ph();
display_temperatura();
}
if (minuto==60){
minuto=0;
hora=hora+1;}
if(hora==24){
hora=0;}

}


void main() {
//Grabamos EEPROM
//LUCES
EEPROM_Write(0x32, 8);//hora encendido luces
EEPROM_Write(0x33, 0);//minuto encendido luces
EEPROM_Write(0x34, 8);//hora apagado luces
EEPROM_Write(0x35, 1);//minuto apagado luces
////TEMPERATURA
EEPROM_Write(0x36, 24);//grado temperatura
EEPROM_Write(0x37, 5);//miligradotemperatura
EEPROM_Write(0x38, 27);//temperatura maxima
EEPROM_Write(0x39, 22);//temperatura minima
//ALIMENTO
EEPROM_Write(0x3A, 8);//hora alimento1
EEPROM_Write(0x3B, 2);//minuto alimento1
EEPROM_Write(0x3C, 8);//hora alimento2
EEPROM_Write(0x3D, 3);//minuto alimento2
EEPROM_Write(0x3E, 8);//hora alimento3
EEPROM_Write(0x3F, 4);//minuto alimento3
//PH
EEPROM_Write(0x40, 7);//ph unidad
EEPROM_Write(0x41, 0);//ph decimal
EEPROM_Write(0x42, 30);//ph tolerancia decimal

Delay_ms(10);
LeeEEPROM();

//CONFIGURACION DE PUERTOS
  TRISD = 1; //entradas puerto D Teclado
  PORTD = 0b00000000;
  TRISC = 0; //Salidas para leds y funciones
  PORTC = 0b00000000;//encendemos leds verdes
  //configuramos PUERTO A para sensores
  TRISA = 1; //Entradas para sensores
  PORTA = 0b00000000;

  ANSEL = 0;                // Configurar los pines AN como digitales
  ANSELH = 0;
  C1ON_bit = 0;             // Deshabilitar los comparadores
  C2ON_bit = 0;
 
  Lcd_Init();               // Inicializar el LCD
  Lcd_Cmd(_LCD_CLEAR);      // Borrar el LCD
  Lcd_Cmd(_LCD_CURSOR_OFF); // Apagar el cursor

  //--- bucle principal
  Lcd_Out_Cp("H=");
  Lcd_Out(2,10,"Ph=-.-");
  display_ph();
  display_temperatura();
  display_hora();
  do {
         Delay_ms(50); //simulacion de pulsos
         timer();        //simulador de pulsos
         display_hora(); //mostramos la hora
         programacion(); //revisamos que se esta programado
         display_mensaje(); //mostramos un mensaje por 15 de lo que se esta haciendo
         //mensaje_del();      //
  } while (1);
}



Desconectado JOJOJORGE5

  • PIC16
  • ***
  • Mensajes: 167
Re: Proyecto Acuario Autonomo
« Respuesta #1 en: 20 de Marzo de 2011, 18:54:18 »
muy interesante pero solo el codigo sin tener idea del hardware no ayuda mucho
tambien seria bueno que nos cuentes con que tipo de sensor mediste el ph

salu2:)

Desconectado todopic

  • Administrador
  • DsPIC30
  • *******
  • Mensajes: 3495
    • http://www.todopicelectronica.com.ar
Re: Proyecto Acuario Autonomo
« Respuesta #2 en: 20 de Marzo de 2011, 22:01:20 »
Hola, podrias hacer que al darles el alimento, se detenga la bomba de filtro por unos 10 minutos (el cálculo de la ración de alimento, es lo que pueden comer en 5 minutos, si hay de más... es desperdicio, o se pudre o se sobre alimenta  ;-) )
Firmat - Santa Fe - Argentina

www.TodoPic.net

Solo se tiran piedras, al arbol que tiene frutos...

Desconectado jaimearmandofc

  • PIC10
  • *
  • Mensajes: 22
Re: Proyecto Acuario Autonomo
« Respuesta #3 en: 20 de Marzo de 2011, 23:46:33 »
me parece interesante el comentario sobre la bomba de filtro, pero no lo veo necesario ya que son muy pequeñas las vibraciones para que afecte,

en brebe subire el hardware....

y el sensor de ph aun no lo tengo, solo estoi manejando valores de una variable, espero tener el sensor, y que el pic adquiera los valorees y los guarde en la variable para su funcionamiento

Desconectado todopic

  • Administrador
  • DsPIC30
  • *******
  • Mensajes: 3495
    • http://www.todopicelectronica.com.ar
Re: Proyecto Acuario Autonomo
« Respuesta #4 en: 21 de Marzo de 2011, 07:55:48 »
Hola Jaime, no me refiero a las vibraciones... es para que la bomba, no absorba el alimento
Firmat - Santa Fe - Argentina

www.TodoPic.net

Solo se tiran piedras, al arbol que tiene frutos...

Desconectado jaimearmandofc

  • PIC10
  • *
  • Mensajes: 22
Re: Proyecto Acuario Autonomo
« Respuesta #5 en: 21 de Marzo de 2011, 14:32:01 »
Entiendo, pero si me agrada tu comentario, pero si como te digo, no es necesario, la entrada del filtro se encuentra al otro lado del acuario, el lado opuesto a donde los alimento, y las plantas que estan no permiten que todo el alimento llegue hasta el otro lado antes de que se lo coman,

Desconectado jaimearmandofc

  • PIC10
  • *
  • Mensajes: 22
Re: Proyecto Acuario Autonomo
« Respuesta #6 en: 21 de Marzo de 2011, 19:19:26 »
ahora me ha surgido un nuevo problema,

tengo un sensor de temperatura [LM35] conectado a el pin RA3:   el lm35 configurado a 27°c  me da 0.27116v   simulado en proteus

y en el display tengo...   51.3°c
el codigo es el siguiente:   esta en MikroC PRO

Código: [Seleccionar]
MAIN----->>
 TRISA = 1; //Entradas para sensores
  PORTA = 0b00000000;
 ANSEL = 0b00001000;;          //Configuramos el pin AN3 como analogico.
  ANSELH = 0;    //configurar los demas puertos como digitales
  C1ON_bit = 0;             // Deshabilitar los comparadores
  C2ON_bit = 0;

void calcula_temp(){
       long tlong;//variable larga
       char *txt="00";
       adc_rd=ADC_read(2);
  adc_rd=adc_rd*50000/1023;
  txt[0]=(adc_rd/10000)*10;
  txt[1]=tempunit+((adc_rd%10000)/1000);
  tempunit=(int)txt;
  txt[0]=((adc_rd%10000)%1000)/100;
  tempdec=(int)txt;
  //a4=(((adc_res%10000)%1000)%100)/10;

}

void display_temperatura(){
     char *temp;
     Lcd_Chr(1,15,223);
     Lcd_Out(1,16,"C");
     BytetoStr(tempdec,temp);
     Lcd_Out(1,12,temp);
     Lcd_Out(1,13,".");
     BytetoStr(tempunit,temp);
     Lcd_Out(1,10,temp);
     Lcd_Out(1,8," T=");
}

Desconectado jaimearmandofc

  • PIC10
  • *
  • Mensajes: 22
Re: Proyecto Acuario Autonomo
« Respuesta #7 en: 26 de Marzo de 2011, 00:22:48 »
Esto es lo que llevo hasta el dia de hoy....
Código: [Seleccionar]
/*Cabecera******************************************************/
sbit LCD_RS at RB4_bit;
sbit LCD_EN at RB5_bit;
sbit LCD_D4 at RB0_bit;
sbit LCD_D5 at RB1_bit;
sbit LCD_D6 at RB2_bit;
sbit LCD_D7 at RB3_bit;
sbit LCD_RS_Direction at TRISB4_bit;
sbit LCD_EN_Direction at TRISB5_bit;
sbit LCD_D4_Direction at TRISB0_bit;
sbit LCD_D5_Direction at TRISB1_bit;
sbit LCD_D6_Direction at TRISB2_bit;
sbit LCD_D7_Direction at TRISB3_bit;
// Final de conexiones del módulo LCD

signed char menu=0;
signed char sub=0;
unsigned char segundo =58;
unsigned char minuto=59;
unsigned char hora=7;

unsigned cnt;
float adc2;

signed char lastbut=0;
unsigned char boton=0;


unsigned int adc_rd;//para temperatura
long  tlong;

unsigned char err=0;//para errores

//variables RAM valores de agua
unsigned char tempunit =25; //parametros ideales
unsigned char tempdec = 0;
unsigned char phunit = 7;
unsigned char phdeci = 0;

//variables de carga de EEPROM
//LUCES
unsigned short luce_enc_hor;//hora encendido luces
unsigned short luce_enc_min;//minuto encendido luces
unsigned short luce_off_hor;//hora apagado luces
unsigned short luce_off_min;//minuto apagado luces
////TEMPERATURA
unsigned short grad;//grado temperatura
unsigned short miligrad;//miligradotemperatura
unsigned short tempmax;//temperatura maxima
unsigned short tempmin;//temperatura minima
//ALIMENTO
unsigned short hor_alim1;//hora alimento1
unsigned short min_alim1;//minuto alimento1
unsigned short hor_alim2;//hora alimento2
unsigned short min_alim2;//minuto alimento2
unsigned short hor_alim3;//hora alimento3
unsigned short min_alim3;//minuto alimento3
//PH
unsigned short ph_unit;//ph unidad
unsigned short ph_decim;//ph decimal
unsigned short ph_tol;//ph tolerancia decimal

void LeeEEPROM(){
luce_enc_hor = EEPROM_Read(0x32);   //hora encendido luces
luce_enc_min = EEPROM_Read(0x33);//minuto encendido luces
luce_off_hor = EEPROM_Read(0x34);//hora apagado luces
luce_off_min = EEPROM_Read(0x35);//minuto apagado luces
////TEMPERATURA
grad = EEPROM_Read(0x36);//grado temperatura deseado
miligrad = EEPROM_Read(0x37);//miligradotemperatura
tempmax = EEPROM_Read(0x38);//temperatura maxima
tempmin = EEPROM_Read(0x39);//temperatura minima
//ALIMENTO
hor_alim1 = EEPROM_Read(0x3A);//hora alimento1
min_alim1 = EEPROM_Read(0x3B);//minuto alimento1
hor_alim2 = EEPROM_Read(0x3C);//hora alimento2
min_alim2 = EEPROM_Read(0x3D);//minuto alimento2
hor_alim3 = EEPROM_Read(0x3E);//hora alimento3
min_alim3 = EEPROM_Read(0x3F);//minuto alimento3
//PH
ph_unit = EEPROM_Read(0x40);//ph unidad
ph_decim = EEPROM_Read(0x41);//ph decimal
}




/*ACCIONES*/

void luces(unsigned char action){
     if (action==1){ //ENCEDEMOS LUCES ACTIVANDO EL PORTC.6
        PORTC.F6=1;
     }
     if (action==0){ //APAGAMOS LUCES DESACTIVANDO EL PORTD.6
        PORTC.F6=0;
     }
}

void alimento(unsigned char action){
     if (action==1){ //ENCEDEMOS EL ALIMENTADOR PORTC.4
        PORTC.F4=1;
     }
     if (action==0){ //APAGAMOS EL ALIMENTADOR PORTD.4
        PORTC.F4=0;
     }
}

/*TEMPERATURA*/
void calcula_temperatura(){
char *temp;
//CALCULAMOS TEMPERATURA
    adc_rd = ADC_Read(2);        // Conversión A/D. Pin RA2 es una entrada.
    adc2 = 0.242*adc_rd*2;//(long)adc_rd * 5000;
    FloatToStr(adc2,temp);
    //envio a la RAM
    tempunit=(int)adc2;
    tempdec=(adc2-tempunit)*10;
}


/* PROGRAMACION   alimentox3 luces on y off
*/
void programacion(){//revisamos las programaciones segun la hora
     //Luces encendido a las 08:00
     if ((hora==luce_enc_hor) && (minuto==luce_enc_min) && (segundo==0)){//revisar el encendido de Luces
        luces(1);
     }
     if ((hora==luce_off_hor) && (minuto==luce_off_min) && (segundo==0)){//revisar el apagado de Luces
        luces(0);
     }
     if((hora==hor_alim1)&&(minuto==min_alim1)&&(segundo==0)){//Primer almento
        alimento(1);
     }
     if((hora==hor_alim1)&&(minuto==min_alim1)&&(segundo>2))
        alimento(0);//desactivamos el alimentador
     if((hora==hor_alim2)&&(minuto==min_alim2)&&(segundo==0)){//segundo almento
        alimento(1);
     }
     if((hora==hor_alim2)&&(minuto==min_alim2)&&(segundo>2))
        alimento(0);//desactivamos el alimentador
     if((hora==hor_alim3)&&(minuto==min_alim3)&&(segundo>0)){//tercer almento
        alimento(1);
     }
     if((hora==hor_alim3)&&(minuto==min_alim3)&&(segundo>2)){
        alimento(0);
     }//desactivamos el alimentador
}

void display_menu(){
Lcd_Cmd(_Lcd_CLEAR);//limpiamos pantalla
   switch(sub){
   case 1:
     Lcd_Out(2,1,"<");
     Lcd_Out(2,16,">");
     Lcd_Out(1,1,"<- Menu");
     switch(menu){
        case 1:
           Lcd_Out(2,3,"Ajustar hora");
        case 2:
           Lcd_Out(2,3,"Ajustar Luces");
        case 3:
           Lcd_Out(2,3,"Ajustar Temp");
        case 4:
           Lcd_Out(2,2,"Ajust Alimento");
         case 5:
           Lcd_Out(2,4,"Informe");
        default: menu=99;
     }
     break;
   default: sub=-1;
  }
}


/*HORA
*/
void display_hora(){
char *temp; //variable temporal texto
//IMPRIMIMOS TEMPERATURA
     BytetoStr(tempdec,temp);
     Lcd_Out(1,12,temp);
     BytetoStr(tempunit,temp);
     Lcd_Out(1,10,temp);
     Lcd_Chr(1,15,223);
     Lcd_Out(1,16,"C");
     Lcd_Out(1,13,".");
     Lcd_Out(1,8," T=");

//char *temp;
BytetoStr(minuto,temp);
Lcd_Out(1,5,temp);
if(minuto<=9)Lcd_Out(1,6,"0");

BytetoStr(hora,temp);
Lcd_Out(1,2,temp);
if(hora<=9)Lcd_Out(1,3,"0");

Lcd_Out(1,2,"=");
Lcd_Out(1,5,":");
Lcd_Out(1,1,"H");

//IMPRIMIMOS PH
BytetoStr(phdeci,temp);
Lcd_Out(2,14,temp);
Lcd_Out(2,15,".");
BytetoStr(phunit,temp);
Lcd_Out(2,12,temp);
Lcd_Out(2,10,"Ph=");

Lcd_Out(2,1,"> Menu   ");

}


/*display mensajes de error
imprime errores dependiendo el error cargado
*/
void display_mensajes_error(){
Lcd_Cmd(_LCD_CLEAR);
Lcd_Out(1,1,"Error Agua");
   switch(err){
      case 1://TEMPERATURA ALTA    err=1
         Lcd_Out(2,1,"Enfriar agua");
      case 2: //TEMPERATURA BAJA
         Lcd_Out(2,1,"Calentar Agua");
      case 3: //PH ALTO
         Lcd_Out(2,1,"Bajar PH");
      case 4: //PH BAJO
         Lcd_Out(2,1,"Elevar PH");
      case 5: //ERROR NIVEL DE AGUA
         Lcd_Out(2,1,"Agregar Agua");
   }
}

/* Revision del estado de agua, al encontrar un error mandamos la bandera err a 1
variables globales, tempunit, grad, tempmax, tempmin,
*/
void estadoagua(){//revision de los parametros de agua y mostramos errores en pantalla
//valores de temp 25
   if(tempunit>=(grad+1)){//si la temperatura es alta.
      PORTC.F0=0; //APAGAMOS LOS CALENTADORES
      if(tempunit>tempmax){//si la temperatura sube a la temp max grados de lo normal
         err=1;
         PORTC.F5=1;
         return;
      }
      err=0;
   }
   if(tempunit<=(grad-1)){//si la temperatura es baja.
      PORTC.F0=1; //ENCENDEMOS LOS CALENTADORES
      if(tempunit<tempmin){//si la temperatura baja 2 grados de lo normal
         PORTC.F5=1;//encendemos led de error
         err=2;
         return;
      }
      err=0;
   }
   if(tempunit==grad){
      PORTC.F0=0;//apagamos calentador
      err=0;
   }
   if (Button(&PORTA,5,1,1)){ // revisamos nivel de agua PORTA.0 ERROR
      err=5;
      PORTC.F5=1; //encendemos led ERROR
      }
   if (Button(&PORTA,5,1,0)){// revisamos nivel de agua PORTA.0 BIEN
      err=0;
      }
//   apagamos led ERROR
if (err==0){PORTC.F5=0;}
}


//seleccion de menu
void select_menu(){
   if ((lastbut==1) && (boton==1)){//se selecciono el boton de menu
      menu=1;
      sub=1;
      lastbut=-1;
      boton=0;
   }
   if ((lastbut==2)&&(boton==1)&&(menu==1)){//UP
      switch(sub){ //elegimos el menu en que estamos
         case 0: //si estamos en el menu principal [5]
            menu++;
            if (menu==6)menu=1;
      }
   }
   if ((lastbut==3)&&(boton==1)&&(menu==1)){//DOWN
      switch(menu){//elegimos el menu en que estamos
         case 1: //si estamos en el menu principal [5]
            menu--;
            if (menu==0)menu=5;
      }
   }
   if ((lastbut==4) && (boton==1)){//SALIR
      lastbut=0;
      boton=0;
      menu=0;
   }
      if ((lastbut==5)&&(boton==1)&&(menu!=0)){//SELECT
      sub++;//ingresamos al submenu
   }
}

void timer(){
  if (segundo>=60){
     segundo=0;
     minuto++;
  }
  if (minuto>=60){
     minuto=0;
     hora=hora+1;
  }
  if(hora>=24){
     hora=0;
  }
  //ACCIONES cada 10 segundos (impresion de pantalla)
  if((segundo==0)||(segundo==10)||(segundo==20)||(segundo==30)||(segundo==40)||(segundo==50)){
     calcula_temperatura();
     programacion(); //programacion de alimento y luces
     estadoagua();   //revision de nivel de agua, temperatura y ph
     if((err==0)&&(menu==0)){ //si no hay errores o menu imprimimos esto
        display_hora();//ok,
     }
     if (err!=0)display_mensajes_error();
     if ((err==0)&&(menu>=1))display_menu();

 }
}


void interrupt() {
//encendemos led al apretar un menu
if((PORTD.F0==1)||(PORTD.F1==1)||(PORTD.F2==1)||(PORTD.F3==1)||(PORTD.F4==1)){
   PORTC.F3=1;
}else{
   PORTC.F3=0;
}

  cnt++;
  if(cnt==10){
     segundo++;
     cnt=0;}               // Con una interrupción la cnt se incrementa en 1
  TMR0 = 0;           // El valor inicial se devuelve en el temporizador TMR0
  INTCON = 0x20;       // Bit T0IE se pone a 1, el bit T0IF se pone a 0
 
if (PORTD.F0==1)lastbut=1; //[MENU]
if (PORTD.F1==1)lastbut=2; //[arriba]
if (PORTD.F2==1)lastbut=3; //[abajo]
if (PORTD.F3==1)lastbut=4; //[atras]
if (PORTD.F4==1)lastbut=5; //[select]

if ((lastbut==1)&&(PORTD.F0==0)) boton=1; //MENU    activo el boton EN 1 de que se SOLTO
if ((lastbut==2)&&(PORTD.F1==0)) boton=1; //ARRIBA
if ((lastbut==3)&&(PORTD.F2==0)) boton=1; //ABAJO
if ((lastbut==4)&&(PORTD.F3==0)) boton=1; //ATRAS
if ((lastbut==5)&&(PORTD.F4==0)) boton=1; //SELECT

if (boton==1)select_menu();//cuando se suelte el boton ejecutamos la bandera del menu
}

void main() {
//Grabamos EEPROM
//LUCES
EEPROM_Write(0x32, 8);//hora encendido luces     8
EEPROM_Write(0x33, 0);//minuto encendido luces   0
EEPROM_Write(0x34, 21);//hora apagado luces        21
EEPROM_Write(0x35, 30);//minuto apagado luces      30
////TEMPERATURA
EEPROM_Write(0x36, 25);//grado temperatura        25
EEPROM_Write(0x37, 0);//miligradotemperatura      0
EEPROM_Write(0x38, 27);//temperatura maxima        27
EEPROM_Write(0x39, 23);//temperatura minima        23
//ALIMENTO
EEPROM_Write(0x3A, 8);//hora alimento1          8
EEPROM_Write(0x3B, 10);//minuto alimento1        10
EEPROM_Write(0x3C, 14);//hora alimento2           14
EEPROM_Write(0x3D, 30);//minuto alimento2         30
EEPROM_Write(0x3E, 20);//hora alimento3           20
EEPROM_Write(0x3F, 0);//minuto alimento3          0
//PH
EEPROM_Write(0x40, 7);//ph unidad                 7
EEPROM_Write(0x41, 0);//ph decimal                0
EEPROM_Write(0x42, 3);//ph tolerancia decimal    3

Delay_ms(100);
LeeEEPROM();

//CONFIGURACION DE PUERTOS E/S
  TRISA=0x0;   //PUERTO A SALIDA
  //TRISB=0x0; //PUERTO D PARA LCD
  TRISC=0x00;  //PUERTO C PARA ACTUADORES SALIDAS
  TRISD=0xFF;  //PUERTO D PARA TECLADO
  //CONFIGURACION DE A/D
  ANSEL=0x06; //CONFIGURAMOS AN0=pulso AN1 temp  AN2=PH,
  ANSELH=0;
  //CONFUGIRAMOS ESTADO NORMAL DE PINES
  PORTA=0x00;  //PONEMOS EN BLANCO LOS SENSORES
//  PORTB=0x00;  //PONEMOS EN BLANCO EL LCD
  PORTC=0x00;  //PONEMOS EN BLANCO OS ACTUADORES
  PORTD=0x00; //PONEMOS EN BLANCO EL TECLADO

  OPTION_REG = 0x84;   // Pre-escalador se le asigna al temporizador TMR0

  TMR0=0; //se pone el timer en 0
  INTCON = 0xA0;         //interrupcion global habilitada
 
  Lcd_Init();               // Inicializar el LCD
  Lcd_Cmd(_LCD_CLEAR);      // Borrar el LCD
  Lcd_Cmd(_LCD_CURSOR_OFF); // Apagar el cursor

 Delay_ms(10);

 while(1){
     timer();
     Delay_ms(10);
         
  }
}