sbit LCD_RS at RD4_bit;
sbit LCD_EN at RD5_bit;
sbit LCD_D4 at RD0_bit;
sbit LCD_D5 at RD1_bit;
sbit LCD_D6 at RD2_bit;
sbit LCD_D7 at RD3_bit;

sbit LCD_RS_Direction at TRISD4_bit;
sbit LCD_EN_Direction at TRISD5_bit;
sbit LCD_D4_Direction at TRISD0_bit;
sbit LCD_D5_Direction at TRISD1_bit;
sbit LCD_D6_Direction at TRISD2_bit;
sbit LCD_D7_Direction at TRISD3_bit;

#define ENCODER_A PORTB.RB6        // Encoder A Pin
#define ENCODER_B PORTB.RB5        // Encoder B Pin

unsigned char    encoder_counter=0;    // Used to control brightness of LED, values 0 to 25 (we dont need 250 increments)
unsigned char    encoder_A;
unsigned char    encoder_B;
unsigned char    encoder_A_prev=0;

void init(){
  Lcd_Init();                                    // Initialize LCD
  Lcd_Cmd(_LCD_CLEAR);                           // Clear LCD
  Lcd_Cmd(_LCD_CURSOR_OFF);                      // Turn cursor off
}

void interrupt(){
if (INTCON.T0IF)
    {
        encoder_A = ENCODER_A;
        encoder_B = ENCODER_B;

        if((!encoder_A) && (encoder_A_prev)){

            // A has gone from high to low
            if(encoder_B) {
                // B is high so clockwise
                if(encoder_counter<25)    encoder_counter++;
            }
            else {
                // B is low so counter-clockwise
                if(encoder_counter>0) encoder_counter--;
            }
        }
        encoder_A_prev = encoder_A;     // Store value for next time
        TMR0 = 178;                    // 200 Hz
        INTCON.T0IF = 0;          // Clear interrupt flag
    }
}
void Main(){
ANSEL  = 0;                                    // Configure AN pins as digital I/O
  ANSELH = 0;
  C1ON_bit = 0;                                  // Disable comparators
  C2ON_bit = 0;
  TRISB = 1;
  TRISA = 0;
  OPTION_REG = 0X07;
  INTCON.T0IE = 1;
  INTCON.GIE = 1;
  init() ;
          Lcd_Out(1, 1, " Menu  ");
          while(1){
  switch(encoder_counter){
  case 1: init() ;
          Lcd_Out(1, 1, " Menu 1  ");
  break;
  case 2: init() ;
          Lcd_Out(1, 1, " Menu 2 ");
  break;
  case 3: init() ;
          Lcd_Out(1, 1, " Menu 3 ");
  break;
  case 4: init() ;
          Lcd_Out(1, 1, " Menu 4 ");
  break;
  }
 }
}