Matrix keyboard scanning c program

Publisher:jingyanLatest update time:2016-11-09 Source: eefocus Reading articles on mobile phones Scan QR code
Read articles on your mobile phone anytime, anywhere
Each key is connected at both ends, horizontally and vertically. For example, if the scan code is input vertically, it means that the scan code received in that row is the same bit, while the scan code is read horizontally. The scanning action is to input the scan code first and then read the input value. After comparison, you can know which key is pressed.

比如说扫描码送入01111111,前面的0111是代表此时扫描第一行P1.0列,而后面的1111是让读取的4行接脚先设為VDD,若此时第一行的第三列按键被按下,那读取的结果就会变成01111101(注意1111变成1101),其中LSB的第三个bit会由1变成0,这是因為这个按键被按下之后,会被垂直的扫描码电位short,而把读取的LSB的bit电位拉到0,此即為扫描原理。

* describe: *   

* Matrix keyboard digital tube displays key values ​​*   

*                                                                              *   

* Matrix keyboard definition: *

* P1.0-P1.3 are column lines, P1.4-P1.7 are row lines *   

* Speaker connected to P3.7 port matrix keyboard P1 port, digital tube data P0 port, digital tube control P2 port *   

*                                                                              *                           

#include

#include

                

#define uchar unsigned char

#define uint unsigned int

uchar table[17]= {0x28,0x7e,0xa2,0x62,0x74,0x61,0x21,0x7a,0x20,0x60,0x30,0x25,0xa9,0x26,0xa1,0xb1}; //digital tube code

sbit BEEP = P3^7; //Buzzer drive line

uchar dis_buf; //display cache

flying tempo;

uchar key; //key order

void beep(); //Buzzer

void delay0(volatile x); //x*0.14MS

//--------------------------------------------------

/* Delay subroutine */

void delay(fly x)

{ fly j;

    while((x--)!=0)

    { for(j=0;j<125;j++)

         {;}

    }

}

//--------------------------------------------------

/*Key scan subroutine*/

void keyscan(void)

{

    P1=0x0F; //lower four bits input

    delay(1);

temp=P1; //Read P1 port

    temp=temp&0x0F;

    temp=~(temp|0xF0);

    if(temp==1)

        key=0;

    else if(temp==2)

        key=1;

    else if(temp==4)

        key=2;

    else if(temp==8)

        key=3;

    else

        key=16;

       

    P1=0xF0; //high four bits input

    delay(1);

temp=P1; //Read P1 port      

    temp=temp&0xF0;

    temp=~((temp>>4)|0xF0);

    if(temp==1)

        key=key+0;

    else if(temp==2)

        key=key+4;

    else if(temp==4)

        key=key+8;

    else if(temp==8)

        key=key+12;

    else

        key=16;

   

     dis_buf=table[key]; //Look up the table to get the key value

}

//--------------------------------------------------

/* Check if the key is pressed */

void keydown(void)

{

P1=0xF0;

if(P1!=0xF0)

{

   keyscan();

   beep();

     // while(P1!=0xF0); // Wait for key release

}

}

//--------------------------------------------------

void beep()

{

unsigned char i;

for (i=0;i<100;i++)

   {

   delay0(4);

   BEEP=!BEEP;       //BEEP取反

   }

   BEEP=1; //Turn off the buzzer

   delay(250); //delay    

}

//--------------------------------------------------

void delay0(volatile x) //x*0.14MS

{

unsigned char i;

while(x--)

{

for (i = 0; i<13; i++) {}

}

}

//--------------------------------------------------

    main()

{

    P0=0xFF; //Set P0 port

    P2=0xFF; //Set P2 port

    dis_buf=0xBF;

   

    while(1)

    {

       keydown();

    P0 = dis_buf; //key value sent to display

       delay(2);

       P2 = 0x7F;

    }

}  

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#include

#define uchar unsigned char

#define uint unsigned int

sbit key0=P1^0;

sbit key1=P1^1;

sbit key2=P1^2;

sbit key3=P1^3;

sbit key4=P1^4;

sbit key5=P1^5;

sbit key6=P1^6;

sbit key7=P1^7;

void key_judge(void)

