Very simple matrix scanning program of 51 single chip microcomputer

Time:2020-12-20
/*Key position definition of key*/
unsigned char code anj[4][4] = {
	1,	2,	3,	10,
	4,	5,	6,	11,
	7,	0,	9,	12,
	13,	8,	14,	15,
};

char ScanKey()
{
        Char key = - 1; // the assignment is used to judge if the key is not pressed
	unsigned i,j;
	for (i = 0;i < 4;i++)
	{
		P1 = _cror_(0x7f,i);
		for (j = 0;j < 4;j++)
		{
			if ((P1 & _cror_(0x08,j)) == 0)
			{
				key = anj[i][j];
				while ((P1 & _ cror_ (0x08, J)) = = 0); // let go detection
				break;
			}
		}
	}
    return key;
}
Principle:
For example, the high position is the row, and the low position is the column
Copy 0111 1111 for P1 first
Then & 0000 1000
If the first column is pressed, then 
  0111 1111
&0000 0000 (press 0000 1000 to change to 0000 0000)
= 0000 0000  
Naturally, the key to (1,1) is pressed and the right shift (_ cror_ () and so on, and all the buttons can be detected.