// AUTHOR : KARTHIKH AMARAN
// THIS PROJECT WAS BUILT FOR INTERFACING KEYPAD AND 7 SEGMENT DISPLAY WITH ARDUINO MEGA
// WIHTOUT USING ANY INBUILT FUNCTIONS AND LIBRARIES

// AIM OF THE PROJECT
// INPUTS: PRESSING THE NUMBER SWITCHES IN KEYPAD
// OUTPUT: DISPLAYING THE CORRESPONDING PRESSED NUMBER IN A SEVEN SEGMENT DISPLAY

//**********************************************************

//CODE:

#define DELAY 100000
void init_port();
void outf(char w);
void outk(char x);
void outa(char y);
//void outc(unsigned char z){ volatile unsigned char *outc; outc = 0x28; *outc = z;}
char inb(void);
void outl(unsigned char l);
void delay1(char count);
void setup() 
{
  init_port();
  p1();
}

void p1()
{ 
  volatile unsigned char i,nums[11]={0x3f,0x06,0x5b,0x4f,0x66,0x6d,0x7d,0x07,0x7f,0x6f,0x00};
  while(1)
  { 
   for(i=0;i<4;i++)
  {
    outl(1<<i);
    if(inb() != 0)
    {
      switch(i)
      {
      case 0: switch(inb()){ case 1: outf(nums[1]); break; case 2: outf(nums[2]); break; case 4: outf(nums[3]); break;} break;

      case 1: switch(inb()){ case 1: outf(nums[4]); break; case 2: outf(nums[5]); break; case 4: outf(nums[6]); break;} break;

      case 2: switch(inb()){ case 1: outf(nums[7]); break; case 2: outf(nums[8]); break; case 4: outf(nums[9]); break;} break;

      case 3: switch(inb()){ case 2: outf(nums[0]); break;} break;
      }
      delay1(5);
    }
    //delay1(5);
    outk(nums[10]); outf(nums[10]);
  }
  }
}



//*************************************************************************
//*************************INITIALIZATION FUNCTIONS************************
//*************************************************************************

void init_port(){
  volatile char *dira,*dirc,*dirf,*dirk,*dirb = 0x24,*dirl = 0x10a;
  dira = 0x21; dirc = 0x27; dirf = 0x30; dirk = 0x107;
  *dira = 0xff; *dirc = 0xff; *dirf = 0xff; *dirk = 0xff,*dirb = 0x00,*dirl = 0xff;
}

void outf(char w){ volatile char *outf; outf = 0x31; *outf = w;}
void outk(char x){ volatile char *outk; outk = 0x108; *outk = x;}
void outa(char y){ volatile char *outa; outa = 0x22; *outa = y;}
void outc(unsigned char z){ volatile unsigned char *outc; outc = 0x28; *outc = z;}
char inb() { volatile char *inb; inb = 0x23; return *inb;}
void outl(unsigned char l){ volatile unsigned char *outl; outl = 0x10b; *outl = l; }
void delay1(char count)
{ volatile unsigned long i; 
while (count)
{
   for(i=0;i<DELAY;i++); // TO GIVE DELAY
   count--;
}
}

void loop() {
  // put your main code here, to run repeatedly:

}