{ uchar keyvalue=0; //Set the key variable, initialize it to 0 to indicate no key is pressed

keyvalue=P1&0xFF; //Get the key value

while (keyvalue!=0xff) //If the key is pressed

   {

     delay(1000); //Software delay debounce

     if((keyvalue&P1)!=0xff) //It is indeed pressed

       {

         while((keyvalue^P1)!=0x0) //Wait for the key to be released

         delay(500);

         switch(keyvalue)

            {

              case 0xfe: managekey0();break;

              case 0xfd: managekey1();break;

              case 0xfb: managekey2();break;

              case 0xf7: managekey3();break;

              case 0xef: managekey4();break;

              case 0xdf: managekey5();break;

              case 0xbf: managekey6();break;

              case 0x7f: managekey7();break;

              default:    break;

            }

         keyvalue=0; //Reinitialize the key value and exit the loop

       }

     keyvalue=P1&0Xff; //If it is a false action, continue to query and wait for the next round of key presses

   }

}

void managekey0(void)

{

}

void delay(uint n)

{ uint i;

for(i=0;i

}

void main(void)

{

//initialization

while(1)

{

key_judge( );

for(;);

{ //Other programs

}

}

}

/*Now modify this student's program*/

bit keyjudge(void)

{ // fly KeyV;

    float KeyV1;

// float tmp;

    KeyV1=0xf0;

    P1=KeyV1;

if((P1&0xf0)!=0xf0)

// return(0); Modification

    delay(1000);

//mling(12);

if((P1&0xf0)!=0xf0)

    return(1);

else

    return(0);

}

   

uchar kbscan(void) /*key scan*/

{ bit flag1;

flag=keyjudge(void);

if(flag1==1)

     { while ((P1&0xf0)==0xf0) //Button released?

         {

         //The key scan value can be stored here

         }

     }

   else

    return(0); //0 means no key is pressed

}

/*   

The following paragraph is a bit dizzy

else

{ for(a=0;a<4;a++)

      { tmp=P3;

         tmp=0xfe;

         KeyV=_crol_(tmp,a);

         if(P34==0)

           { KeyV=P3;

             break;}

         if(P35==0)

           { KeyV=P3;

             break;}

         if(P36==0)

           { KeyV=P3;

             break;}

         if(P37==0)

           { KeyV=P3;

             break;}

       }

     for(;;)

       {if((tmp&0xf0)==0xf0)

          break;}

     return(KeyV);

}

}

*/

1. Key scanning (line inversion)

//-------------------------------- ------------------------------------------------------------------

// Function name: program_SCANkey

// Function: The program scans the keyboard,

// Complete key processing if a key is pressed, return directly if no key is pressed

//--------------------------------------------------------------------------------------------------

void program_SCANkey()

{

unsigned char key_code;

          if(judge_hitkey()) //Judge whether a key is pressed

{

              delay(1000); //Delay about 20ms to eliminate jitter interference

              if(judge_hitkey()) //Judge whether the key is valid

   {

                  key_code=scan_key(); //Get the key value

             while(judge_hitkey()); //Wait for the key to be released

        {

         }

                  key_manage(key_code); //Keyboard scanning, keyboard rotation, key processing

       }

}

}

//--------------------------------------------------------------------------------------------------

// Function name: judge_hitkey

// Function: // Check if a key is pressed, return 1 if yes, return 0 if no

// Column judgment, you can also use row judgment.

//--------------------------------------------------------------------------------------------------

bit judge_hitkey() //Judge whether a key is pressed, return 1 if yes, return 0 if no

{

unsigned char scancode,keycode;

scancode=0x0F; //Start setting P1.0~P1.3 outputs are all 1 (initial value), which means no key is closed

KEY=scancode;          

keycode=KEY; //Read the real status of P1.0~P1.3 to determine whether any key is pressed

if(keycode==0x0F)

      return(0); //All 1 means no key closed

else

           return(1); //Otherwise there is a key closed

}

//--------------------------------------------------------------------------------------------------

// Function name: scan_key

// Function: //Scan the keyboard and return the key value (the upper four bits represent the row, the lower four bits represent the column)

// Description: scancode scan code, keycode key value, keycode_line row, keycode_row column

// Process: First scan the row to determine which row's key is pressed. Then scan the column to determine which column's key is pressed, and thus determine which key is pressed.

//--------------------------------------------------------------------------------------------------

unsigned char scan_key() //Scan the keyboard and return the key value (the upper four bits represent the row, the lower four bits represent the column)

{

         unsigned char scancode,keycode,keycode_line,keycode_row;

    scancode=0xF0; //Set the column to low and the row to high

    KEY = scancode; //Enter scan code, scan line

    keycode_line=KEY; //The value of KEY is the status value of P connected to the keyboard. If no key is pressed, the value of KEY is 0xF0. If a key is pressed, the value of KEY is not 0xF0.

   

    scancode=0x0F; //Set the column to high and the row to low

    KEY=scancode; //Enter the scan code and scan the column

    keycode_row=KEY; //The value of KEY is the status value of P connected to the keyboard. If no key is pressed, the value of KEY is 0x0F. If a key is pressed, the value of KEY is not 0x0F.

         keycode = ((keycode_line&0xF0)|(keycode_row&0x0F));

         return(keycode);

}

2. Key scanning (progressive scanning)

//--------------------------------------------------------------------------------------------------

// Function name: kbscan keyboard scanning subroutine

// Function: Determine whether a key is pressed, return the key value if yes, otherwise return 0

// The upper four bits of p1 are columns, and the lower four bits are rows P1.7 P1.6 P1.5 P1.4 P1.3 P1.2 P1.1 P1.0

// Column 4 Column 3 Column 2 Column 1 Row 4 Row 3 Row 2 Row 1

// Process: First determine whether a key is pressed based on the column. If not, return 0. If yes, scan row by row to determine the row where the key is located, and then determine the column where the key is located

// This finally determines the key.

//--------------------------------------------------------------------------------------------------

fly kbscan(void)

{

uchar sccode,recode;

P1=0xf0; //Set all lines to low level, row scan, column line input (at this time)

if((P1&0xf0)!=0xf0) //Judge whether a key is pressed (read the real status of the column. If a key is pressed in the 4th column, the value of P1 will become 0111 0000).

{

        delays(); //Delay debounce (10ms)

        if((P1&0xf0)!=0xf0) // Check if there is interference signal in the column again, if not, execute below

          {

           sccode=0xFE; // Scan the initial value line by line (i.e. scan the first line first)

           while((sccode&0x10)!=0) //When the row scan is completed (i.e. all 4 rows have been scanned), sccode is 1110 1111, stop while     

             {

                   P1=sccode; //Output line scan code

                 if ((P1&0xf0)!=0xf0) //A key is pressed in this row (i.e. the upper four bits of P1 (real status) are not all 1)

                       {

                          recode=(P1&0xf0)|0x0f; //column

                           return(sccode&recode); //Return rows and columns

                       }

               else //If no key is pressed in the scanned row, scan the next row until all 4 rows are scanned. At this time, the sccode value is 1110 1111 Exit while program

                      {

                            sccode=(sccode<<1)|0x01; //Scan code shifted left by one position

                       }

              }

           }

       }

       else

            {

              return 0; //No key is pressed, return 0

            }

}

--------------------------------------------------------------------------------------------------------------------------

/*Main.c*/

#include "global.c"

void SystemInit();

void Timer1Init();

void KickDog();

void delay();

unsigned int judge_key();

unsigned int scan_key();

unsigned char numkey=0;

unsigned char DATX,DATY;   

main()

{  

    SystemInit(); //System initialization

   

    MCRA=MCRA & 0x80FF; //IOPB0-6 is set to IO port mode

    PBDATDIR=0xBFC2; //All LEDs=0, and set IOPB6 as input port

   

    Timer1Init(); //Timer initialization

    asm(" CLRC INTM ");

    while(1)

    {

     // KeyLed();

if(judge_key()==1)

numkey++;

    }

   

}

void SystemInit()

{  

asm("SETC INTM"); /* Disable total interrupt*/

asm("CLRC SXM"); /* Disable sign extension*/

asm(" CLRC CNF "); /* Block B0 is mapped as on-chip DARAM*/

asm("CLRC OVM"); /* Accumulator result overflows normally*/

SCSR1=0x83FE; /* System clock CLKOUT=20*2=40M */

WDCR=0x006F; /* Disable watchdog, watchdog clock divided by 64*/

KickDog(); /* Initialize watchdog */  

     IFR=0xFFFF; /* Clear interrupt flag*/

     IMR=0x0002; /* Enable interrupt 2*/      

    

}  

void Timer1Init()           

{

     EVAIMRA=0x0080; //Timer 1 periodic interrupt enable

     EVAIFRA=0xFFFF; // Clear interrupt flag

     GPTCONA=0x0000;

T1PR=2500; // Timer 1 initial value, timing 0.4us*2500=1ms    

T1CNT=0;

T1CON=0x144E; //Increase mode, TPS coefficient 40M/16=2.5M, T1 enabled

    

}  

unsigned int judge_key()

{

MCRC=MCRC&0x81FF;    //

PFDATDIR=PFDATDIR|0x0070;

PFDATDIR=PFDATDIR&0x8FFF; //Set 456 input high

PFDATDIR=PFDATDIR&0xFFF1;

PFDATDIR=PFDATDIR|0x0E00; //Set 123 output low

if((PFDATDIR&0x0070)==0x0070)

      return(0);

else

      return(1);

}

unsigned int scan_key()

{

if(judge_key()==1)

   delay();

if(judge_key()==1)

   {

      MCRC=MCRC&0x81FF;    //

    PFDATDIR=PFDATDIR|0x0070;

    PFDATDIR=PFDATDIR&0x8FFF; //Set 456 input high

   

    PFDATDIR=PFDATDIR&0xFFF1;

    PFDATDIR=PFDATDIR|0x0E00; //Set 123 output low  

       delay();

       

       numkey=((PFDATDIR&0x0070)|(PFDATDIR&0x000E));

   // delay();

  

  

    //MCRC=MCRC&0x81FF;    //

          PFDATDIR=PFDATDIR&0xFF8F; //Set 456 output low

    PFDATDIR=PFDATDIR|0xE000;

          PFDATDIR=PFDATDIR|0x000E; //Set 123 input high

    PFDATDIR=PFDATDIR&0xF1FF;

    delay();

   

   // numkey=((PFDATDIR&0x0070)|(PFDATDIR&0x000E));

    numkey=numkey|(PFDATDIR&0x000E);

    return(numkey);

  

  

   }

}

 

void c_int2() /*Timer 1 interrupt service routine*/

{

     if(PIVR!=0x27)

   { asm(" CLRC INTM ");

    return;

   }

scan_key()   ;  

    

EVAIFRA=EVAIFRA&0x80;

asm(" CLRC INTM ");   

}  

void delay()

{

int i;

for(i=0;i<10000;i++);

}

void KickDog() /*Kick out the watchdog*/

{

WDKEY=0x5555;

WDKEY=0xAAAA;

Reference address:Matrix keyboard scanning c program

Previous article:Design of PS2 keyboard --- C51 program
Next article:C51 delay program re-throws the original

Latest Microcontroller Articles
  • Download from the Internet--ARM Getting Started Notes
    A brief introduction: From today on, the ARM notebook of the rookie is open, and it can be regarded as a place to store these notes. Why publish it? Maybe you are interested in it. In fact, the reason for these notes is ...
  • Learn ARM development(22)
    Turning off and on interrupts Interrupts are an efficient dialogue mechanism, but sometimes you don't want to interrupt the program while it is running. For example, when you are printing something, the program suddenly interrupts and another ...
  • Learn ARM development(21)
    First, declare the task pointer, because it will be used later. Task pointer volatile TASK_TCB* volatile g_pCurrentTask = NULL;volatile TASK_TCB* vol ...
  • Learn ARM development(20)
    With the previous Tick interrupt, the basic task switching conditions are ready. However, this "easterly" is also difficult to understand. Only through continuous practice can we understand it. ...
  • Learn ARM development(19)
    After many days of hard work, I finally got the interrupt working. But in order to allow RTOS to use timer interrupts, what kind of interrupts can be implemented in S3C44B0? There are two methods in S3C44B0. ...
  • Learn ARM development(14)
  • Learn ARM development(15)
  • Learn ARM development(16)
  • Learn ARM development(17)
Change More Related Popular Components

EEWorld
subscription
account

EEWorld
service
account

Automotive
development
circle

About Us Customer Service Contact Information Datasheet Sitemap LatestNews


Room 1530, 15th Floor, Building B, No.18 Zhongguancun Street, Haidian District, Beijing, Postal Code: 100190 China Telephone: 008610 8235 0740

Copyright © 2005-2024 EEWORLD.com.cn, Inc. All rights reserved 京ICP证060456号 京ICP备10001474号-1 电信业务审批[2006]字第258号函 京公网安备 11010802033920号