4×4 keypad interfacing using ATMEGA328p

#include <avr/io.h>
#include <util/delay.h>

#define KeypadDDR DDRD
#define KeypadPortControl PORTD
#define KeypadPinValue PIND

#define LedDDR DDRC
#define LedPortControl PORTC

void KeypadScan()
{
 
  _delay_ms(10);

  //Set Cols as INPUT and ROWS as OUTPUT
  KeypadDDR = 0b11100000;         _delay_ms(1);
  KeypadPortControl = 0b00011111; _delay_ms(1);

  //scan the keypad
  uint8_t keyPressCode = KeypadPinValue;

  if( keyPressCode == 0b00011011 ) //If C1 becomes LOW
  {
     //Set Cols as OUTPUT and ROWS as INPUT
     KeypadDDR = 0b00011100;          _delay_ms(1);
     KeypadPortControl = 0b11100011;  _delay_ms(1);

     //Read the input again
     keyPressCode = KeypadPinValue;
     
     if( keyPressCode == 0b11000011 ) LedPortControl = 0b00000001; //If R1 becomes LOW
     if( keyPressCode == 0b10100011 ) LedPortControl = 0b00000010; //If R2 becomes LOW
     if( keyPressCode == 0b01100011 ) LedPortControl = 0b00000100; //If R3 becomes LOW
   
  }

  if( keyPressCode == 0b00010111 ) //If C2 becomes LOW
  {
     //Set Cols as OUTPUT and ROWS as INPUT
     KeypadDDR = 0b00011100;          _delay_ms(1);
     KeypadPortControl = 0b11100011;  _delay_ms(1);

     //Read the input again
     keyPressCode = KeypadPinValue;
     
     if( keyPressCode == 0b11000011 ) LedPortControl = 0b00001000; //If R1 becomes LOW
     if( keyPressCode == 0b10100011 ) LedPortControl = 0b00010000; //If R2 becomes LOW
     if( keyPressCode == 0b01100011 ) LedPortControl = 0b00100000; //If R3 becomes LOW
   
  }
  
  _delay_ms(100);

  //turn off all lights
  LedPortControl = 0b00000000;
}

int main(void)
{
  //4x3 matrix keypad(Bit 1,2 are  unused)
   KeypadDDR         = 0b11100000;// Rows = 111 , Cols = 000
   KeypadPortControl = 0b00011111;// Rows = 000 , Cols = 111

   LedDDR         = 0b00111111;
   LedPortControl = 0b00000000; // quick led test OFF
   LedPortControl = 0b00111111; // 
   _delay_ms(100);
    while(1)
    {
      KeypadScan();
    }//while
  return 0;
}

About PraveenMax
My Interests: ------------------ Programming , Drawing & Music

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: