简体   繁体   中英

How do you convert binary 0001,0010,0100,1000 to 0,1,2,3 to index a 4x4 2D array?

I am reading key presses from a 4x4 keypad connected to a microcontroller but since a keypad is divided into rows and columns, it only reads 0001 or 1000 etc to specify row and column.

I have a character lookup table for the keypad in my main like:

char keys[4][4]={
        //       c3  c2  c1  c0
                {'1','2','3','A'},  //row4 PortA4 1000 

                {'4','5','6','B'},  //row3 PortA3 0100

                {'7','8','9','C'},  //row2 PortA2 0010

                {'*','0','#','D'}   //row1 PortA1 0001

                };

I want the inputs read from the keypad to be able to directly index this table and print out said character, but naturally, any number above 3 is out of bounds. I want to be able to use something like

printf("Key Pressed: %c",keys[indexrow][indexcolumn]);

but right now I have it hardcoded as follows:

...

while(1)
    {
        //begin polling
        row_data=0x01;//bottom row
        bus.IOWrite(PortA,row_data);
        column_data=b&bus.IORead(PortB);
        if((column_data & b)!=0)
        {
            //printf("Keypress detected @row %0b @column %0b",row_data,column_data);
            switch(column_data)
            {
                case 0x01:printf("Key Pressed: D");break;
                case 0x02:printf("Key Pressed: #");break;
                case 0x04:printf("Key Pressed: 0");break;
                case 0x08:printf("Key Pressed: *");break;
                default: break;
            }

        }
.
.
.

I suppose it could be simpler to just create an 8x8 table with lots of empty spaces within, but that would not be as pleasing to look at.

You switch statement could help you derive an index into your 2-dimensional array like this:

            switch(column_data)
            {
                case 0x01:column_index=0;break;
                case 0x02:column_index=1;break;
                case 0x04:column_index=2;break;
                case 0x08:column_index=3;break;
                default: /* probably needs handling here */ break;
            }

... but, what happens when more than one button is pressed.

You could write a code to convert the number format

# include <stdio.h>

int main()
{
  int numberToBeConverted = 0x08;
  int i,j;
  for(i=numberToBeConverted, j=1; i!=0;i/=2,j++)
  {
    if(i&1==1)
    {
      printf("%d\n",j);
      //Whatever you want to do with the key thats pressed
    }

  }
  return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM